title: How to convert X509 certificate into PKCS7 using bouncycastle?
body: <p>Hi, all! My problem is following: I 'm trying to encrypt X509 certificate to PKCS7 but I receive a wrong result.</p>
  
  <p>The first attempt is:(used bcmail-jdk16:1.46)</p>
  
  <p><pre><code>
              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());
  
  </code></pre></p>
  
  <p>...and it doesn't work.</p>
  
  <p>The second attempt is next(used bcmail-jdk16-140):</p>
  
  <p><pre><code>
          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();
  </code></pre></p>
  
  <p>I get wrong results in both cases.
  Help please who know a right way to do it. Thanks!</p>