Note: [Mar 23, 2017] This website was migrated to a new platform recently. Some linked content may not be accessible until all the links are configured properly,

Exporting the private key from a jks file (Java keystore)

Submitted by Kamal Wickramanayake on June 18, 2008 - 18:08

Some seems to have used complicated mechanisms including writing new software to do so. Here's a simple approach:

1. Import the keystore from JKS to PKCS12

keytool -importkeystore -srckeystore mystore.jks -destkeystore mystore.p12 -srcstoretype JKS -deststoretype PKCS12 -srcstorepass mysecret -deststorepass mysecret -srcalias myalias -destalias myalias -srckeypass mykeypass -destkeypass mykeypass -noprompt

Note that the above command will generate a warning regarding '-destkeypass'. But if you omit that option, importing does not work properly (I tried in JDK 1.6.0_03).

2. Convert pkcs12 to pem using openssl

openssl pkcs12 -in mystore.p12 -out mystore.pem -passin pass:mysecret -passout pass:mysecret

That's it. Try 'cat mystore.pem'. You will see that both the private key and the certificate appears there.

If you are familiar with openssl and wish to use the private key to sign say another certificate, you can try the following:

openssl x509 -req -days 365 -in newclient.csr -CA mystore.pem -CAcreateserial -out newclient.cer -passin pass:mysecret -extfile openssl.cnf -extensions v3_usr

Note that here we assume the private key in mystore.pem is of a certificate authority (CA).

I didn't try the reverse of this. That is getting the private key in a pem file to a jks file. Hopefully, the same steps executed in reverse order (with the in/out options reversed) should work.