Skip to content

Instantly share code, notes, and snippets.

@schneefisch
Last active December 18, 2023 09:41
Show Gist options
  • Save schneefisch/6b5752523715bf97633c57627ee1b5ac to your computer and use it in GitHub Desktop.
Save schneefisch/6b5752523715bf97633c57627ee1b5ac to your computer and use it in GitHub Desktop.
Convert certificate formats with OpenSSL

Various certificate-conversions

Exports

Export public certificate/key from pfx

openssl pkcs12 -in <cert>.pfx -clcerts -nokeys -out <pub_cert>.pem

Export certificate

openssl pkcs12 -in keystore.p12 -nokeys -out cert.pem

Export (plain) private key

openssl pkcs12 -in keystore.p12 -nodes -nocerts -out key.pem

Conversions

Convert PEM -> DER

openssl x509 -in domain.crt \
        -outform der \
        -out domain.der

Convert DER -> PEM

openssl x509 -inform der \
        -in domain.der \
        -out domain.crt

Convert PEM -> PKCS7

Use this command if you want to add PEM certificates (domain.crt and ca-chain.crt) to a PKCS7 file (domain.p7b):

openssl crl2pkcs7 -nocrl \
       -certfile domain.crt \
       -certfile ca-chain.crt \
       -out domain.p7b

Convert PKCS7 -> PEM

openssl pkcs7 -in domain.p7b \
        -print_certs \
        -out domain.crt

when working with a legacy algorithm, e.g. SHA1, then use -legacy

openssl pkcs7 -in domain.p7b \
        -print_certs \
        -legacy \
        -out domain.crt

Convert PEM -> PKCS12

Use this command if you want to take a private key (domain.key) and a certificate (domain.crt), and combine them into a PKCS12 file (domain.pfx):

openssl pkcs12 \
       -inkey domain.key \
       -in domain.crt \
       -export -out domain.pfx

if you need an "alias", then includ option -name "myalias"

Convert PKCS12 -> PEM

Use this command if you want to convert a PKCS12 file (domain.pfx) and convert it to PEM format (domain.combined.crt):

openssl pkcs12 \
       -in domain.pfx \
       -nodes -out domain.combined.crt

Convert .crt -> PEM

openssl x509 -in mycert.crt -out mycert.pem -outform PEM

Convert PEM -> .crt

openssl x509 -outform der -in certificate.pem -out certificate.crt

Convert .crt -> pfx

openssl pkcs12 -export -out certificate.pfx -inkey privateKey.key -in certificate.crt -certfile more.crt

Notes

  • openssl – the command for executing OpenSSL
  • pkcs12 – the file utility for PKCS#12 files in OpenSSL
  • -export -out certificate.pfx – export and save the PFX file as certificate.pfx
  • -inkey privateKey.key – use the private key file privateKey.key as the private key to combine with the certificate.
  • -in certificate.crt – use certificate.crt as the certificate the private key will be combined with.
  • -certfile more.crt – This is optional, this is if you have any additional certificates you would like to include in the PFX file.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment