如何使用BouncyCastle的X509证书转换为PKCS7?(How to convert X5

2019-10-18 00:26发布

大家好! 我的问题是以下内容:我试图加密X509证书PKCS7但是我收到一个错误的结果。

第一次尝试时:(使用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):

 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(); 

我得到在这两种情况下错误的结果。 请帮助谁知道做一个正确的方式。 谢谢!

Answer 1:

我找到了解决办法!

 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(); } 



文章来源: How to convert X509 certificate into PKCS7 using bouncycastle?