开发者

Convert a PKCS#8 private key to PEM in java

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开发者_StackOverflow中文版 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.


You can use the PEMWriter class in Bouncycastle.


The fact that OpenSSL uses it's own format is really the only thing that makes this challenging. Thankfully the bouncy castle PEMWriter makes this easy, but the interface isn't very well documented. I found some code by searching through the mailing list. I've adapted it below:

KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
keyGen.initialize(2048);
KeyPair keyPair = keyGen.generateKeyPair(); 
StringWriter stringWriter = new StringWriter();
PEMWriter pemWriter = new PEMWriter(stringWriter);  
pemWriter.writeObject( keyPair.getPrivate());
pemWriter.close();
privateKeyString = stringWriter.toString();


Use the header:

-----BEGIN PRIVATE KEY-----

… and the footer:

-----END PRIVATE KEY-----

Note that the "RSA" is left out—The Java code is using PKCS #8 encoding for the private key, and that encoding includes the algorithm.

The openssl command that you show is converting a standard PKCS #8 key in DER form to a proprietary OpenSSL key in PEM form. To keep the PKCS #8 format, but convert from DER to PEM, add the -topk8 option. Then the OpenSSL output should match what your Java code is producing.

If you need to produce the OpenSSL key, instead of PKCS #8, it's possible, but you'll have to create your own OpenSSL structure with the BouncyCastle ASN.1 library and encode that. Please clarify if that's what you need.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜