我在密钥库中创建了一个密钥对,并使用这一对,我想创建以下curl命令的Java等效代码。
openssl smime -sign -in req.xml -nointern -nodetach -nocerts -nochain -outform PEM \
-out req_signed.txt -signer you.cer -inkey private.key -passin pass:HIDDEN
我的Java方法如下:
public byte[] sign(boolean includeCerts) throws GeneralSecurityException, OperatorCreationException, CMSException, IOException {
try {
java.security.cert.Certificate[] certChain = KeyStoreUtil.getCertificateChainCombined(alias);
if (certChain == null || certChain.length < 1)
throw new GeneralSecurityException("Certificate chain was null or empty for alias \"" + alias + "\"");
List<java.security.cert.Certificate> certList = new ArrayList<java.security.cert.Certificate>();
for (int i = 0; i < certChain.length; i++)
certList.add(certChain[i]);
certs = CertStore.getInstance("Collection", new CollectionCertStoreParameters(certList), "BC");
priv = KeyStoreUtil.getPrivateKeyCombined(alias,"GwHwYQbeSLK6jES47wRR3fk1j");
storecert = KeyStoreUtil.getCertificateCombined(alias);
} catch (GeneralSecurityException gse) {
log.warn("Problem with keystore access: " + gse.toString());
throw gse;
}
if (log.isDebugEnabled()) {
log.debug("Private Key Format: " + priv.getFormat());
if (!Runmode.isLive()) {
log.debug("Certificate for alias \"" + alias + "\" (encoded):\n" + LogUtil.encryptForLog(storecert.toString().getBytes(Constants.C_ASCII)));
}
}
/*
* Signing based on code from http://i-proving.ca/space/Technologies/JCE/PKCS7+Signatures+using+Bouncy+Castle
*/
CMSSignedDataGenerator generator = new CMSSignedDataGenerator();
// Add signer info generator (actual signing will be done after)
ContentSigner sha256Signer = new JcaContentSignerBuilder("SHA1withRSA").setProvider("BC").build(priv);
DigestCalculatorProvider digestCalculatorProvider = new JcaDigestCalculatorProviderBuilder().setProvider("BC").build();
generator.addSignerInfoGenerator(new JcaSignerInfoGeneratorBuilder(digestCalculatorProvider).build(sha256Signer, (X509Certificate)storecert));
if (includeCerts) {
// Add certificates used for signing
List<X509Certificate> certificates = new ArrayList<X509Certificate>();
certificates.add((X509Certificate)storecert);
generator.addCertificates(new JcaCertStore(certificates));
}
// NOTE: IOUtils handles large files by copying bytes in blocks of 4MB
CMSTypedData content = new CMSProcessableByteArray(IOUtils.toByteArray(inputStream));
org.bouncycastle.cms.CMSSignedData signedData = generator.generate(content, true);
if (!Runmode.isLive()) {
if (log.isDebugEnabled()) {
String asn1Dump = ASN1Dump.dumpAsString(signedData.toASN1Structure(), true);
log.debug("CMSSignedData ASN.1 dump (encoded):\n" + LogUtil.encryptForLog(asn1Dump.getBytes(Constants.C_ASCII)));
}
}
return signedData.getEncoded();
}
但是OpenSSL和Java的输出是不同的。我做了很多搜索,但我无法到达任何地方。我想说我不熟悉数字签名。
我的代码有什么问题吗?我做错了什么?