Importing private keys into a Java keystore using keytool
For ages the keytool application shipped as part of Java could provide all the functionality to generate a private key and certificate sign request from a Java keystore, but the most basic function, importing a preexisting private key and certificate generated externally, remained overlooked.
This is fixed in Java 6, at long last.
The solution is to convert your existing certificate and key into a PKCS12 file, and then use the keytool functionality to merge one keystore with another one. Java 6 can treat a PKCS12 file as a keystore, so putting this together, you get this:
keytool -importkeystore -deststorepass changeit -destkeypass changeit -destkeystore my-keystore.jks -srckeystore cert-and-key.p12 -srcstoretype PKCS12 -srcstorepass cert-and-key-password -alias 1
The alias of 1 is required to choose the certificate in the source PKCS12 file, keytool isn't clever enough to figure out which certificate you want in a store containing one certificate.
At last, it works.
Comments
Thank you for that. I was trying to import into a keystore using JDK 1.4.2 to no avail until I come across your post. The good news is that JDK 6 and JDK 1.4.2 uses the same file format. So, the following works in my Makefile (kt is set to 1.4.2 keytool, and kt6 is set to Java 6 keytool):
add2KS:
$(kt6) -importkeystore -deststorepass "destpass" -srckeystore C.pkcs12.PW -srcstoretype PKCS12 -srcstorepass "srcpass"
$(kt) -list -v -storepass "destpass"
Posted by: Lee Chia Ling | May 20, 2009 06:54 PM