【问题标题】:How to convert X509 certificate into PKCS7 using bouncycastle?如何使用 bouncycastle 将 X509 证书转换为 PKCS7?
【发布时间】:2013-04-15 11:36:00
【问题描述】:

大家好!我的问题如下:我正在尝试将 X509 证书加密为 PKCS7,但我收到错误的结果。

第一次尝试是:(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());

...它不起作用。

第二次尝试是next(使用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();

我在这两种情况下都得到了错误的结果。 请帮助谁知道正确的方法。谢谢!

【问题讨论】:

    标签: java bouncycastle x509 pkcs#7


    【解决方案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();
        }
    
    

    【讨论】:

      猜你喜欢
      • 2015-07-21
      • 1970-01-01
      • 1970-01-01
      • 2018-11-15
      • 2021-03-28
      • 1970-01-01
      • 2021-03-09
      • 2019-04-30
      • 1970-01-01
      相关资源
      最近更新 更多