Wednesday, August 27, 2008

Creating a new JKS with an existing private key and a signed certificate

You have your own private key and a CA signed certificate - and now you want to import both the key and the certificate to a new JKS.

This is how we do it and you need to have OpenSSL installed.

For Windows you can download Win32 OpenSSL v0.9.8g from here.Once installed make sure you add C:\OpenSSL\bin [i.e [INSTALLED_LOCATION]\bin] to the PATH env variable.

If your key and certificate are in PEM format, then you need to convert them into DER format. [privateKey.pem & signedCert.pem]

:\> openssl pkcs8 -topk8 -nocrypt -in privateKey.pem -inform PEM -out privateKey.der -outform DER

:\>openssl x509 -in signedCert.pem -inform PEM -out signedCert.der -outform DER


Copy the resulted signedCert.der and privateKey.der to c:\keys.

Java keytool does not support a direct way of importing an existing private key to a new key store. So, we'll be doing it programmatically.

You can download the code from here and copy it to c:\keys.

c:\keys\>javac BuildJKS.java

c:\keys\>java BuildJKS privateKey.der signedCert.der mykeyalias MyJKS.jks keypassword storepassword


The above will create a JKS with the name MyJKS.jks and the key store password will be storepassword while the private key password is keypassword. Also the alias of the imported key is mykeyalias.

To verify that the JKS being created properly just issue the following command to list certificates stored in the key store.

c:\keys\>keytool -list -keystore MyJKS.jks -storepass storepassword

0 comments: