Pages

Thursday, 10 October 2019

import private key and certificate to a Java keystore

1. Surprise! JKS doesn't support importing a private key file

For a non-technical reason, JKS does NOT support importing private keys from files directly. It wants users to generate private keys inside it directly.

However, it's very common for users to generate private key files using OpenSSL. So it's necessary to find a way for importing private keys into a JKS Keystore.

Fortunately, there is one possible way to do that. 

2. Workaround: taking PKCS12 as a middle man

PKCS12 and JKS are two common file formats for saving key/certificates. Even if JKS has been replaced by PKCS12 from JAVA 9, it's still very common in production environments.

To import a private key to a JKS, the steps are:

  1. generating a PKCS12 file with the private key 
  2. importing the private key in PKCS12 file to JKS
Here is an example.

Step 1:

openssl pkcs12 -export \
   -in example.com.crt \
   -inkey example.com.key \
   -name example.com \
   -password pass:mypass1234 \
   -out example.com.p12


Note: pkcs12 uses the same password to encrypt the file itself and the private key inside the file.
It does NOT support separated passwords for the file and the private key inside.

Step 2:

keytool -importkeystore \
   -srckeystore example.com.p12 \
   -srcalias example.com \
   -srcstoretype PKCS12 \
   -srcstorepass mypass1234 \
   -srckeypass mypass1234 \
   -destkeystore keystore.jks \
   -destalias example.com \
   -deststoretype JKS \
   -deststorepass storepass5555 \
   -destkeypass storeKeypass6666

Note: JKS supports different passwords for the private key and Keystore file itself.

One tricky thing:

If "-destkeypass" is not provided, the private key will be encrypted with the password of source store PKCS12, rather than the "-deststorepass" provided.

This is a common error source as the pkcs12 is only for temporary use and we don't really care about its password. But actually, this password may be imported into JKS Keystore if we didn't provide "-destkeypass" to keytool.

No comments:

Post a Comment