天天看點

java der 解碼_X.509證書的 Base64 和 DER 編碼

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

-inform PEM

-out  -outform DER

Converting from PEM to DER:

openssl x509 -in

-inform DER

-out  -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 aliastest

in this example.

keytool -genkey -alias test -keystore

keytool -delete -alias test -keystore

Converting from DER to PEM:

keytool -import -trustcacerts -aliastest -file

-keystore

test.keystore

keytool -exportcert -alias test

-file

-rfc

-keystore test.keystore

Converting from PEM to DER:

keytool -import -trustcacerts -aliastest -file

-keystore

test.keystore

keytool -exportcert -alias test

-file

-keystore test.keystore