« At Last, A Wireless Bandwidth Solution | Main | JAXB2: Marshalling fails due to validation, but you can't see the error »

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.


TrackBack URL for this entry:


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):

$(kt6) -importkeystore -deststorepass "destpass" -srckeystore C.pkcs12.PW -srcstoretype PKCS12 -srcstorepass "srcpass"
$(kt) -list -v -storepass "destpass"

Thanks a lot for this tip. It was very useful to me, since I didn't want to mess with independent Java classes to achieve this. Better to have all in one single tool (or almost).

In case that it's of any help to someone, I followed the steps below.

First, I took the certificate and key in PEM format and, using openssl, I built a PKCS12 file:

openssl pkcs12 -export -in [my_certificate.crt] -inkey [my_key.key] -out [keystore.p12] -name [new_alias] -CAfile [my_ca_bundle.crt] -caname root

Then, I used the command explained by Graham in this message:

keytool -importkeystore -deststorepass [new_keystore_pass] -destkeypass [new_key_pass] -destkeystore [keystore.jks] -srckeystore [keystore.p12] -srcstoretype PKCS12 -srcstorepass [pass_used_in_p12_keystore] -alias [alias_used_in_p12_keystore]

On thing that seems to cause problems is the requirement for the PKCS12 file to be protected by a password - if it is created without a password, keytool crashes...

Post a comment

(If you haven't left a comment here before, you may need to be approved by the site owner before your comment will appear. Until then, it won't appear on the entry. Thanks for waiting.)