Brief notes on TLS/SSL private keys and certificates, their various formats and converting them to different formats using OpenSSL.
- OpenSSL Commands: https://www.openssl.org/docs/man1.1.1/man1/ (current stable version - v1.1.1)
- OpenSSL Cookbook: https://www.feistyduck.com/books/openssl-cookbook/
- Public-key Cryptography Standards (PKCS): https://en.wikipedia.org/wiki/PKCS
- X.509 certificates filename extensions: https://en.wikipedia.org/wiki/X.509#Certificate_filename_extensions
- Java keytool: https://docs.oracle.com/javase/8/docs/technotes/tools/windows/keytool.html
- Keys and X.509 certificates are usually stored in PKCS formats.
- They can be converted to:
- Keys are usually stored as Base64 encoded
.pemfiles. - Keys can be generated and processed using following commands, depending on their type —
genrsa,rsa: RSA keys.gendsa,dsa: DSA keys.genpkey,pkey: Recommended for both RSA and DSA keys.
- In OpenSSL 3.0
genrsacommand was deprecated andgenpkeyshould be used instead. - The
genpkeycommand generates keys in PKCS#8 format. Encrypted keys of this format have the phraseENCRYPTED PRIVATE KEYin both header and trailer records. - Depending on how they were generated, keys can be converted from PEM to DER format, and vice-versa, using the
rsa,dsa, andpkeycommands.
- X.509 certificates are usually stored in PKCS#7 format of extensions
.p7band.p7c. - PKCS7 files can be converted to readable PEM files using the command:
openssl pkcs7 -in <p7b input> -print_certs -out <output name>
- Certificates in PEM format can be converted to PKCS7 format using
crl2pkcs7command. - Certificates in PEM format can be converted to DER format, and vice-versa, using the command:
openssl x509 -inform <PEM|DER> -in <input file> -outform <DER|PEM> -out <output name>
- DER certificates filename extensions are
.der,.cer, and.crt.
- On server-side, certificate and keys can be stored together in PKCS#12 format as
.p12files. - PKCS12 files can be split into constituent key, certificate and cert-chain, and vice-versa, using
pkcs12command.
- Check key:
openssl rsa -check -noout -in <key file>
- Verify output is:
RSA key ok. - Get MD5 hash of the key's modulus:
openssl rsa -modulus -noout -in <key file> | openssl md5
- Get MD5 hash of the certificate's modulus:
openssl x509 -modulus -noout -in <DER/PEM certificate file> | openssl md5
- Compare the MD5 hashes of above two steps. If they match, the key and the certificate are a pair.
- ASN.1 JavaScript decoder: https://lapo.it/asn1js/