Skip to content

Certificate Decoder — Python source

Paste a PEM X.509 certificate and see its subject, issuer, SAN, validity, key usage, fingerprints, and chain details in a human-readable format.

This is the Python implementation — the same logic the interactive tool runs, in a shareable, citable form.

"""cert-decoder — Pure ASN.1 DER parser + X.509 certificate decoder.

Language: Python 3 (standard library only).
CosmoDev polyglot showcase port of the `cert-decoder` tool, ported from
src/lib/cert-decoder.ts (the canonical TypeScript implementation).

Why this file exists: DER is deterministic and parsed sequentially, so ~150
lines of stdlib Python decode a certificate without ssl/OpenSSL — no X.509
library hiding the very structure this tool exists to show. It decodes; it
never verifies signatures or validates chains: a parsed cert is not a trusted
one.

display source — part of CosmoDev's polyglot tool pages.
"""

from __future__ import annotations

import base64
import binascii
import datetime as dt
import re

# Human-readable names for the OIDs certificates actually carry. Unknown OIDs
# fall through as their dotted numbers, exactly like the TS map.
OID_NAMES = {
    "1.2.840.113549.1.1.1": "RSA", "1.2.840.113549.1.1.5": "SHA-1 with RSA",
    "1.2.840.113549.1.1.11": "SHA-256 with RSA", "1.2.840.113549.1.1.12": "SHA-384 with RSA",
    "1.2.840.113549.1.1.13": "SHA-512 with RSA", "1.2.840.113549.1.1.14": "SHA-224 with RSA",
    "1.2.840.10045.2.1": "ECDSA", "1.2.840.10045.4.3.2": "ECDSA with SHA-256",
    "1.2.840.10045.4.3.3": "ECDSA with SHA-384", "1.2.840.10045.4.3.4": "ECDSA with SHA-512",
    "1.3.14.3.2.29": "SHA-1 with RSA (OIW)", "2.5.4.3": "CN", "2.5.4.6": "C",
    "2.5.4.7": "L", "2.5.4.8": "ST", "2.5.4.10": "O", "2.5.4.11": "OU",
    "1.2.840.113549.1.9.1": "emailAddress", "2.5.29.14": "Subject Key Identifier",
    "2.5.29.15": "Key Usage", "2.5.29.17": "Subject Alternative Name",
    "2.5.29.19": "Basic Constraints", "2.5.29.35": "Authority Key Identifier",
    "2.5.29.37": "Extended Key Usage", "1.3.6.1.5.5.7.1.1": "Authority Information Access",
    "1.3.6.1.5.5.7.1.3": "CRL Distribution Points", "1.3.6.1.5.5.7.3.1": "serverAuth",
    "1.3.6.1.5.5.7.3.2": "clientAuth", "1.3.6.1.5.5.7.3.3": "codeSigning",
    "1.3.6.1.5.5.7.3.4": "emailProtection", "1.3.6.1.5.5.7.3.8": "timeStamping",
    "1.2.840.113549.1.9.14": "Extension Request",
    "1.3.6.1.4.1.11129.2.1.17": "CT Precertificate SCTs",
    "1.3.6.1.4.1.311.21.7": "Microsoft Certificate Template",
}

EC_CURVES = {"1.2.840.10045.3.1.7": "P-256", "1.3.132.0.34": "P-384",
             "1.3.132.0.35": "P-512", "1.3.132.0.10": "secp256k1"}

# Key Usage bit names, in BIT STRING bit order.
KEY_USAGE_BITS = ["digitalSignature", "nonRepudiation", "keyEncipherment",
                  "dataEncipherment", "keyAgreement", "keyCertSign", "cRLSign",
                  "encipherOnly", "decipherOnly"]

PEM_REGEX = re.compile(
    r"-----BEGIN\s+CERTIFICATE-----\s*\r?\n([\s\S]*?)\r?\n-----END\s+CERTIFICATE-----")


class Node:
    """One DER TLV node; `children` is None for primitive types."""

    def __init__(self, tag_class, constructed, tag_number, raw_value, offset):
        self.tag_class, self.constructed = tag_class, constructed
        self.tag_number, self.raw_value, self.offset = tag_number, raw_value, offset
        self.children: list[Node] | None = None


def read_node(buf: bytes, pos: int) -> tuple[Node, int]:
    """Read one TLV at `pos`; returns (node, next_pos). Bounds-check every
    length against the buffer: a pasted certificate is untrusted input."""
    offset = pos
    byte0 = buf[pos]
    pos += 1
    tag_class = ("universal", "application", "context", "private")[(byte0 >> 6) & 3]
    constructed = bool(byte0 & 0x20)
    tag_number = byte0 & 0x1F
    if tag_number == 0x1F:  # long-form tag number
        tag_number = 0
        while True:
            b = buf[pos]
            pos += 1
            tag_number = (tag_number << 7) | (b & 0x7F)
            if not b & 0x80:
                break
    length = buf[pos]
    pos += 1
    if length >= 0x80:
        n = length & 0x7F
        if n == 0:
            raise ValueError("Indefinite length is not supported in DER")
        if n > 4:
            raise ValueError(f"Length too large: {n} bytes")
        length = int.from_bytes(buf[pos:pos + n], "big")
        pos += n
    if pos + length > len(buf):
        raise ValueError(
            f"Truncated DER: need {length} bytes at offset {pos}, "
            f"but only {len(buf) - pos} remain")
    node = Node(tag_class, constructed, tag_number, buf[pos:pos + length], offset)
    if constructed and length:
        node.children = []
        p = pos
        while p < pos + length:
            child, p = read_node(buf, p)
            node.children.append(child)
    return node, pos + length


def decode_oid(raw: bytes) -> str:
    if not raw:
        raise ValueError("Empty OID")
    parts = [raw[0] // 40, raw[0] % 40]
    value = 0
    for b in raw[1:]:
        value = (value << 7) | (b & 0x7F)
        if not b & 0x80:
            parts.append(value)
            value = 0
    return ".".join(str(p) for p in parts)


def oid_name(oid: str) -> str:
    return OID_NAMES.get(oid, oid)


def read_string(node: Node) -> str:
    """Known text tags decode as UTF-8; anything else only if it is valid
    UTF-8, else colon-separated hex so binary never becomes mojibake."""
    try:
        return node.raw_value.decode("utf-8")
    except UnicodeDecodeError:
        return ":".join(f"{b:02x}" for b in node.raw_value)


def parse_time(node: Node) -> dt.datetime:
    """UTCTime (tag 23, two-digit year window) / GeneralizedTime (tag 24)."""
    utc = node.tag_number == 23
    if not utc and node.tag_number != 24:
        raise ValueError(f"Unknown time tag: {node.tag_number}")
    m = re.fullmatch(r"(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})Z", read_string(node))
    if not m:
        raise ValueError(f"Invalid time value in tag {node.tag_number}")
    y, mo, d, h, mi, s = (int(g) for g in m.groups())
    if utc:
        y += 1900 if y >= 50 else 2000
    return dt.datetime(y, mo, d, h, mi, s, tzinfo=dt.timezone.utc)


def parse_rdn(node: Node) -> list[dict]:
    attrs = []
    for rdn_set in node.children or []:
        for attr_seq in rdn_set.children or []:
            if not attr_seq.children or len(attr_seq.children) < 2:
                continue
            attrs.append({
                "type": oid_name(decode_oid(attr_seq.children[0].raw_value)),
                "value": read_string(attr_seq.children[1]),
            })
    return attrs


def format_dn(attrs: list[dict]) -> str:
    return ", ".join(f"{a['type']}={a['value']}" for a in attrs)


def parse_extensions(nodes: list[Node]) -> dict:
    ext: dict = {"basic_constraints_ca": None, "key_usage": None,
                 "ext_key_usage": None, "san_dns": [], "san_ip": [], "san_email": []}
    for node in nodes:
        if not node.children or len(node.children) < 2:
            continue
        oid = decode_oid(node.children[0].raw_value)
        # Skip the `critical` BOOLEAN when present; the value is an OCTET
        # STRING wrapping the extension's own DER.
        value_idx = 2 if len(node.children) >= 3 and node.children[1].tag_number == 1 \
            and node.children[1].tag_class == "universal" else 1
        octet = node.children[value_idx].raw_value
        if not octet:
            continue
        content, _ = read_node(octet, 0)
        if oid == "2.5.29.19":  # Basic Constraints
            flag = content.children[0] if content.children else None
            ext["basic_constraints_ca"] = bool(
                flag and flag.tag_number == 1 and flag.raw_value == b"\xff")
        elif oid == "2.5.29.15":  # Key Usage — BIT STRING
            ext["key_usage"] = usage = []
            if len(content.raw_value) >= 2:
                unused, octets = content.raw_value[0], content.raw_value[1:]
                for i, name in enumerate(KEY_USAGE_BITS):
                    if i // 8 < len(octets) and octets[i // 8] & (1 << (7 - i % 8)):
                        usage.append(name)
                while unused and len(usage) > len(octets) * 8 - unused:
                    usage.pop()
        elif oid == "2.5.29.37":  # Extended Key Usage
            ext["ext_key_usage"] = [oid_name(decode_oid(c.raw_value))
                                    for c in content.children or []]
        elif oid == "2.5.29.17":  # Subject Alternative Name
            for child in content.children or []:
                if child.tag_class != "context":
                    continue
                if child.tag_number == 2:
                    ext["san_dns"].append(read_string(child))
                elif child.tag_number == 1:
                    ext["san_email"].append(read_string(child))
                elif child.tag_number == 7 and len(child.raw_value) == 4:
                    ext["san_ip"].append(".".join(str(b) for b in child.raw_value))
                elif child.tag_number == 7 and len(child.raw_value) == 16:
                    ext["san_ip"].append(":".join(
                        f"{(child.raw_value[i] << 8) | child.raw_value[i + 1]:x}"
                        for i in range(0, 16, 2)))
    return ext


def parse_spki(spki: Node) -> tuple[str, int]:
    """SubjectPublicKeyInfo -> (algorithm name, key size in bits)."""
    if not spki.children or len(spki.children) < 2:
        return "unknown", 0
    alg_seq, key_bits = spki.children[0], spki.children[1].raw_value
    if not alg_seq.children:
        return "unknown", 0
    alg_oid = decode_oid(alg_seq.children[0].raw_value)
    key_algorithm = oid_name(alg_oid)
    if alg_oid == "1.2.840.113549.1.1.1":  # RSA
        if len(key_bits) > 1:
            rsa_seq, _ = read_node(key_bits, 1)  # skip unused-bits byte
            if rsa_seq.children:
                mod = rsa_seq.children[0].raw_value
                # A leading 0x00 is the DER positive-sign pad.
                effective = len(mod) - 1 if mod[0] == 0 else len(mod)
                return key_algorithm, effective * 8
    elif alg_oid == "1.2.840.10045.2.1":  # ECDSA
        if len(alg_seq.children) >= 2:
            curve = EC_CURVES.get(decode_oid(alg_seq.children[1].raw_value))
            if curve:
                key_algorithm = f"{key_algorithm} ({curve})"
        # 0x00 unused bits + uncompressed point (0x04 | X | Y).
        if len(key_bits) > 1:
            return key_algorithm, (len(key_bits) - 2) * 8
    elif len(key_bits) > 1:
        return key_algorithm, (len(key_bits) - 1) * 8
    return key_algorithm, 0


def decode_certificate(pem: str) -> dict:
    """Decode the first PEM certificate block into a CertificateInfo dict:
    subject/issuer RDNs + DN strings, validity window (tz-aware UTC), serial
    (uppercase colon-hex), algorithms, key size, extension facts, version."""
    if not pem or not pem.strip():
        raise ValueError("Empty input — paste a PEM certificate")
    blocks = PEM_REGEX.findall(pem)
    if not blocks:
        raise ValueError("No PEM certificate block found — expected -----BEGIN CERTIFICATE-----")
    try:
        der = base64.b64decode(re.sub(r"\s+", "", blocks[0]), validate=True)
    except (binascii.Error, ValueError) as exc:
        raise ValueError(f"Certificate body is not valid base64: {exc}") from exc

    cert_seq, _ = read_node(der, 0)
    kids = cert_seq.children or []
    if len(kids) < 3:
        raise ValueError("Invalid certificate structure: expected TBSCertificate, "
                         "signatureAlgorithm, signatureValue")
    tbs, sig_alg_node = kids[0], kids[1]
    sig_alg_oid = decode_oid(sig_alg_node.children[0].raw_value) if sig_alg_node.children else ""
    if not tbs.children or len(tbs.children) < 7:
        raise ValueError("Invalid TBSCertificate structure")

    idx = 0
    version = 0  # v1 unless the explicit context [0] wrapper is present
    first = tbs.children[0]
    if first.tag_class == "context" and first.tag_number == 0:
        if first.children and len(first.children[0].raw_value) == 1:
            version = first.children[0].raw_value[0]
        idx = 1

    serial_raw = tbs.children[idx].raw_value
    idx += 2  # serial, then the inner signature algorithm
    issuer = parse_rdn(tbs.children[idx])
    idx += 1
    validity = tbs.children[idx]
    idx += 1
    epoch = dt.datetime(1970, 1, 1, tzinfo=dt.timezone.utc)
    not_before = not_after = epoch
    if validity.children and len(validity.children) >= 2:
        not_before, not_after = (parse_time(validity.children[0]),
                                 parse_time(validity.children[1]))
    subject = parse_rdn(tbs.children[idx])
    idx += 1
    key_algorithm, key_size = parse_spki(tbs.children[idx])
    idx += 1

    extensions: dict = {"basic_constraints_ca": None, "key_usage": None,
                        "ext_key_usage": None, "san_dns": [], "san_ip": [], "san_email": []}
    while idx < len(tbs.children):
        child = tbs.children[idx]
        if child.tag_class == "context" and child.tag_number == 3 and child.children:
            outer_seq = child.children[0]
            if outer_seq.children:
                extensions = parse_extensions(outer_seq.children)
        idx += 1

    if len(serial_raw) > 1 and serial_raw[0] == 0:
        serial_raw = serial_raw[1:]  # sign pad, not serial material
    serial = ":".join(f"{b:02x}" for b in serial_raw).upper()

    return {
        "subject": subject, "subject_dn": format_dn(subject),
        "issuer": issuer, "issuer_dn": format_dn(issuer),
        "not_before": not_before, "not_after": not_after,
        "serial_number": serial, "signature_algorithm": oid_name(sig_alg_oid),
        "key_algorithm": key_algorithm, "key_size": key_size,
        "basic_constraints_ca": extensions["basic_constraints_ca"],
        "key_usage": extensions["key_usage"] or [],
        "ext_key_usage": extensions["ext_key_usage"] or [],
        "san_dns": extensions["san_dns"], "san_ip": extensions["san_ip"],
        "san_email": extensions["san_email"], "version": version, "raw_der": der,
    }


def is_expired(cert: dict) -> bool:
    return cert["not_after"] < dt.datetime.now(dt.timezone.utc)


def days_until_expiry(cert: dict) -> int:
    delta = cert["not_after"] - dt.datetime.now(dt.timezone.utc)
    import math
    return math.ceil(delta.total_seconds() / 86400)


def decode_certificate_chain(pem: str) -> list[dict]:
    """Extract every PEM certificate block and decode each one."""
    if not pem or not pem.strip():
        raise ValueError("Empty input — paste PEM certificate(s)")
    blocks = PEM_REGEX.findall(pem)
    if not blocks:
        raise ValueError("No PEM certificate block found — expected -----BEGIN CERTIFICATE-----")
    wrap = "-----BEGIN CERTIFICATE-----\n{}\n-----END CERTIFICATE-----"
    return [decode_certificate(wrap.format(b)) for b in blocks]

Also available in 13 other languages

Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →