Skip to content

Certificate Decoder — Rust 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 Rust 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: Rust (std only — no external crates; base64 and the DER reader
//! are hand-rolled, exactly as in the TS reference).
//! 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 a
//! small recursive TLV reader is all a certificate needs — no X.509 crate
//! hiding the very structure this tool exists to show. It decodes; it never
//! verifies signatures or validates chains: a parsed certificate is not a
//! trusted one. Errors are `Result<_, String>` in place of the TS `throw`.
//!
//! display source — part of CosmoDev's polyglot tool pages.

/// One decoded certificate, mirroring `CertificateInfo` in the TS lib.
/// Times are Unix seconds (the role `Date.getTime()` plays there).
#[derive(Debug, Default)]
pub struct CertInfo {
    pub subject_dn: String,
    pub issuer_dn: String,
    pub not_before: i64,
    pub not_after: i64,
    pub serial_number: String,
    pub signature_algorithm: String,
    pub key_algorithm: String,
    pub key_size: usize,
    pub basic_constraints_ca: Option<bool>,
    pub key_usage: Vec<String>,
    pub ext_key_usage: Vec<String>,
    pub san_dns: Vec<String>,
    pub san_ip: Vec<String>,
    pub san_email: Vec<String>,
    pub version: u32,
    pub raw_der: Vec<u8>,
}

/// Human-readable names for the OIDs certificates actually carry; unknown
/// OIDs fall through as their dotted numbers, exactly like the TS map.
const OID_NAMES: &[(&str, &str)] = &[
    ("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"),
];
const EC_CURVES: &[(&str, &str)] = &[
    ("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.
const KEY_USAGE_BITS: [&str; 9] = [
    "digitalSignature", "nonRepudiation", "keyEncipherment", "dataEncipherment",
    "keyAgreement", "keyCertSign", "cRLSign", "encipherOnly", "decipherOnly",
];

fn oid_name(oid: &str) -> String {
    OID_NAMES.iter().find(|(o, _)| *o == oid)
        .map_or(oid.to_string(), |(_, n)| n.to_string())
}

fn hex(bytes: &[u8], sep: &str) -> String {
    bytes.iter().map(|b| format!("{b:02x}")).collect::<Vec<_>>().join(sep)
}

// ── Base64 (PEM envelope) ──────────────────────────────────────────────────

fn b64_val(b: u8) -> Option<u32> {
    match b {
        b'A'..=b'Z' => Some((b - b'A') as u32),
        b'a'..=b'z' => Some((b - b'a' + 26) as u32),
        b'0'..=b'9' => Some((b - b'0' + 52) as u32),
        b'+' => Some(62),
        b'/' => Some(63),
        _ => None,
    }
}

/// Strict-ish standard Base64: whitespace is tolerated and stripped, padding
/// is optional; anything else is an error (the TS port strips and `atob`s).
fn b64_decode(input: &str) -> Result<Vec<u8>, String> {
    let clean: Vec<u8> = input.bytes().filter(|b| !b.is_ascii_whitespace()).collect();
    let body = match clean.len() % 4 {
        0 if clean.last() == Some(&b'=') => &clean[..clean.iter().rposition(|&b| b != b'=').map_or(0, |p| p + 1)],
        0 => &clean[..],
        2 => &clean[..],
        3 => &clean[..],
        _ => return Err("certificate body is not valid base64".into()),
    };
    let mut out = Vec::with_capacity(body.len() * 3 / 4 + 2);
    for chunk in body.chunks(4) {
        let mut acc = 0u32;
        for &b in chunk {
            acc = (acc << 6) | b64_val(b).ok_or("certificate body is not valid base64")?;
        }
        acc <<= 6 * (4 - chunk.len() as u32);
        out.push((acc >> 16) as u8);
        if chunk.len() > 2 { out.push((acc >> 8) as u8); }
        if chunk.len() > 3 { out.push(acc as u8); }
    }
    Ok(out)
}

/// Collect the Base64 body of every `-----BEGIN CERTIFICATE-----` block.
/// (std has no regex, so the TS regex's `\r?\n` framing is approximated by
/// scanning the markers and stripping whitespace from the body.)
fn pem_blocks(pem: &str) -> Vec<String> {
    let mut blocks = Vec::new();
    let mut rest = pem;
    while let Some(i) = rest.find("-----BEGIN CERTIFICATE-----") {
        let after = &rest[i + 27..];
        match after.find("-----END CERTIFICATE-----") {
            Some(j) => {
                blocks.push(after[..j].chars().filter(|c| !c.is_whitespace()).collect());
                rest = &after[j + 25..];
            }
            None => break,
        }
    }
    blocks
}

// ── DER TLV reader ─────────────────────────────────────────────────────────

#[derive(Debug)]
struct Node {
    /// 0 universal, 1 application, 2 context, 3 private
    tag_class: u8,
    constructed: bool,
    tag_number: u32,
    raw: Vec<u8>,
    children: Option<Vec<Node>>,
}

/// Read one TLV at `pos`; returns (node, next_pos). Every length is
/// bounds-checked against the buffer before the slice: a pasted certificate
/// is untrusted input.
fn read_node(buf: &[u8], pos: usize) -> Result<(Node, usize), String> {
    let mut pos = pos;
    let byte0 = *buf.get(pos).ok_or("Unexpected end of DER data")?;
    pos += 1;
    let tag_class = byte0 >> 6;
    let constructed = byte0 & 0x20 != 0;
    let mut tag_number = (byte0 & 0x1f) as u32;
    if tag_number == 0x1f {
        // Long-form tag number (>= 31).
        tag_number = 0;
        loop {
            let b = *buf.get(pos).ok_or("Unexpected end of DER data")?;
            pos += 1;
            tag_number = (tag_number << 7) | (b & 0x7f) as u32;
            if b & 0x80 == 0 { break; }
        }
    }
    let first = *buf.get(pos).ok_or("Unexpected end of DER data")?;
    pos += 1;
    let length = if first < 0x80 {
        first as usize
    } else {
        let n = (first & 0x7f) as usize;
        if n == 0 { return Err("Indefinite length is not supported in DER".into()); }
        if n > 4 { return Err(format!("Length too large: {n} bytes")); }
        if pos + n > buf.len() { return Err("Unexpected end of DER data".into()); }
        let mut len = 0usize;
        for i in 0..n { len = (len << 8) | buf[pos + i] as usize; }
        pos += n;
        len
    };
    if pos + length > buf.len() {
        return Err(format!(
            "Truncated DER: need {length} bytes at offset {pos}, but only {} remain",
            buf.len() - pos));
    }
    let raw = buf[pos..pos + length].to_vec();
    let mut node = Node { tag_class, constructed, tag_number, raw, children: None };
    if constructed && length > 0 {
        let mut children = Vec::new();
        let mut p = pos;
        while p < pos + length {
            let (child, next) = read_node(buf, p)?;
            children.push(child);
            p = next;
        }
        node.children = Some(children);
    }
    Ok((node, pos + length))
}

// ── Small helpers ──────────────────────────────────────────────────────────

fn decode_oid(raw: &[u8]) -> Result<String, String> {
    if raw.is_empty() { return Err("Empty OID".into()); }
    let mut parts = vec![(raw[0] / 40).to_string(), (raw[0] % 40).to_string()];
    let mut value = 0u64;
    for &b in &raw[1..] {
        value = (value << 7) | (b & 0x7f) as u64;
        if b & 0x80 == 0 {
            parts.push(value.to_string());
            value = 0;
        }
    }
    Ok(parts.join("."))
}

/// Known text tags (UTF8String 12, PrintableString 19, IA5String 22,
/// BMPString 30, 36) decode as UTF-8 with invalid bytes replaced; anything
/// else only if it is valid UTF-8, else colon-separated hex (no mojibake).
fn read_string(node: &Node) -> String {
    if matches!(node.tag_number, 12 | 19 | 22 | 30 | 36) {
        return String::from_utf8_lossy(&node.raw).into_owned();
    }
    match std::str::from_utf8(&node.raw) {
        Ok(s) => s.to_string(),
        Err(_) => hex(&node.raw, ":"),
    }
}

/// Days since 1970-01-01 for a proleptic Gregorian date (Hinnant's algorithm
/// — std has no date math).
fn days_from_civil(y: i64, m: i64, d: i64) -> i64 {
    let y = if m <= 2 { y - 1 } else { y };
    let era = if y >= 0 { y } else { y - 399 } / 400;
    let yoe = y - era * 400;
    let doy = (153 * ((m + 9) % 12) + 2) / 5 + d - 1;
    era * 146097 + yoe * 365 + yoe / 4 - yoe / 100 + doy - 719468
}

/// UTCTime (tag 23, two-digit year window) / GeneralizedTime (tag 24),
/// both `...Z` — returned as Unix seconds.
fn parse_time(node: &Node) -> Result<i64, String> {
    let digits = |s: &[u8]| s.iter().all(|b| b.is_ascii_digit());
    let two = |s: &[u8]| (s[0] - b'0') as i64 * 10 + (s[1] - b'0') as i64;
    let (year, rest) = match node.tag_number {
        23 if node.raw.len() == 13 && node.raw[12] == b'Z' && digits(&node.raw[..12]) => {
            let yy = two(&node.raw[..2]);
            (if yy >= 50 { 1900 + yy } else { 2000 + yy }, &node.raw[2..12])
        }
        24 if node.raw.len() == 15 && node.raw[14] == b'Z' && digits(&node.raw[..14]) => {
            (((node.raw[0] - b'0') as i64 * 1000 + (node.raw[1] - b'0') as i64 * 100
                + (node.raw[2] - b'0') as i64 * 10 + (node.raw[3] - b'0') as i64), &node.raw[4..14])
        }
        _ => return Err(format!("Unknown or invalid time tag: {}", node.tag_number)),
    };
    let (mo, d, h, mi, s) = (
        two(&rest[0..2]), two(&rest[2..4]), two(&rest[4..6]),
        two(&rest[6..8]), two(&rest[8..10]),
    );
    Ok((days_from_civil(year, mo, d) * 86400 + h * 3600 + mi * 60 + s) as i64)
}

/// RDN sequence -> "CN=example.com, O=CosmoDev" style DN string.
fn parse_dn(seq: &Node) -> Result<String, String> {
    let mut parts = Vec::new();
    for set in seq.children.iter().flatten() {
        for attr in set.children.iter().flatten() {
            if let Some(kids) = &attr.children {
                if kids.len() >= 2 {
                    parts.push(format!(
                        "{}={}",
                        oid_name(&decode_oid(&kids[0].raw)?),
                        read_string(&kids[1])));
                }
            }
        }
    }
    Ok(parts.join(", "))
}

// ── Extensions ─────────────────────────────────────────────────────────────

/// The handful of extensions the TS port surfaces: Basic Constraints CA flag,
/// Key Usage bit names, Extended Key Usage purposes, and the DNS/IP/email
/// Subject Alternative Names.
fn parse_extensions(exts: &[Node]) -> Result<(Option<bool>, Vec<String>, Vec<String>, Vec<String>, Vec<String>, Vec<String>), String> {
    let (mut bc_ca, mut ku, mut eku) = (None, Vec::new(), Vec::new());
    let (mut dns, mut ips, mut emails) = (Vec::new(), Vec::new(), Vec::new());
    for node in exts {
        let kids = match &node.children { Some(k) if k.len() >= 2 => k, _ => continue };
        let oid = decode_oid(&kids[0].raw)?;
        // Skip the `critical` BOOLEAN when present; the value is an OCTET
        // STRING wrapping the extension's own DER.
        let value_idx = if kids.len() >= 3 && kids[1].tag_class == 0 && kids[1].tag_number == 1 { 2 } else { 1 };
        let octet = &kids[value_idx].raw;
        if octet.is_empty() { continue; }
        let (content, _) = read_node(octet, 0)?;
        match oid.as_str() {
            "2.5.29.19" => {
                // Basic Constraints: default false when present, true only on
                // an explicit cA=TRUE.
                let flag = content.children.as_ref().and_then(|c| c.first());
                bc_ca = Some(matches!(flag, Some(f) if f.tag_number == 1 && f.raw == [0xff]));
            }
            "2.5.29.15" => {
                // Key Usage — BIT STRING: first byte is the unused-bit count.
                ku = Vec::new();
                if content.raw.len() >= 2 {
                    let (unused, octets) = (content.raw[0], &content.raw[1..]);
                    for (i, name) in KEY_USAGE_BITS.iter().enumerate() {
                        if i / 8 < octets.len() && octets[i / 8] & (1 << (7 - i % 8)) != 0 {
                            ku.push(name.to_string());
                        }
                    }
                    while unused > 0 && !ku.is_empty()
                        && ku.len() as i32 > octets.len() as i32 * 8 - unused as i32 {
                        ku.pop();
                    }
                }
            }
            "2.5.29.37" => {
                // Extended Key Usage — SEQUENCE of OIDs.
                eku = content.children.iter().flatten()
                    .map(|c| decode_oid(&c.raw)).collect::<Result<Vec<_>, _>>()?
                    .iter().map(|o| oid_name(o)).collect();
            }
            "2.5.29.17" => {
                // Subject Alternative Name: context tag 2 = dNSName, 7 =
                // iPAddress (4 bytes dotted IPv4 / 16 bytes IPv6 hex groups),
                // 1 = rfc822Name.
                for child in content.children.iter().flatten() {
                    if child.tag_class != 2 { continue; }
                    match child.tag_number {
                        2 => dns.push(read_string(child)),
                        1 => emails.push(read_string(child)),
                        7 if child.raw.len() == 4 => {
                            ips.push(child.raw.iter().map(|b| b.to_string()).collect::<Vec<_>>().join("."));
                        }
                        7 if child.raw.len() == 16 => {
                            ips.push((0..16).step_by(2)
                                .map(|i| format!("{:x}", (child.raw[i] as u16) << 8 | child.raw[i + 1] as u16))
                                .collect::<Vec<_>>().join(":"));
                        }
                        _ => {}
                    }
                }
            }
            _ => {}
        }
    }
    Ok((bc_ca, ku, eku, dns, ips, emails))
}

/// SubjectPublicKeyInfo -> (algorithm name, key size in bits). RSA reads the
/// modulus length; ECDSA names the curve and uses the point length.
fn parse_spki(spki: &Node) -> (String, usize) {
    let kids = match &spki.children { Some(k) if k.len() >= 2 => k, _ => return ("unknown".into(), 0) };
    let alg_seq = &kids[0];
    let key_bits = &kids[1].raw;
    let first_alg = match alg_seq.children.as_ref().and_then(|c| c.first()) {
        Some(a) => a,
        None => return ("unknown".into(), 0),
    };
    let alg_oid = match decode_oid(&first_alg.raw) {
        Ok(o) => o,
        Err(_) => return ("unknown".into(), 0),
    };
    let name = oid_name(&alg_oid);
    if alg_oid == "1.2.840.113549.1.1.1" {
        // RSA: BIT STRING = 0x00 unused bits + DER SEQUENCE { modulus, exponent }.
        if key_bits.len() > 1 {
            if let Ok((rsa_seq, _)) = read_node(key_bits, 1) {
                if let Some(mod_bytes) = rsa_seq.children.as_ref().and_then(|c| c.first()) {
                    // A leading 0x00 is the DER positive-sign pad.
                    let effective = if mod_bytes.raw.first() == Some(&0) { mod_bytes.raw.len() - 1 } else { mod_bytes.raw.len() };
                    return (name, effective * 8);
                }
            }
        }
        (name, 0)
    } else if alg_oid == "1.2.840.10045.2.1" {
        let mut name = name;
        if let Some(params) = alg_seq.children.as_ref().and_then(|c| c.get(1)) {
            if let Ok(curve_oid) = decode_oid(&params.raw) {
                if let Some((_, curve)) = EC_CURVES.iter().find(|(o, _)| *o == curve_oid) {
                    name = format!("{name} ({curve})");
                }
            }
        }
        // 0x00 unused bits + uncompressed point (0x04 | X | Y).
        if key_bits.len() > 1 { (name, (key_bits.len() - 2) * 8) } else { (name, 0) }
    } else if key_bits.len() > 1 {
        (name, (key_bits.len() - 1) * 8)
    } else {
        (name, 0)
    }
}

fn unix_now() -> i64 {
    std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_secs() as i64)
        .unwrap_or(0)
}

/// True once `not_after` has passed.
pub fn is_expired(cert: &CertInfo) -> bool {
    cert.not_after < unix_now()
}

/// Whole days until expiry, ceiled — matches the TS `daysUntilExpiry`.
pub fn days_until_expiry(cert: &CertInfo) -> i64 {
    let diff = (cert.not_after - unix_now()) as f64;
    (diff / 86_400.0).ceil() as i64
}

/// Decode the first PEM certificate block into a `CertInfo`.
pub fn decode_certificate(pem: &str) -> Result<CertInfo, String> {
    if pem.trim().is_empty() {
        return Err("Empty input — paste a PEM certificate".into());
    }
    let block = pem_blocks(pem).into_iter().next()
        .ok_or("No PEM certificate block found — expected -----BEGIN CERTIFICATE-----")?;
    let der = b64_decode(&block)?;
    decode_der(&der)
}

/// Decode an already-extracted DER certificate body.
fn decode_der(der: &[u8]) -> Result<CertInfo, String> {
    let (cert_seq, _) = read_node(der, 0)?;
    let kids = cert_seq.children.as_deref().unwrap_or(&[]);
    if kids.len() < 3 {
        return Err("Invalid certificate structure: expected TBSCertificate, signatureAlgorithm, signatureValue".into());
    }
    let tbs = &kids[0];
    let sig_alg_oid = kids[1].children.as_ref().and_then(|c| c.first())
        .map(|n| decode_oid(&n.raw)).transpose()?.unwrap_or_default();
    let tbs_kids = match &tbs.children {
        Some(k) if k.len() >= 7 => k,
        _ => return Err("Invalid TBSCertificate structure".into()),
    };
    let mut idx = 0usize;
    // Version (explicit context [0]); absent means v1.
    let mut version = 0;
    if tbs_kids[0].tag_class == 2 && tbs_kids[0].tag_number == 0 {
        if let Some(v) = tbs_kids[0].children.as_ref().and_then(|c| c.first()) {
            if v.raw.len() == 1 { version = v.raw[0] as u32; }
        }
        idx = 1;
    }
    let serial_raw = &tbs_kids[idx].raw;
    idx += 2; // serial, then the inner signature algorithm
    let issuer_dn = parse_dn(&tbs_kids[idx])?;
    idx += 1;
    let validity = &tbs_kids[idx];
    idx += 1;
    let (mut not_before, mut not_after) = (0i64, 0i64);
    if let Some(v) = &validity.children {
        if v.len() >= 2 {
            not_before = parse_time(&v[0])?;
            not_after = parse_time(&v[1])?;
        }
    }
    let subject_dn = parse_dn(&tbs_kids[idx])?;
    idx += 1;
    let (key_algorithm, key_size) = parse_spki(&tbs_kids[idx]);
    idx += 1;
    // Extensions — context [3] after subjectPublicKeyInfo.
    let mut parsed = (None, Vec::new(), Vec::new(), Vec::new(), Vec::new(), Vec::new());
    while idx < tbs_kids.len() {
        let child = &tbs_kids[idx];
        if child.tag_class == 2 && child.tag_number == 3 {
            if let Some(outer) = child.children.as_ref().and_then(|c| c.first()) {
                if let Some(entries) = &outer.children {
                    parsed = parse_extensions(entries)?;
                }
            }
        }
        idx += 1;
    }
    let (bc_ca, ku, eku, dns, ips, emails) = parsed;
    // Serial as uppercase colon-separated hex, sign pad removed.
    let serial_bytes: &[u8] = if serial_raw.len() > 1 && serial_raw[0] == 0 { &serial_raw[1..] } else { serial_raw };
    Ok(CertInfo {
        subject_dn, issuer_dn, not_before, not_after,
        serial_number: hex(serial_bytes, ":").to_uppercase(),
        signature_algorithm: oid_name(&sig_alg_oid),
        key_algorithm, key_size,
        basic_constraints_ca: bc_ca,
        key_usage: ku, ext_key_usage: eku,
        san_dns: dns, san_ip: ips, san_email: emails,
        version, raw_der: der.to_vec(),
    })
}

/// Extract every PEM certificate block and decode each one.
pub fn decode_certificate_chain(pem: &str) -> Result<Vec<CertInfo>, String> {
    if pem.trim().is_empty() {
        return Err("Empty input — paste PEM certificate(s)".into());
    }
    let blocks = pem_blocks(pem);
    if blocks.is_empty() {
        return Err("No PEM certificate block found — expected -----BEGIN CERTIFICATE-----".into());
    }
    blocks.iter().map(|b| b64_decode(b)).collect::<Result<Vec<_>, _>>()?
        .iter().map(|der| decode_der(der)).collect()
}

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 →