views:

109

answers:

2

Hello everyone I'm trying to convert a PKCS#8 private key that I generate in my java program to a PEM encoded file.

Security.addProvider(new BouncyCastleProvider());
SecureRandom rand = new SecureRandom();
JDKKeyPairGenerator.RSA keyPairGen = new JDKKeyPairGenerator.RSA();        
keyPairGen.initialize(2048, rand);
KeyPair keyPair = keyPairGen.generateKeyPair();

PEMWriter privatepemWriter = new PEMWriter(new FileWriter(new File(dir + "private.key")));
privatepemWriter.writeObject(keyPair.getPrivate());

After running the program I have the private key in both formats and a public key(the code isn't shown as it works). I then use this openssl command to conver the private.key back to a pem formated file.

openssl pkcs8 -nocrypt -inform DER -in private.key -out private2.pem

When I compare private.pem and private2.pem they are different and obviously when I try to use private.pem it says it's not a valid file.

What step am I missing in order to properly convert this private key into the PEM format that I need? I can't use OpenSSL from within my program, otherwise I would simply add that function call. I have access to BouncyCastle libs in this program, so maybe it has a solution I'm overlooking.

A: 
erickson
Yes what I want is to produce the OpenSSL key instead of the PKCS#8. I looked at the PEMWriter bellow, but I don't know if that will do what I need, given the conversion.
Hiro2k
Would it hurt you to try it out and see?
GregS
+1  A: 

You can use the PEMWriter class in Bouncycastle.

GregS
Thanks this worked out great and I was able to remove all of my redundant code! Reading the source code helped me figure out what objects to pass.http://www.java2s.com/Open-Source/Java-Document/Security/Bouncy-Castle/org/bouncycastle/openssl/PEMWriter.java.htm
Hiro2k
Yes, bouncycastle documentation is poor but the source code is very easy to read!
GregS