X.509 Certificates: Fields, Building and Parsing
A public key alone says nothing about who owns it. When your browser receives a key from bank.example, it needs some reason to believe the key belongs to the bank and not to whoever is sitting on the café Wi-Fi. A certificate is that reason: a signed statement by a certificate authority (CA) binding a public key to names, for a limited time, for limited purposes. Certificates use the X.509 format (ITU-T X.509, profiled for the Internet in RFC 5280), and reading one fluently is a daily skill in incident response and audits.
What is in a certificate
| Field | Meaning | In the lab certificate |
|---|---|---|
| version | 3 for anything with extensions | 3 |
| serial number | unique per CA; public CAs must use at least 64 random bits | 0x1002 |
| signature algorithm | how the CA signed it | sha256WithRSAEncryption |
| issuer | the CA's name | ExcelTAD Lab Root CA |
| validity | notBefore, notAfter |
2026-01-01 to 2028-01-01 |
| subject | the owner's name; for TLS mostly legacy | CN = lab.test |
| subject public key info | algorithm and public key | RSA 2048 |
| extensions | the fields that matter for decisions | see below |
The important extensions:
- subjectAltName (SAN): the DNS names and IP addresses the certificate is valid for. Browsers ignore the subject CN and match only the SAN.
- basicConstraints:
CA:TRUEfor a CA certificate,CA:FALSEfor a leaf; an optionalpathlenlimits how many CAs may follow below it. - keyUsage and extendedKeyUsage (EKU): what the key may do:
digitalSignature,keyCertSign,cRLSign;serverAuth,clientAuth,codeSigning. - subjectKeyIdentifier / authorityKeyIdentifier: identifiers that link a certificate to its issuer's key, used to build chains.
- CRL distribution points, Authority Information Access: where to check revocation and fetch the issuer (Revocation).
- Signed certificate timestamps (SCTs): proof of logging in Certificate Transparency (CT and ACME).
Extensions marked critical must be understood by the verifier, or the certificate must be rejected.
Here is the lab certificate as OpenSSL prints it (the long hex dumps of key and signature are removed):
P=$SAMPLES/pki
openssl x509 -in $P/lab.test.crt -noout -text | sed -n '1,12p;/X509v3 extensions/,/Signature Algorithm/p' | grep -v '^ *[0-9a-f][0-9a-f]:' Certificate:
Data:
Version: 3 (0x2)
Serial Number: 4098 (0x1002)
Signature Algorithm: sha256WithRSAEncryption
Issuer: C = XX, O = ExcelTAD Lab, CN = ExcelTAD Lab Root CA
Validity
Not Before: Jan 1 00:00:00 2026 GMT
Not After : Jan 1 00:00:00 2028 GMT
Subject: C = XX, O = ExcelTAD Lab, OU = Web, CN = lab.test
Subject Public Key Info:
Public Key Algorithm: rsaEncryption
X509v3 extensions:
X509v3 Basic Constraints: critical
CA:FALSE
X509v3 Key Usage: critical
Digital Signature, Key Encipherment
X509v3 Extended Key Usage:
TLS Web Server Authentication
X509v3 Subject Alternative Name:
DNS:lab.test, DNS:www.lab.test
X509v3 Subject Key Identifier:
X509v3 Authority Key Identifier:
Signature Algorithm: sha256WithRSAEncryption
The encoding underneath is ASN.1 DER: a tree of tagged, length-prefixed values. The signed part is tbsCertificate ("to be signed"); the CA's signature over its DER bytes follows.
Building a CA and a leaf in Python
The example creates a small lab CA and a server certificate for api.lab.test, then parses both. The keys are Ed25519 keys from fixed lab-only seeds, and Ed25519 signatures are deterministic, so the certificates are byte-identical on every run; real keys come from Ed25519PrivateKey.generate() (or ec.generate_private_key), and a real CA keeps its key in an HSM.
import datetime
from cryptography import x509
from cryptography.x509.oid import NameOID, ExtendedKeyUsageOID
from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey
# Fixed lab-only keys so the certificates come out byte-identical on every run (real keys: generate()).
ca_key = Ed25519PrivateKey.from_private_bytes(bytes(31) + b"\x01")
leaf_key = Ed25519PrivateKey.from_private_bytes(bytes(31) + b"\x02")
T0 = datetime.datetime(2026, 1, 1, tzinfo=datetime.timezone.utc)
ca_name = x509.Name([x509.NameAttribute(NameOID.ORGANIZATION_NAME, "Lab"),
x509.NameAttribute(NameOID.COMMON_NAME, "Lab Root CA")])
ca = (x509.CertificateBuilder()
.subject_name(ca_name).issuer_name(ca_name)
.public_key(ca_key.public_key()).serial_number(0x1001)
.not_valid_before(T0).not_valid_after(T0 + datetime.timedelta(days=3650))
.add_extension(x509.BasicConstraints(ca=True, path_length=0), critical=True)
.add_extension(x509.KeyUsage(False, False, False, False, False, True, True, False, False), critical=True)
.add_extension(x509.SubjectKeyIdentifier.from_public_key(ca_key.public_key()), critical=False)
.sign(ca_key, None))
leaf = (x509.CertificateBuilder()
.subject_name(x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, "api.lab.test")]))
.issuer_name(ca.subject)
.public_key(leaf_key.public_key()).serial_number(0x2001)
.not_valid_before(T0).not_valid_after(T0 + datetime.timedelta(days=90))
.add_extension(x509.SubjectAlternativeName([x509.DNSName("api.lab.test"), x509.DNSName("lab.test")]), critical=False)
.add_extension(x509.BasicConstraints(ca=False, path_length=None), critical=True)
.add_extension(x509.ExtendedKeyUsage([ExtendedKeyUsageOID.SERVER_AUTH]), critical=False)
.add_extension(x509.AuthorityKeyIdentifier.from_issuer_public_key(ca_key.public_key()), critical=False)
.sign(ca_key, None))
for cert in (ca, leaf):
print("subject :", cert.subject.rfc4514_string())
print("issuer :", cert.issuer.rfc4514_string())
print("serial :", hex(cert.serial_number), " valid", cert.not_valid_before_utc.date(), "->", cert.not_valid_after_utc.date())
print("sig alg :", cert.signature_algorithm_oid._name, " DER bytes:", len(cert.public_bytes(serialization.Encoding.DER)))
for ext in cert.extensions:
print(" ext", ext.oid._name, "(critical)" if ext.critical else "")
san = leaf.extensions.get_extension_for_class(x509.SubjectAlternativeName).value
print("SAN names:", san.get_values_for_type(x509.DNSName))
print("leaf SHA-256 fingerprint:", leaf.fingerprint(hashes.SHA256()).hex()[:32] + "...")
leaf.verify_directly_issued_by(ca); print("leaf signed by CA: OK")subject : CN=Lab Root CA,O=Lab
issuer : CN=Lab Root CA,O=Lab
serial : 0x1001 valid 2026-01-01 -> 2035-12-30
sig alg : ed25519 DER bytes: 320
ext basicConstraints (critical)
ext keyUsage (critical)
ext subjectKeyIdentifier
subject : CN=api.lab.test
issuer : CN=Lab Root CA,O=Lab
serial : 0x2001 valid 2026-01-01 -> 2026-04-01
sig alg : ed25519 DER bytes: 344
ext subjectAltName
ext basicConstraints (critical)
ext extendedKeyUsage
ext authorityKeyIdentifier
SAN names: ['api.lab.test', 'lab.test']
leaf SHA-256 fingerprint: 8150590c9def7261a49ae6915e65504f...
leaf signed by CA: OK
Things to notice:
- The root is self-signed: issuer equals subject, and it is trusted only because it is installed in a trust store, not because of its signature.
- 3,650 days from 2026-01-01 is 2035-12-30 (two leap years); the leaf's 90 days end on 2026-04-01.
- The whole Ed25519 leaf is only 344 bytes; RSA certificates are typically 1–2 KB, which matters for TLS handshake size.
verify_directly_issued_bychecks one signature and the issuer name. It is not full path validation: dates, names, key usages and chains are the next lesson.- The fingerprint is a hash of the whole DER certificate. It identifies one certificate (for pinning or inventory), but it changes at every renewal; pinning the public key (SPKI hash) survives renewals with the same key.
Formats you will meet
| Format | What it is |
|---|---|
PEM (.pem, .crt, .cer) |
Base64 of DER between -----BEGIN CERTIFICATE----- lines; may hold several certificates (a chain) |
DER (.der, .cer) |
the raw binary |
PKCS#12 (.p12, .pfx) |
certificate(s) plus private key in one password-protected file; often weakly encrypted in old exports |
CSR (.csr, PKCS#10) |
a request: subject, public key, requested extensions, signed with the requester's private key |
How certificate problems are detected
- Expiry:
openssl x509 -checkend 2592000(30 days) in monitoring; inventories of every certificate in use, including internal ones and those on appliances. - Wrong or missing names: SAN without every served host name; reliance on CN only (rejected by browsers since 2017).
- Weak parameters: RSA under 2,048 bits, SHA-1 signatures, missing
basicConstraintson leaves, leaves withCA:TRUE, overly broad EKUs (anyExtendedKeyUsage), wildcard certificates spread across many systems. - Private keys in the wrong place:
.pemand.pfxfiles with keys in repositories, images and shared folders (secret scanners flagBEGIN PRIVATE KEY).
How it is fixed
- Automate issuance and renewal (ACME), with short lifetimes; monitor expiry anyway.
- Issue certificates with exact SAN lists,
CA:FALSE,digitalSignatureand the EKU actually needed. - Generate private keys where they are used (or in an HSM/KMS), never send them by e-mail, and keep them out of source control.
Pitfalls
- Trusting a certificate because it "parses": parsing is not validation.
- Wildcards (
*.lab.test) match one label only:a.lab.test, nota.b.lab.testorlab.test. - Time zones and clock skew: certificates are in UTC; devices with wrong clocks reject valid certificates or accept expired ones.
Practice
1. Change the leaf's validity to 400 days. Would a browser accept it if a public CA issued it today?
No. Public TLS certificates issued from 15 March 2026 may be valid for at most 200 days under the CA/Browser Forum Baseline Requirements (ballot SC-081), falling to 100 days in March 2027 and 47 days in March 2029. Browsers enforce the limit. A private CA can choose its own policy.
2. A leaf certificate has basicConstraints: CA:TRUE. Why is that dangerous?
Its key could sign further certificates, and a verifier that only checks signatures would accept them; the owner of that "server" key effectively becomes a CA. Correct verifiers reject CA certificates as leaves and check constraints on intermediates.
3. Which field does a browser use to decide whether the certificate is valid for www.lab.test?
The subjectAltName extension's DNS names (lab.test, www.lab.test in the sample certificate), not the subject CN.
Test yourself
Which extension lists the host names a TLS certificate is valid for?
- keyUsage
- subjectAltName
- basicConstraints
- authorityKeyIdentifier
Why is a root CA certificate trusted although it is self-signed?
- Its signature is stronger
- It is installed in the trust store
- It has CA:TRUE
- It has a long validity
What does verify_directly_issued_by NOT check?
- The issuer's signature
- The issuer name
- Validity dates and host names
- That the issuer key signed the certificate
What changes when a certificate is renewed with the same key: the fingerprint or the SPKI hash?
- Neither
- Only the fingerprint
- Only the SPKI hash
- Both