title: How to extract PKCS12 keystore(containing a keypair of pkcs#8 and a certificate)
body: <p>when the user provides keystore, usually the keystore contains a keypair(an RSA encrypted private key, x.509 certificate) and CA certificates.
  I want to extract the contents of keystore and write them in a different file.</p>
  
  <p>I am able to read the contents of certificates without any issue but when trying to read the key and write to file, the contents are in unecrypted form.</p>
  
  <p>How to write the contents of private key file in encrypted from itself?</p>
  
  <p>I have fetched the key and cert as below:</p>
  
  <pre><code>key = (PrivateKey)keyStore.getKey(keyAlias, password.toCharArray());
  cert = keyStore.getCertificate(keyAlias);
  </code></pre>
  
  <p>I also tried using bouncycastle.</p>
  
  <p>Using java libs:</p>
  
  <pre><code>PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(key.getEncoded());
  byte[] privatekey = encoder.encode(pkcs8EncodedKeySpec.getEncoded());
  </code></pre>
  
  <p>Using bouncycastle:</p>
  
  <pre><code> JceOpenSSLPKCS8EncryptorBuilder encryptorBuilder = new JceOpenSSLPKCS8EncryptorBuilder(PKCS8Generator.PBE_SHA1_RC2_128);  
   encryptorBuilder.setRandom(new SecureRandom());  
   encryptorBuilder.setPasssword("abcde".toCharArray()); // password  
   OutputEncryptor encryptor = encryptorBuilder.build();  
  
   JcaPKCS8Generator gen2 = new JcaPKCS8Generator(key, encryptor);  
   PemObject obj2 = gen2.generate();  
   StringWriter sw2 = new StringWriter();  
   try (JcaPEMWriter pw = new JcaPEMWriter(sw2)) {  
     pw.writeObject(obj2);  
   }  
   String pkcs8Key2 = sw2.toString();  
   FileOutputStream fos2 = new FileOutputStream(privateKeyLocation);  
   fos2.write(pkcs8Key2.getBytes());  
   fos2.flush();  
   fos2.close();  
  </code></pre>
  
  <p>when used plain java libs the content is decrypted and I may want to append the header and footer tags.</p>
  
  <p>When used bouncy castle, I got some data with in <code>-----BEGIN ENCRYPTED PRIVATE KEY-----</code> and <code>-----END ENCRYPTED PRIVATE KEY-----</code> but the content is not same as the original file. I also tried using different PKCS8Gnerator.algorithms to no use.</p>