How do I list and export a private key from a keystore?
First call keytool -list -keystore myStore to know which alias to look for, then call this program with the passwords and parameters. In case of a private key entry, it shows the key itself and additionally a self-signed certificate which contains the public key, in a readable form.
Exporting the public key from a JSK is quite straightforward with the keytool utility, but exporting the private key is not allowed. Therefore, we need to get the support of the openssl utility for that. Additionally, you can write some custom Java code to get the private key extracted as well.
The private key entry is password protected. Generally, a JKS type of key store can have only one private key entry in a key store file.
You can extract a private key from a keystore with Java6 and OpenSSL. This all depends on the fact that both Java and OpenSSL support PKCS#12-formatted keystores. To do the extraction, you first use keytool
to convert to the standard format. Make sure you use the same password for both files (private key password, not the keystore password) or you will get odd failures later on in the second step.
keytool -importkeystore -srckeystore keystore.jks \ -destkeystore intermediate.p12 -deststoretype PKCS12
Next, use OpenSSL to do the extraction to PEM:
openssl pkcs12 -in intermediate.p12 -out extracted.pem -nodes
You should be able to handle that PEM file easily enough; it's plain text with an encoded unencrypted private key and certificate(s) inside it (in a pretty obvious format).
When you do this, take care to keep the files created secure. They contain secret credentials. Nothing will warn you if you fail to secure them correctly. The easiest method for securing them is to do all of this in a directory which doesn't have any access rights for anyone other than the user. And never put your password on the command line or in environment variables; it's too easy for other users to grab.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With