How to import a private key into a java keystore


You cannot, but you can convert the private key and certificate into a java keystore. Below are the steps:

Step one: Convert x509 Cert and Key to a pkcs12 file

openssl pkcs12 -export -in server.crt -inkey server.key \
               -out server.p12 -name [some-alias] \
               -CAfile ca.crt -caname root

Note: Make sure you put a password on the p12 file – otherwise you’ll get a null reference exception when you try to import it. (In case anyone else had this headache). (Thanks jocull!)

Note 2: You might want to add the -chainoption to preserve the full certificate chain. (Thanks Mafuba)

Step two: Convert the pkcs12 file to a java keystore

keytool -importkeystore \
        -deststorepass [changeit] -destkeypass [changeit] -destkeystore server.keystore \
        -srckeystore server.p12 -srcstoretype PKCS12 -srcstorepass some-password \
        -alias [some-alias]