HOW TO : Convert PFX/P12 crypto objects into a java keystore

We needed to add a certificate that is currently in PKCS#12 format currently into a java keystore at work recently. The typical step would be due to create an empty keystore and then import the certificate from the PKCS#12 store using the following command

[code]keytool -importkeystore -srckeystore sourceFile.p12 -srcstoretype PKCS12 -destkeystore destinationFile.jks[/code]

Note: PKCS#12 files can have extensions “.p12” or “.pfx”

The command executed without any issues, but we received the following error when we started the application server using this newly created keystore

[code] Error initializing server socket factory SSL context: Cannot recover key [/code]

It didn’t make sense, because we were able to view the certificate in the keystore and were using the right password in the configuration files.

After a lot of searching and head scratching, the team came up with the following solution

  1. Export the public key and private key from the PKCS#12 store using openssl.
  2. Import these keys into the java keystore (default format of JKS)

The commands used were

openssl pkcs12 -in sourcePKCS12File.p12 -nocerts -out privateKey.pem
openssl pkcs12 -in sourcePKCS12File.p12 -nokeys -out publicCert.pem
openssl pkcs12 -export -out intermittentPKCS12File.p12 -inkey privateKey.pem -in publicCert.pem
keytool -importkeystore -srckeystore intermittantPKCS12File.p12 -srcstoretype PKCS12 -destkeystore finalKeyStore.jks

2 Replies to “HOW TO : Convert PFX/P12 crypto objects into a java keystore”

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.