# Certificate: PEM -> DER, and DER -> PEMopenssl x509 -in cert.pem -outform DER -out cert.deropenssl x509 -in cert.der -inform DER -out cert-again.pem# Private key -> PKCS#8 DER on every OpenSSL version (unencrypted: -nocrypt)openssl pkcs8 -topk8 -nocrypt -in key.pem -outform DER -out key.der# ...and back to PKCS#8 PEM ("BEGIN PRIVATE KEY")openssl pkey -in key.der -inform DER -out key-again.pem # The public key as DER (SubjectPublicKeyInfo)openssl pkey -in key.pem -pubout -outform DER -out pub.derHow it works
- PEM is DER in base64 between
-----BEGIN …-----and-----END …-----lines, so the conversion changes the encoding, never the content: the certificate's DER is 563 bytes here and converting it back gives a file identical to the original PEM. openssl x509 -outform DERwrites the binary form;-inform DERreads it, and without-outform DERthe output is PEM again.openssl pkcs8 -topk8 -nocrypt -outform DERwrites the key as PKCS#8 (PrivateKeyInfo, 138 bytes for this P-256 key) — the formcrypto.subtle.importKey("pkcs8"), Java'sPKCS8EncodedKeySpecand most libraries expect. Drop-nocryptto get an encrypted PKCS#8 DER.openssl pkey -pubout -outform DERwrites the public key as SubjectPublicKeyInfo DER (91 bytes for P-256).
Gotchas
- On OpenSSL 3.5 and earlier (3.5.7 in the run),
openssl pkey -outform DERwrites an EC key in the traditional SEC1 structure (ECPrivateKey, 121 bytes, first INTEGER01), not PKCS#8 (first INTEGER00) — even though the PEM it reads is PKCS#8. OpenSSL 3.6 writes PKCS#8 there;openssl pkcs8 -topk8gives PKCS#8 on every version. - DER has no label: a
.derfile does not say whether it holds a certificate, a SEC1 key or a PKCS#8 key. Name files after their content, or inspect them withopenssl asn1parse -inform DER. - OpenSSL 3 detects the input format when reading —
openssl x509 -in cert.derworks without-inform DER— but output is PEM unless you pass-outform DER.
Related recipes
- How to convert a certificate and a private key between PEM and DER in Python
- How to convert a certificate and a private key between PEM and DER in Go
- How to convert a certificate and a private key between PEM and DER in Node.js
- How to export a public key as PEM with OpenSSL
- How to decode an X.509 certificate with OpenSSL