ecdsa.com

Decode a certificate · Python

How to decode an X.509 certificate in Python

Python's cryptography package decodes X.509 certificates with a typed API: load_pem_x509_certificate returns an object whose subject, validity and public key are real Python types rather than text to parse. Ideal for expiry monitoring and key extraction scripts.

Tested with Python 3.14 and cryptography 50.0.

Same recipe in:Node.jsPythonGoOpenSSL
decode_cert.py — fields, fingerprint, key curve
from cryptography import x509
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric import ec
 
cert = x509.load_pem_x509_certificate(open("cert.pem", "rb").read())
 
print("subject:", cert.subject.rfc4514_string())
print("issuer:", cert.issuer.rfc4514_string())
print("valid:", cert.not_valid_before_utc, "->", cert.not_valid_after_utc)
print("serial:", hex(cert.serial_number))
print("sig alg:", cert.signature_algorithm_oid._name)
print("fingerprint:", cert.fingerprint(hashes.SHA256()).hex())
 
key = cert.public_key()
if isinstance(key, ec.EllipticCurvePublicKey):
print("EC key on", key.curve.name) # secp256r1 == P-256
expiry check for monitoring scripts
from datetime import datetime, timezone
 
remaining = cert.not_valid_after_utc - datetime.now(timezone.utc)
print("days until expiry:", remaining.days)

How it works

  1. load_pem_x509_certificate for PEM, load_der_x509_certificate for binary DER — the library does not guess.
  2. Use the _utc-suffixed validity properties: they return timezone-aware datetimes, and the naive originals are deprecated.
  3. cert.public_key() returns the same key object types the rest of the library uses — pass it directly to verify or serialize it to PEM.
  4. For chain files with several BEGIN CERTIFICATE blocks, x509.load_pem_x509_certificates (plural) parses the whole bundle into a list in one call.

Gotchas

  • Comparing not_valid_after_utc with a naive datetime.now() raises TypeError — always use datetime.now(timezone.utc).
  • cert.signature_algorithm_oid tells you what signed this certificate (the CA's algorithm), not what the certificate's own key can do — a common misreading of ECDSA certs in RSA-signed chains.
  • Decoding is not validating: the library will happily parse an expired, self-signed or revoked certificate. Trust decisions need chain verification against a store.

Related recipes