Certificate Decoder — JavaScript 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 JavaScript 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: JavaScript (ES module; runs in browsers, Node >= 16, Bun, Deno).
* 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 library
* 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.
*
* display source — part of CosmoDev's polyglot tool pages.
*/
// 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 = {
'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 = { '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' };
const KEY_USAGE_BITS = ['digitalSignature', 'nonRepudiation', 'keyEncipherment', 'dataEncipherment', 'keyAgreement', 'keyCertSign', 'cRLSign', 'encipherOnly', 'decipherOnly'];
const PEM_REGEX = /-----BEGIN\s+CERTIFICATE-----\s*\r?\n([\s\S]*?)\r?\n-----END\s+CERTIFICATE-----/g;
const hex = (bytes, sep) => Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join(sep);
const oidName = (oid) => OID_NAMES[oid] ?? oid;
/**
* Read one DER TLV node: { tagClass, constructed, tagNumber, rawValue,
* offset, children? }. Returns [node, nextPos] so callers drive the cursor;
* constructed nodes parse their children eagerly, like the TS DERParser.
*/
function readNode(buf, pos) {
const offset = pos;
const byte0 = buf[pos++];
const tagClass = ['universal', 'application', 'context', 'private'][(byte0 >> 6) & 3];
const constructed = (byte0 & 0x20) !== 0;
let tagNumber = byte0 & 0x1f;
if (tagNumber === 0x1f) { // long-form tag number
tagNumber = 0;
let b;
do { b = buf[pos++]; tagNumber = (tagNumber << 7) | (b & 0x7f); } while (b & 0x80);
}
let length = buf[pos++];
if (length >= 0x80) {
const n = length & 0x7f;
if (n === 0) throw new Error('Indefinite length is not supported in DER');
if (n > 4) throw new Error(`Length too large: ${n} bytes`);
length = 0;
for (let i = 0; i < n; i++) length = (length << 8) | buf[pos++];
}
if (pos + length > buf.length)
throw new Error(`Truncated DER: need ${length} bytes at offset ${pos}, but only ${buf.length - pos} remain`);
const node = { tagClass, constructed, tagNumber, rawValue: buf.slice(pos, pos + length), offset };
if (constructed && length > 0) {
node.children = [];
for (let p = pos; p < pos + length;) {
const [child, next] = readNode(buf, p);
node.children.push(child);
p = next;
}
}
return [node, pos + length];
}
function decodeOID(bytes) {
if (bytes.length === 0) throw new Error('Empty OID');
const parts = [Math.floor(bytes[0] / 40), bytes[0] % 40];
let value = 0;
for (let i = 1; i < bytes.length; i++) {
value = (value << 7) | (bytes[i] & 0x7f);
if ((bytes[i] & 0x80) === 0) { parts.push(value); value = 0; }
}
return parts.join('.');
}
function readString(node) {
// UTF8String(12), PrintableString(19), IA5String(22), BMPString(30), 36 are
// text by definition; anything else only if it is valid UTF-8, else hex.
if ([12, 19, 22, 30, 36].includes(node.tagNumber)) return new TextDecoder().decode(node.rawValue);
try { return new TextDecoder('utf-8', { fatal: true }).decode(node.rawValue); }
catch { return hex(node.rawValue, ':'); }
}
function parseTime(node) {
const utc = node.tagNumber === 23; // UTCTime else GeneralizedTime
const m = utc || node.tagNumber === 24
? readString(node).match(utc ? /^(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})Z$/ : /^(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})Z$/)
: null;
if (!m) throw new Error(`Invalid or unsupported time value (tag ${node.tagNumber})`);
let year = Number(m[1]);
if (utc) year += year >= 50 ? 1900 : 2000; // UTCTime's two-digit year window
return new Date(Date.UTC(year, m[2] - 1, m[3], m[4], m[5], m[6]));
}
function parseRDN(node) {
const attrs = [];
for (const set of node.children ?? []) for (const seq of set.children ?? []) {
if (!seq.children || seq.children.length < 2) continue;
attrs.push({ type: oidName(decodeOID(seq.children[0].rawValue)), value: readString(seq.children[1]) });
}
return attrs;
}
const formatDN = (attrs) => attrs.map((a) => `${a.type}=${a.value}`).join(', ');
// Extension payload: Basic Constraints CA flag, Key Usage bit names,
// Extended Key Usage purposes, and the DNS/IP/email SANs.
function parseExtensions(nodes) {
const ext = { basicConstraintsCA: null, keyUsage: null, extKeyUsage: null, sanDNS: [], sanIP: [], sanEmail: [] };
for (const node of nodes) {
if (!node.children || node.children.length < 2) continue;
const oid = decodeOID(node.children[0].rawValue);
// Skip the `critical` BOOLEAN when present; the value is an OCTET STRING
// wrapping the extension's own DER.
const valueIdx = node.children.length >= 3 && node.children[1].tagNumber === 1 && node.children[1].tagClass === 'universal' ? 2 : 1;
const octet = node.children[valueIdx].rawValue;
if (octet.length === 0) continue;
const [content] = readNode(octet, 0);
if (oid === '2.5.29.19') { // Basic Constraints
const flag = content.children?.[0];
ext.basicConstraintsCA = !!(flag && flag.tagNumber === 1 && flag.rawValue.length === 1 && flag.rawValue[0] === 0xff);
} else if (oid === '2.5.29.15') { // Key Usage — BIT STRING
if (content.rawValue.length < 2) { ext.keyUsage = []; continue; }
const octets = content.rawValue.slice(1);
const flags = [];
for (let i = 0; i < KEY_USAGE_BITS.length; i++) {
if ((i >> 3) < octets.length && (octets[i >> 3] & (1 << (7 - (i % 8)))) !== 0) flags.push(KEY_USAGE_BITS[i]);
}
while (content.rawValue[0] > 0 && flags.length > octets.length * 8 - content.rawValue[0]) flags.pop();
ext.keyUsage = flags;
} else if (oid === '2.5.29.37') { // Extended Key Usage
ext.extKeyUsage = (content.children ?? []).map((c) => oidName(decodeOID(c.rawValue)));
} else if (oid === '2.5.29.17') { // Subject Alternative Name
for (const child of content.children ?? []) {
if (child.tagClass !== 'context') continue;
if (child.tagNumber === 2) ext.sanDNS.push(readString(child));
else if (child.tagNumber === 1) ext.sanEmail.push(readString(child));
else if (child.tagNumber === 7 && child.rawValue.length === 4)
ext.sanIP.push(Array.from(child.rawValue).join('.'));
else if (child.tagNumber === 7 && child.rawValue.length === 16)
ext.sanIP.push(Array.from({ length: 8 }, (_, i) => ((child.rawValue[i * 2] << 8) | child.rawValue[i * 2 + 1]).toString(16)).join(':'));
}
}
}
return ext;
}
// SubjectPublicKeyInfo -> { keyAlgorithm, keySize (bits) }. RSA reads the
// modulus length; ECDSA names the curve and uses the point length; anything
// else falls back to the BIT STRING body length.
function parseSPKI(spki) {
const out = { keyAlgorithm: 'unknown', keySize: 0 };
if (!spki.children || spki.children.length < 2) return out;
const [algSeq, keyBitsNode] = spki.children;
if (!algSeq.children || algSeq.children.length < 1) return out;
const algOID = decodeOID(algSeq.children[0].rawValue);
const keyBits = keyBitsNode.rawValue;
out.keyAlgorithm = oidName(algOID);
if (algOID === '1.2.840.113549.1.1.1') { // RSA
if (keyBits.length > 1) {
const [rsaSeq] = readNode(keyBits, 1); // skip the unused-bits byte
const mod = rsaSeq.children?.[0]?.rawValue;
// A leading 0x00 is the DER positive-sign pad, not modulus material.
if (mod) out.keySize = (mod[0] === 0 ? mod.length - 1 : mod.length) * 8;
}
} else if (algOID === '1.2.840.10045.2.1') { // ECDSA
if (algSeq.children.length >= 2) {
const curve = EC_CURVES[decodeOID(algSeq.children[1].rawValue)];
if (curve) out.keyAlgorithm = `${out.keyAlgorithm} (${curve})`;
}
// 0x00 unused bits + uncompressed point (0x04 | X | Y): drop both prefixes.
if (keyBits.length > 1) out.keySize = (keyBits.length - 2) * 8;
} else if (keyBits.length > 1) {
out.keySize = (keyBits.length - 1) * 8;
}
return out;
}
function pemToDER(block) {
const binary = atob(block.replace(/\s/g, ''));
return Uint8Array.from(binary, (ch) => ch.charCodeAt(0));
}
/**
* Decode the first PEM certificate block into a plain-object CertificateInfo:
* subject/issuer RDNs + DN strings, validity window, serial (uppercase
* colon-hex), algorithms, key size, extension facts, version and raw DER.
*/
export function decodeCertificate(pem) {
if (!pem || !pem.trim()) throw new Error('Empty input — paste a PEM certificate');
const blocks = [...pem.matchAll(PEM_REGEX)].map((m) => m[1]);
if (blocks.length === 0)
throw new Error('No PEM certificate block found — expected -----BEGIN CERTIFICATE-----');
const der = pemToDER(blocks[0]);
const [certSeq] = readNode(der, 0);
const kids = certSeq.children ?? [];
if (kids.length < 3)
throw new Error('Invalid certificate structure: expected TBSCertificate, signatureAlgorithm, signatureValue');
const [tbs, sigAlgNode] = kids;
const sigAlgOID = sigAlgNode.children ? decodeOID(sigAlgNode.children[0].rawValue) : '';
if (!tbs.children || tbs.children.length < 7) throw new Error('Invalid TBSCertificate structure');
let idx = 0;
let version = 0; // v1 unless the explicit context [0] wrapper is present
if (tbs.children[idx].tagClass === 'context' && tbs.children[idx].tagNumber === 0) {
const v = tbs.children[idx].children?.[0];
if (v && v.rawValue.length === 1) version = v.rawValue[0];
idx++;
}
const serialNode = tbs.children[idx++];
idx++; // the inner signature algorithm
const issuer = parseRDN(tbs.children[idx++]);
const validity = tbs.children[idx++];
let notBefore = new Date(0);
let notAfter = new Date(0);
if (validity.children && validity.children.length >= 2) {
notBefore = parseTime(validity.children[0]);
notAfter = parseTime(validity.children[1]);
}
const subject = parseRDN(tbs.children[idx++]);
const { keyAlgorithm, keySize } = parseSPKI(tbs.children[idx++]);
let extensions = { basicConstraintsCA: null, keyUsage: null, extKeyUsage: null, sanDNS: [], sanIP: [], sanEmail: [] };
for (; idx < tbs.children.length; idx++) {
const child = tbs.children[idx];
if (child.tagClass === 'context' && child.tagNumber === 3 && child.children) {
const outerSeq = child.children[0];
if (outerSeq?.children) extensions = parseExtensions(outerSeq.children);
}
}
let serialBytes = serialNode.rawValue;
if (serialBytes[0] === 0 && serialBytes.length > 1) serialBytes = serialBytes.slice(1); // sign pad
return {
subject, subjectDN: formatDN(subject), issuer, issuerDN: formatDN(issuer),
notBefore, notAfter,
serialNumber: serialBytes.length ? hex(serialBytes, ':').toUpperCase() : '',
signatureAlgorithm: oidName(sigAlgOID), keyAlgorithm, keySize,
basicConstraintsCA: extensions.basicConstraintsCA,
keyUsage: extensions.keyUsage ?? [], extKeyUsage: extensions.extKeyUsage ?? [],
sanDNS: extensions.sanDNS, sanIP: extensions.sanIP, sanEmail: extensions.sanEmail,
version, rawDER: der,
};
}
export const isExpired = (cert) => cert.notAfter < new Date();
export const daysUntilExpiry = (cert) => Math.ceil((cert.notAfter.getTime() - Date.now()) / 86400000);
/** Extract every PEM certificate block and decode each one. */
export function decodeCertificateChain(pem) {
if (!pem || !pem.trim()) throw new Error('Empty input — paste PEM certificate(s)');
const blocks = [...pem.matchAll(PEM_REGEX)].map((m) => m[1]);
if (blocks.length === 0)
throw new Error('No PEM certificate block found — expected -----BEGIN CERTIFICATE-----');
return blocks.map((block) => decodeCertificate(`-----BEGIN CERTIFICATE-----\n${block}\n-----END CERTIFICATE-----`));
}
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 →