Convert Certificates from Base64 (PEM) to Binary (DER)

Posted by Marcel Friedmann on 9:37 AM with No comments

Certificates

X.509-Certificates are encoded in a Base64 ascii format called PEM or in a binary formed called DER.

The PEM format is the most used format. PEM certificates typically have file extentions such as .pem and .crt, .cer.

A DER formatted certificate contains all the same information as an PEM certificate, however it's encoded in a binary way. DER certificates typically have file extentions such as .der and .cer.
Java Platforms often use the binary DER Format.
However WebSphere Application Server handls both formats. WebSphere stores its certificates in a p12-File located in the config folder. p12 (PKCS#12) files are certificate stores which can contain  certificates with private and public keys. p12 files are usually protected with a password.

When dealing with Java Keystores (JKS) converting of certificates and key files is necessary.

Converting Certificate formats

It is possible to convert this two certificate formats using tools like the java keytool or openssl.

Converting with openssl

Converting certificates with openssl is straight forward.

Converting from DER to PEM:
openssl x509 -in <der certificate file> -inform PEM
-out
<pem certificate file> -outform DER

Converting from PEM to DER:
openssl x509 -in <pem certificate file> -inform DER
-out
<der certificate file> -outform PEM

 

Converting with java keytool

The java keytool does not allow to directly convert certificates. However when creating a java keystore (JKS) first, certificates can be imported and exported in different formats.

Generate a keystore and delete the mandatory certificate in it:
When generating the keystore with the first command keytool demands several inputs for the mandatory certificate it will generate.We do not need this certificate for convertions and we will delete it afterwards -  so you could type in some foo. I will use the alias test in this example.
keytool -genkey -alias test -keystore <key store file>
keytool -delete -alias test -keystore <key store file>

Converting from DER to PEM:
keytool -import -trustcacerts -alias test -file <der certificate file>
-keystore test.keystore 
keytool -exportcert -alias test -file <pem certificate file> -rfc
-keystore 
test.keystore

Converting from PEM to DER:
keytool -import -trustcacerts -alias test -file <pem certificate file>
-keystore
test.keystore
keytool -exportcert -alias test -file <der certificate file>
-keystore 
test.keystore
Categories: ,