TExcelTAD
Home › Cybersecurity › PKI & Certificates

PKI & Certificates

Signatures prove that a message was signed by the holder of a particular private key. But how do you know that a public key really belongs to bank.example and not to an attacker? A certificate answers that: it is a signed statement, "this public key belongs to this name", issued by a certificate authority (CA) that your device already trusts. The whole system of CAs, certificates and rules is called a public key infrastructure (PKI).

What a certificate contains

Web certificates use the X.509 format. The important fields:

Field Meaning
Subject Who the certificate is for (CN=shop.example)
Subject Alternative Name (SAN) The DNS names (or IPs) it is valid for. Browsers check this, not the CN
Issuer The CA that signed it
Validity not before / not after dates. Public web certificates last at most about a year, and lifetimes are shrinking
Public key The subject's key
Key usage / extended key usage What the key may be used for (server auth, code signing …)
Basic constraints Whether this certificate may itself sign other certificates (CA:TRUE)
Serial number Unique per issuer; used for revocation
Signature The issuer's signature over all of the above

The chain of trust

Your operating system or browser ships with a trust store of about 150 root CA certificates. Roots rarely sign server certificates directly; they sign intermediate CAs, which sign the leaf (server) certificates.

text
Root CA  (self-signed, in your trust store)
  └─ signs ─▶ Intermediate CA
                └─ signs ─▶ shop.example   (sent by the server, with the intermediate)

To validate a server certificate, a client checks that:

  1. each certificate in the chain is signed by the next one, ending at a trusted root;
  2. every certificate is within its validity period;
  3. the intermediates are allowed to act as CAs;
  4. the hostname you connected to matches a SAN entry of the leaf;
  5. none of the certificates is revoked (via OCSP or CRLs, with varying reliability).

If any check fails, the connection must be refused. "Click to continue anyway" is how many man-in-the-middle attacks succeed.

Creating and reading a certificate

The cryptography package can build certificates. The example creates a small self-signed certificate (issuer = subject) with fixed dates and serial number, then reads the fields back. Self-signed certificates are fine for local testing and internal tools where you distribute the certificate yourself; public websites need a CA-issued one (free from Let's Encrypt).

python · try it yourself
import datetime
from cryptography import x509
from cryptography.x509.oid import NameOID
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric import ec

key = ec.generate_private_key(ec.SECP256R1())          # new key every run: not printed
name = x509.Name([
    x509.NameAttribute(NameOID.COMMON_NAME, "dev.tadshop.test"),
    x509.NameAttribute(NameOID.ORGANIZATION_NAME, "TAD Shop Dev"),
])
cert = (
    x509.CertificateBuilder()
    .subject_name(name)
    .issuer_name(name)                                  # self-signed
    .public_key(key.public_key())
    .serial_number(1001)
    .not_valid_before(datetime.datetime(2026, 1, 1, tzinfo=datetime.timezone.utc))
    .not_valid_after(datetime.datetime(2026, 4, 1, tzinfo=datetime.timezone.utc))
    .add_extension(x509.SubjectAlternativeName([
        x509.DNSName("dev.tadshop.test"), x509.DNSName("api.dev.tadshop.test")]),
        critical=False)
    .add_extension(x509.BasicConstraints(ca=False, path_length=None), critical=True)
    .sign(key, hashes.SHA256())
)

print("subject:", cert.subject.rfc4514_string())
print("issuer: ", cert.issuer.rfc4514_string())
print("serial: ", cert.serial_number)
print("valid:  ", cert.not_valid_before_utc.date(), "to", cert.not_valid_after_utc.date())
san = cert.extensions.get_extension_for_class(x509.SubjectAlternativeName).value
print("SANs:   ", san.get_values_for_type(x509.DNSName))
print("is CA:  ", cert.extensions.get_extension_for_class(x509.BasicConstraints).value.ca)
print("signed with:", cert.signature_hash_algorithm.name)
subject: O=TAD Shop Dev,CN=dev.tadshop.test
issuer:  O=TAD Shop Dev,CN=dev.tadshop.test
serial:  1001
valid:   2026-01-01 to 2026-04-01
SANs:    ['dev.tadshop.test', 'api.dev.tadshop.test']
is CA:   False
signed with: sha256

Checking validity and hostnames

Two of the most common certificate errors are expired certificates and name mismatches. Here is a simplified checker for both, including the wildcard rule (*.example.com matches exactly one extra label, so a.example.com but not a.b.example.com or example.com):

python · try it yourself
import datetime

def hostname_matches(pattern, host):
    pattern, host = pattern.lower(), host.lower()
    if pattern.startswith("*."):
        suffix = pattern[1:]                       # ".example.com"
        label = host[: -len(suffix)] if host.endswith(suffix) else ""
        return bool(label) and "." not in label
    return pattern == host

def check(cert, host, now):
    if not (cert["not_before"] <= now <= cert["not_after"]):
        return "invalid: outside validity period"
    if not any(hostname_matches(p, host) for p in cert["sans"]):
        return "invalid: hostname mismatch"
    return "valid"

cert = {
    "sans": ["shop.example", "*.shop.example"],
    "not_before": datetime.date(2026, 1, 1),
    "not_after": datetime.date(2026, 12, 31),
}
today = datetime.date(2026, 6, 1)
for host in ["shop.example", "www.shop.example", "a.b.shop.example", "evilshop.example"]:
    print(f"{host:<18} {check(cert, host, today)}")
print(f"{'shop.example':<18} {check(cert, 'shop.example', datetime.date(2027, 2, 1))}  (in 2027)")
shop.example       valid
www.shop.example   valid
a.b.shop.example   invalid: hostname mismatch
evilshop.example   invalid: hostname mismatch
shop.example       invalid: outside validity period  (in 2027)

evilshop.example doesn't match *.shop.example because the wildcard must be a whole label followed by .shop.example. Real TLS libraries implement these rules for you; your job is to never disable them (no verify=False, no "trust all certificates" in production code).

Revocation and transparency

If a private key leaks, its certificate must be revoked before it expires. Revocation checking is notoriously unreliable on the web, which is one reason certificate lifetimes keep getting shorter: a short-lived certificate limits how long a stolen key is useful.

Certificate Transparency (CT) requires CAs to publish every certificate they issue in public, append-only logs. Domain owners can monitor the logs and spot certificates issued for their domains that they never requested.

Certificates beyond the web

  • mTLS (mutual TLS): clients present certificates too, common between microservices.
  • Code signing: operating systems check signatures on installers and drivers.
  • S/MIME: signed and encrypted email.
  • Internal PKI: companies run their own CA for VPNs, Wi-Fi Enterprise and devices, and install its root on managed machines.

Go further: Certificate Chains and Path Validation builds and verifies a chain with OpenSSL and Python, and Revocation compares CRLs, OCSP and short-lived certificates.

Test yourself

What does a CA's signature on a certificate assert?

  1. That the website is safe
  2. That the public key belongs to the named subject
  3. That the traffic is encrypted
  4. That the server is up to date

Does the certificate *.shop.example match a.b.shop.example?

  1. Yes
  2. No, the wildcard covers exactly one label
  3. Only for HTTP
  4. Only if the CN matches

What is Certificate Transparency used for?

  1. Encrypting certificates
  2. Publicly logging issued certificates so mis-issuance can be detected
  3. Speeding up TLS
  4. Hiding certificates from attackers