Monthly Archives: September 2020

Import a SSL Key and Cert into a Java Keystore.

I have a X.509 certificate encoded in PEM and a SSL key also encoded in PEM. I need to import them into a Java keystore.

First, we need to create a PKCS#12 file which contains the SSL key and cert.

openssl pkcs12 -export -in <CER> -inkey <KEY> -name <ALIAS> -out <DOMAIN>-PKCS-12.p12

Then I use the following command to create the Java keystore:

keytool -importkeystore -deststorepass changeit -destkeystore <DOMAIN>-keystore.jks -srckeystore <DOMAIN>-PKCS-12.p12 -srcstoretype PKCS12

The alias used in the PKCS#12 file will be used in the Java keystore. You can change it with the following command:

keytool -changealias -alias <OLD_ALIAS> -destalias <NEW_ALIAS> -keystore <DOMAIN>-keystore.jks

Chain Certificate (SSL)

There are at least two ways to present a chain certificate. The easiest way is to create a file with multiple X.509 certificates in it. Start with your certificate, then follow with an intermediate CA cert or root CA cert. It usually has the file extension “.pem”. I use this approach for Apache HTTPD and NGINX.

-----BEGIN CERTIFICATE-----
...Your certificate in base64...
-----END CERTIFICATE-----
-----BEGIN CERTIFICATE-----
...Intermediate CA certificate in base64...
-----END CERTIFICATE-----

Another way, which I just found out, is to create a PKCS#7 file. It usually has the file extension “.p7b”.

-----BEGIN PKCS7-----
... Content in base64...
-----END PKCS7-----

For both of the above examples, the certificate data is encoded in base64. They can also be encoded in binary. For X.509 certificate, the file extension is usually “.der”. For PKCS#7, the same file extension “.p7b” is used. I prefer the base64 encoded version because I can just open the file and I’ll know what file I’m looking at (i.e. a key, a X.509 certificate or a PKCS#7 chain certificate). Using file extension is not reliable. To convert a PKCS#7 binary encoded certificate to base64 encoded:

openssl pkcs7 -text -inform der -in mysite_chain.p7b -outform pem -out mysite_chain.p7b

To convert a binary encoded X.509 certificate to base64 encoded:

openssl x509 -inform der -in mysite.der -outform pem -out mysite.pem

To convert a PKCS#7 chain certificate to a X.509 chain certificate:

openssl pkcs7 -print_certs -in mysite.p7b -out mysite.cer

If the PKCS#7 certificate is binary encoded:

openssl pkcs7 -print_certs inform der -in mysite.p7b -out mysite.cer