Certificate Decoder — PHP 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 PHP implementation — the same logic the interactive tool runs, in a shareable, citable form.
<?php
/**
* cert-decoder — Pure ASN.1 DER parser + X.509 certificate decoder.
*
* Language: PHP 7.4+ (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 a
* byte-cursor TLV reader over PHP's raw byte strings decodes a certificate
* without OpenSSL. 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.
*/
declare(strict_types=1);
// 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-----/';
function hexBytes(string $bytes, string $sep): string { return $bytes === '' ? '' : implode($sep, array_map(fn (string $b) => sprintf('%02x', ord($b)), str_split($bytes))); }
function oidName(string $oid): string { return OID_NAMES[$oid] ?? $oid; }
/** Extract every -----BEGIN CERTIFICATE----- body in the input. */
function pemBlocks(string $pem): array { return preg_match_all(PEM_REGEX, $pem, $m, PREG_SET_ORDER) ? array_column($m, 1) : []; }
/**
* Read one DER TLV node at $pos: ['class', 'constructed', 'tag', 'value',
* 'offset', 'children']. Returns [node, nextPos] so callers drive the cursor;
* constructed nodes parse their children eagerly, like the TS DERParser.
*/
function readNode(string $buf, int $pos): array
{
if ($pos >= strlen($buf)) throw new RuntimeException('Unexpected end of DER data');
$offset = $pos;
$b0 = ord($buf[$pos++]);
$class = ['universal', 'application', 'context', 'private'][($b0 >> 6) & 3];
$constructed = ($b0 & 0x20) !== 0;
$tag = $b0 & 0x1f;
if ($tag === 0x1f) { // long-form tag number
$tag = 0;
do { $b = ord($buf[$pos++]); $tag = ($tag << 7) | ($b & 0x7f); } while ($b & 0x80);
}
$len = ord($buf[$pos++]);
if ($len >= 0x80) {
$n = $len & 0x7f;
if ($n === 0) throw new RuntimeException('Indefinite length is not supported in DER');
if ($n > 4) throw new RuntimeException("Length too large: {$n} bytes");
$len = 0;
for ($i = 0; $i < $n; $i++) { $len = ($len << 8) | ord($buf[$pos++]); }
}
if ($pos + $len > strlen($buf)) {
throw new RuntimeException("Truncated DER: need {$len} bytes at offset {$pos}, but only " . (strlen($buf) - $pos) . ' remain');
}
$node = ['class' => $class, 'constructed' => $constructed, 'tag' => $tag, 'value' => substr($buf, $pos, $len), 'offset' => $offset, 'children' => null];
if ($constructed && $len > 0) {
$node['children'] = [];
for ($p = $pos; $p < $pos + $len;) { [$child, $p] = readNode($buf, $p); $node['children'][] = $child; }
}
return [$node, $pos + $len];
}
function decodeOID(string $bytes): string
{
if ($bytes === '') throw new RuntimeException('Empty OID');
$first = ord($bytes[0]);
$parts = [intdiv($first, 40), $first % 40];
$value = 0;
for ($i = 1, $n = strlen($bytes); $i < $n; $i++) {
$b = ord($bytes[$i]);
$value = ($value << 7) | ($b & 0x7f);
if (($b & 0x80) === 0) { $parts[] = $value; $value = 0; }
}
return implode('.', $parts);
}
function readString(array $node): string
{
// 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 (in_array($node['tag'], [12, 19, 22, 30, 36], true)) return $node['value'];
return preg_match('//u', $node['value']) === 1 ? $node['value'] : hexBytes($node['value'], ':');
}
function parseTime(array $node): DateTimeImmutable
{
$utc = $node['tag'] === 23; // UTCTime else GeneralizedTime
$ok = ($utc || $node['tag'] === 24) && preg_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$/', readString($node), $m) === 1;
if (!$ok) throw new RuntimeException("Invalid or unsupported time value (tag {$node['tag']})");
$year = (int) $m[1];
if ($utc) $year += $year >= 50 ? 1900 : 2000; // UTCTime's two-digit year window
return new DateTimeImmutable('@' . gmmktime((int) $m[4], (int) $m[5], (int) $m[6], (int) $m[2], (int) $m[3], $year));
}
function parseRDN(array $node): array
{
$attrs = [];
foreach ($node['children'] ?? [] as $set) foreach ($set['children'] ?? [] as $seq) {
if (!$seq['children'] || count($seq['children']) < 2) continue;
$attrs[] = ['type' => oidName(decodeOID($seq['children'][0]['value'])), 'value' => readString($seq['children'][1])];
}
return $attrs;
}
function formatDN(array $attrs): string { return implode(', ', array_map(fn (array $a) => "{$a['type']}={$a['value']}", $attrs)); }
// Extension payload: Basic Constraints CA flag, Key Usage bit names,
// Extended Key Usage purposes, and the DNS/IP/email SANs.
function parseExtensions(array $nodes): array
{
$ext = ['basicConstraintsCA' => null, 'keyUsage' => null, 'extKeyUsage' => null, 'sanDNS' => [], 'sanIP' => [], 'sanEmail' => []];
foreach ($nodes as $node) {
if (!$node['children'] || count($node['children']) < 2) continue;
[$oidNode, $c] = [$node['children'][0], $node['children']];
$oid = decodeOID($oidNode['value']);
// Skip the `critical` BOOLEAN when present; the value is an OCTET STRING
// wrapping the extension's own DER.
$vi = count($c) >= 3 && $c[1]['tag'] === 1 && $c[1]['class'] === 'universal' ? 2 : 1;
$octet = $c[$vi]['value'];
if ($octet === '') continue;
[$content] = readNode($octet, 0);
if ($oid === '2.5.29.19') { // Basic Constraints
$flag = $content['children'][0] ?? null;
$ext['basicConstraintsCA'] = $flag !== null && $flag['tag'] === 1 && $flag['value'] === "\xff";
} elseif ($oid === '2.5.29.15') { // Key Usage — BIT STRING
$ext['keyUsage'] = [];
if (strlen($content['value']) >= 2) {
$raw = $content['value'];
$octets = substr($raw, 1);
$flags = [];
for ($i = 0, $total = count(KEY_USAGE_BITS); $i < $total; $i++) {
if (($i >> 3) < strlen($octets) && ((ord($octets[$i >> 3]) >> (7 - ($i % 8))) & 1) === 1) $flags[] = KEY_USAGE_BITS[$i];
}
while (ord($raw[0]) > 0 && count($flags) > strlen($octets) * 8 - ord($raw[0])) array_pop($flags);
$ext['keyUsage'] = $flags;
}
} elseif ($oid === '2.5.29.37') { // Extended Key Usage
$ext['extKeyUsage'] = array_map(fn (array $ch) => oidName(decodeOID($ch['value'])), $content['children'] ?? []);
} elseif ($oid === '2.5.29.17') { // Subject Alternative Name
foreach ($content['children'] ?? [] as $ch) {
if ($ch['class'] !== 'context') continue;
if ($ch['tag'] === 2) $ext['sanDNS'][] = readString($ch);
elseif ($ch['tag'] === 1) $ext['sanEmail'][] = readString($ch);
elseif ($ch['tag'] === 7 && strlen($ch['value']) === 4) $ext['sanIP'][] = implode('.', array_map('ord', str_split($ch['value'])));
elseif ($ch['tag'] === 7 && strlen($ch['value']) === 16) {
$parts = [];
for ($i = 0; $i < 16; $i += 2) $parts[] = dechex((ord($ch['value'][$i]) << 8) | ord($ch['value'][$i + 1]));
$ext['sanIP'][] = implode(':', $parts);
}
}
}
}
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(array $spki): array
{
$out = ['keyAlgorithm' => 'unknown', 'keySize' => 0];
if (!$spki['children'] || count($spki['children']) < 2) return $out;
[$algSeq, $keyBitsNode] = $spki['children'];
if (!$algSeq['children'] || count($algSeq['children']) < 1) return $out;
$algOID = decodeOID($algSeq['children'][0]['value']);
$keyBits = $keyBitsNode['value'];
$out['keyAlgorithm'] = oidName($algOID);
if ($algOID === '1.2.840.113549.1.1.1') { // RSA
if (strlen($keyBits) > 1) {
[$rsaSeq] = readNode($keyBits, 1); // skip the unused-bits byte
$mod = $rsaSeq['children'][0]['value'] ?? '';
// A leading 0x00 is the DER positive-sign pad, not modulus material.
if ($mod !== '') $out['keySize'] = ($mod[0] === "\x00" ? strlen($mod) - 1 : strlen($mod)) * 8;
}
} elseif ($algOID === '1.2.840.10045.2.1') { // ECDSA
if (count($algSeq['children']) >= 2) {
$curve = EC_CURVES[decodeOID($algSeq['children'][1]['value'])] ?? null;
if ($curve !== null) $out['keyAlgorithm'] .= " ({$curve})";
}
// 0x00 unused bits + uncompressed point (0x04 | X | Y): drop both prefixes.
if (strlen($keyBits) > 1) $out['keySize'] = (strlen($keyBits) - 2) * 8;
} elseif (strlen($keyBits) > 1) {
$out['keySize'] = (strlen($keyBits) - 1) * 8;
}
return $out;
}
/**
* Decode the first PEM certificate block into an associative CertificateInfo:
* subject/issuer RDNs + DN strings, validity window, serial (uppercase
* colon-hex), algorithms, key size, extension facts, version and raw DER.
*
* @throws RuntimeException on empty input, missing PEM block, or bad DER.
*/
function decodeCertificate(string $pem): array
{
if (trim($pem) === '') throw new RuntimeException('Empty input — paste a PEM certificate');
$blocks = pemBlocks($pem);
if (!$blocks) throw new RuntimeException('No PEM certificate block found — expected -----BEGIN CERTIFICATE-----');
$der = base64_decode(preg_replace('/\s+/', '', $blocks[0]), true);
if ($der === false) throw new RuntimeException('Invalid Base64 in PEM body');
[$certSeq] = readNode($der, 0);
$kids = $certSeq['children'] ?? [];
if (count($kids) < 3) throw new RuntimeException('Invalid certificate structure: expected TBSCertificate, signatureAlgorithm, signatureValue');
[$tbs, $sigAlgNode] = $kids;
$sigAlgOID = $sigAlgNode['children'] ? decodeOID($sigAlgNode['children'][0]['value']) : '';
if (!$tbs['children'] || count($tbs['children']) < 7) throw new RuntimeException('Invalid TBSCertificate structure');
$t = $tbs['children'];
$idx = 0;
$version = 0; // v1 unless the explicit context [0] wrapper is present
if ($t[$idx]['class'] === 'context' && $t[$idx]['tag'] === 0) {
$v = $t[$idx]['children'][0] ?? null;
if ($v !== null && strlen($v['value']) === 1) $version = ord($v['value']);
$idx++;
}
$serial = $t[$idx++]['value'];
$idx++; // the inner signature algorithm
$issuer = parseRDN($t[$idx++]);
$validity = $t[$idx++];
$notBefore = $notAfter = new DateTimeImmutable('@0');
if ($validity['children'] && count($validity['children']) >= 2) {
$notBefore = parseTime($validity['children'][0]);
$notAfter = parseTime($validity['children'][1]);
}
$subject = parseRDN($t[$idx++]);
$spki = parseSPKI($t[$idx++]);
$extensions = ['basicConstraintsCA' => null, 'keyUsage' => null, 'extKeyUsage' => null, 'sanDNS' => [], 'sanIP' => [], 'sanEmail' => []];
for (; $idx < count($t); $idx++) {
$child = $t[$idx];
if ($child['class'] === 'context' && $child['tag'] === 3 && $child['children']) {
$outerSeq = $child['children'][0] ?? null;
if ($outerSeq !== null && $outerSeq['children']) $extensions = parseExtensions($outerSeq['children']);
}
}
if (strlen($serial) > 1 && $serial[0] === "\x00") $serial = substr($serial, 1); // sign pad
return [
'subject' => $subject, 'subjectDN' => formatDN($subject), 'issuer' => $issuer, 'issuerDN' => formatDN($issuer),
'notBefore' => $notBefore, 'notAfter' => $notAfter,
'serialNumber' => hexBytes($serial, ':') === '' ? '' : strtoupper(hexBytes($serial, ':')),
'signatureAlgorithm' => oidName($sigAlgOID), 'keyAlgorithm' => $spki['keyAlgorithm'], 'keySize' => $spki['keySize'],
'basicConstraintsCA' => $extensions['basicConstraintsCA'],
'keyUsage' => $extensions['keyUsage'] ?? [], 'extKeyUsage' => $extensions['extKeyUsage'] ?? [],
'sanDNS' => $extensions['sanDNS'], 'sanIP' => $extensions['sanIP'], 'sanEmail' => $extensions['sanEmail'],
'version' => $version, 'rawDER' => $der,
];
}
function isExpired(array $cert): bool { return $cert['notAfter']->getTimestamp() < time(); }
function daysUntilExpiry(array $cert): int { return (int) ceil(($cert['notAfter']->getTimestamp() - time()) / 86400); }
/** Extract every PEM certificate block and decode each one. */
function decodeCertificateChain(string $pem): array
{
if (trim($pem) === '') throw new RuntimeException('Empty input — paste PEM certificate(s)');
$blocks = pemBlocks($pem);
if (!$blocks) throw new RuntimeException('No PEM certificate block found — expected -----BEGIN CERTIFICATE-----');
return array_map(fn (string $block) => decodeCertificate("-----BEGIN CERTIFICATE-----\n{$block}\n-----END CERTIFICATE-----"), $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 →