Skip to content

Instantly share code, notes, and snippets.

@srikanthmanda
Last active June 20, 2021 19:13
Show Gist options
  • Save srikanthmanda/3aee7b3a62ba43f90d22867bc1ad6158 to your computer and use it in GitHub Desktop.
Save srikanthmanda/3aee7b3a62ba43f90d22867bc1ad6158 to your computer and use it in GitHub Desktop.
Brief notes on TLS/SSL keys and certificates, their file formats and converting them using OpenSSL.

TLS/SSL & OpenSSL

Brief notes on TLS/SSL private keys and certificates, their various formats and converting them to different formats using OpenSSL.

Resources & References

File Formats of Keys and Certificates

  • Keys and X.509 certificates are usually stored in PKCS formats.
  • They can be converted to:
    • Binary files of ASN.1 notation in DER format.
    • ASCII (text) files of Base64 encoding in PEM format.

Keys

  • Keys are usually stored as Base64 encoded .pem files.
  • 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 genrsa command was deprecated and genpkey should be used instead.
  • The genpkey command generates keys in PKCS#8 format. Encrypted keys of this format have the phrase ENCRYPTED PRIVATE KEY in 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, and pkey commands.

Certificates

  • X.509 certificates are usually stored in PKCS#7 format of extensions .p7b and .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 crl2pkcs7 command.
  • 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.

Certificates & Keys

  • On server-side, certificate and keys can be stored together in PKCS#12 format as .p12 files.
  • PKCS12 files can be split into constituent key, certificate and cert-chain, and vice-versa, using pkcs12 command.

Verifying RSA Key & Certificate Pair

  1. Check key:
openssl rsa -check -noout -in <key file>
  1. Verify output is: RSA key ok.
  2. Get MD5 hash of the key's modulus:
openssl rsa -modulus -noout -in <key file> | openssl md5
  1. Get MD5 hash of the certificate's modulus:
openssl x509 -modulus -noout -in <DER/PEM certificate file> | openssl md5
  1. Compare the MD5 hashes of above two steps. If they match, the key and the certificate are a pair.

Appendix

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment