PEM & DER (ASN.1 Encoding)
- •
What it is
- •
ASN.1 is a schema language for describing structured data (like "an RSA key has a modulus and an exponent"); DER is a specific, canonical binary encoding rule for serializing ASN.1 values. PEM is just DER data, Base64-encoded and wrapped in a one-line
-----BEGIN X-----/-----END X-----header and footer that tells a parser what's inside (an RSA key, a certificate, etc.).
- •
- •
When to apply
- •
You're handed a
.pem(text, with BEGIN/END markers) or.der(raw binary) file containing a key or certificate. Use a library rather than hand-parsing — PyCryptodome'sRSA.importKey()/RSA.import_key()understands both PEM and DER directly, andopensslcan inspect or convert between them from the command line.
- •
- •
Worked example
- •
Stripping the PEM header/footer and Base64-decoding the body of a
-----BEGIN RSA PUBLIC KEY-----block yields the exact same bytes as the equivalent.derfile for that key.
- •
- •
Python
- •
from Crypto.PublicKey import RSA key = RSA.importKey(open("key.pem", "rb").read()) # also works directly on .der bytes print(key.n, key.d) # modulus, private exponent (if present)
- •
- •
Bash
- •
openssl x509 -inform der -in cert.der -noout -modulus openssl rsa -in key.pem -text -noout
- •
- •
- •