If there is one irritating, arcane issue about Java, it is their SSL and Crypto framework. It is a pile of mess. I remember using openssl as a library about 3-4 years ago in a project that was pretty crypto heavy and their library can be used by any junior developer – it’s that simple to use.
However, Java’s crypto framework is just absolutely irritating to use – tons of unnecessary boiler plate, and not enough of self discovery of file formats (as an example). Try to do SSL client certificate authentication from ground up and you’ll know what I mean. Knife, wrist – sound familiar ?
Last night, I had to convert some PEM formatted certificates and private keys to JKS (was getting SSL nicely configured under Jetty). I remember doing this a few years back and there were molehillsmountains of issues to jump across and I did pull my hair out back then. Last night was no different. However, I did manage to solve it and ended up with much less hair.
So, to save everyone else the trouble (and their hair!), I’m jotting down some notes here on how to convert a certificate and private key in PEM format into Java’s keystore and truststore in JKS format.
If we’re starting with PEM format, we need to convert the certificate and key to a PKCS12 file. We’ll use openssl for that:
Remember to use a password for the command below, otherwise, the Jetty converter (the following step) will barf in your face!
openssl pkcs12 -export -out cert.pkcs12 \ -in cert.pem -inkey key.pem
Once that’s done, you need to convert the pkcs12 to a JKS. Here, I will be using a small utility that comes bundled with Jetty called PKCS12Import. You can download the necessary library (you’ll need the main jetty.jar) which can be a huge download for such a small thing, or just grab the jar from here. Run the following command and use the password from the step above and your keystore password:
java -cp /path/to/jetty-6.1.7.jar \ org.mortbay.jetty.security.PKCS12Import \ cert.pkcs12 keystore.jks
Next, you’ll almost definitely need to import the certificate into your truststore whenever you need to do anything related to SSL.
First, export the certificate as a DER:
openssl x509 -in cert.pem -out cert.der -outform der
Then import it into the truststore:
keytool -importcert -alias mycert -file cert.der \ -keystore truststore.jks \ -storepass password
And that’s it! You have your key in the keystore, and your certificate in the truststore. Hope this helps some of you out there.