Friday 15 February 2013

Convert a openssl PEM RSA key to java keystore

Starting from jdk6, keytool allows importing pkcs12 bundles. The pkcs12 bundle includes key, certificate and CA chain so it is possible to require a certificate with openssl than using it with activemq, or other java projects.

The procedure is outlined the jetty ssl page, but there is a important point to note.

The keystore is password protected with the password set during keystore creation. The private key is password protected with the export password typed in openssl pkc12 command.

If a tool doesn't allow to specify both password, they must be the same.

The case is the activemq sslContext, which reads:

<sslContext>
                <sslContext 
                        keyStore="ateneo.store" keyStorePassword="bluehorror"
                        trustStore="client.ks" trustStorePassword="password"/>
        </sslContext>
The trick is to issue a keytool -keypasswd to align password. Failing to do that results in a:
Exception in thread "main" java.security.UnrecoverableKeyException: Cannot recover key
 at sun.security.provider.KeyProtector.recover(KeyProtector.java:311)
 at sun.security.provider.JavaKeyStore.engineGetKey(JavaKeyStore.java:121)
 at sun.security.provider.JavaKeyStore$JKS.engineGetKey(JavaKeyStore.java:38)
 at java.security.KeyStore.getKey(KeyStore.java:763)
Thanks to http://www.xinotes.org/notes/note/1395/

In case you want to follow the single steps, have a look at the puppet module to automatize certs export to keystore: https://github.com/francescm/certs