如何使用Bouncycastle将X509证书转换为PKCS7? [英] How to convert X509 certificate into PKCS7 using bouncycastle?
本文介绍了如何使用Bouncycastle将X509证书转换为PKCS7?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
大家好!我的问题如下:我试图将X509证书加密为PKCS7,但是收到错误的结果。
Hi, all! My problem is following: I 'm trying to encrypt X509 certificate to PKCS7 but I receive a wrong result.
第一次尝试是:(使用了bcmail-jdk16:1.46)
The first attempt is:(used bcmail-jdk16:1.46)
Security.addProvider(new BouncyCastleProvider());
keystore = KeyStore.getInstance("PKCS12", "BC");
keystore.load (new FileInputStream(PATH+"//pkcs7-csr-cer//identity.p12"), "testpassword".toCharArray());
PrivateKey privateKey = (PrivateKey)keystore.getKey("testclientcert", "testpassword".toCharArray());
CMSSignedDataGenerator signedDataGen = new CMSSignedDataGenerator();
signedDataGen.addSigner(privateKey, certificate, CMSSignedDataGenerator.ENCRYPTION_RSA, CMSSignedDataGenerator.DIGEST_SHA256);
CMSProcessableFile pkcs7 = new CMSProcessableFile(new File(destinationfile));
CMSSignedData signedData = signedDataGen.generate(pkcs7, true, "BC");
signedData = new CMSSignedData(pkcs7, signedData.getEncoded());
...这不起作用。
第二次尝试是下一次(使用bcmail-jdk16-140):
The second attempt is next(used bcmail-jdk16-140):
Security.addProvider(new BouncyCastleProvider());
CMSEnvelopedDataGenerator envDataGen = new CMSEnvelopedDataGenerator();
envDataGen.addKeyTransRecipient(certificate);
CMSProcessable sData = new CMSProcessableByteArray(certificate.getEncoded());
CMSEnvelopedData enveloped = envDataGen.generate(sData, CMSEnvelopedDataGenerator.AES256_CBC, "BC");
return enveloped.getEncoded();
在两种情况下我都得到错误的结果。
请帮助知道正确方法的人。谢谢!
I get wrong results in both cases. Help please who know a right way to do it. Thanks!
推荐答案
我找到了解决方案!
private byte[] encryptCertToPKCS7(X509Certificate certificate, Key key)
throws CertificateEncodingException, CMSException, NoSuchProviderException, NoSuchAlgorithmException, IOException, OperatorCreationException {
CMSSignedDataGenerator generator = new CMSSignedDataGenerator();
ContentSigner sha256Signer = new JcaContentSignerBuilder("SHA256withRSA").setProvider("BC").build((PrivateKey) key);
generator.addSignerInfoGenerator(new JcaSignerInfoGeneratorBuilder(new JcaDigestCalculatorProviderBuilder()
.setProvider("BC").build())
.build(sha256Signer, certificate));
generator.addCertificates(new JcaCertStore(certificates));
CMSTypedData content = new CMSProcessableByteArray(certificate.getEncoded());
CMSSignedData signedData = generator.generate(content, true);
return signedData.getEncoded();
}
这篇关于如何使用Bouncycastle将X509证书转换为PKCS7?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文