Skip to content

Certificate Decoder — Go 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 Go implementation — the same logic the interactive tool runs, in a shareable, citable form.

// Package certdecoder ports src/lib/cert-decoder.ts (dual source: the web lib
// is TypeScript, the CLI lib is Go — kept in lock-step). It is a pure ASN.1 DER
// parser + X.509 certificate decoder with no external dependencies; DER is
// deterministic and parsed sequentially. The table-driven tests in
// cert_decoder_test.go share vectors with src/lib/cert-decoder.test.ts so the
// two implementations are held to the same contract.
package certdecoder

import (
	"encoding/base64"
	"errors"
	"fmt"
	"math"
	"regexp"
	"strconv"
	"strings"
	"time"
	"unicode/utf8"
)

// OIDNames maps well-known object identifiers to human-readable names.
// Mirrors OID_NAMES in src/lib/cert-decoder.ts.
var OIDNames = map[string]string{
	"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",
	"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.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.2.840.113549.1.9.1":          "emailAddress",
	"1.3.6.1.4.1.11129.2.1.17":      "CT Precertificate SCTs",
	"1.3.6.1.5.5.7.1.3":             "CRL Distribution Points",
	"1.3.6.1.4.1.311.21.7":          "Microsoft Certificate Template",
}

// ECCurveNames maps EC named-curve OIDs to their common names.
// Mirrors EC_CURVE_NAMES in src/lib/cert-decoder.ts.
var ECCurveNames = map[string]string{
	"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",
}

// keyUsageBits names the Key Usage bit positions, MSB-first per octet.
// Mirrors KEY_USAGE_BITS in src/lib/cert-decoder.ts.
var keyUsageBits = []string{
	"digitalSignature",
	"nonRepudiation",
	"keyEncipherment",
	"dataEncipherment",
	"keyAgreement",
	"keyCertSign",
	"cRLSign",
	"encipherOnly",
	"decipherOnly",
}

// ── ASN.1 DER types ───────────────────────────────────────────────────────

// TagClass is the class bits of a DER tag byte.
type TagClass int

const (
	ClassUniversal TagClass = iota
	ClassApplication
	ClassContext
	ClassPrivate
)

// asn1Node is one parsed TLV. children stays nil for primitive nodes and for
// constructed nodes with empty content (mirroring the TS optional field).
type asn1Node struct {
	class       TagClass
	constructed bool
	tagNumber   int
	rawValue    []byte // value bytes (decoded content)
	offset      int    // offset into the original buffer
	children    []asn1Node
}

// ── DER parsing ───────────────────────────────────────────────────────────

type derParser struct {
	buf []byte
	pos int
}

func (p *derParser) exhausted() bool { return p.pos >= len(p.buf) }

func (p *derParser) readByte() (byte, error) {
	if p.pos >= len(p.buf) {
		return 0, errors.New("Unexpected end of DER data")
	}
	b := p.buf[p.pos]
	p.pos++
	return b, nil
}

func (p *derParser) readLength() (int, error) {
	first, err := p.readByte()
	if err != nil {
		return 0, err
	}
	if first < 0x80 {
		return int(first), nil
	}
	numBytes := int(first & 0x7f)
	if numBytes == 0 {
		return 0, errors.New("Indefinite length is not supported in DER")
	}
	if numBytes > 4 {
		return 0, fmt.Errorf("Length too large: %d bytes", numBytes)
	}
	length := 0
	for i := 0; i < numBytes; i++ {
		b, err := p.readByte()
		if err != nil {
			return 0, err
		}
		length = (length << 8) | int(b)
	}
	return length, nil
}

// readNode reads the next TLV node, recursively parsing children of
// constructed types. Mirrors DERParser.readNode in the TS lib.
func (p *derParser) readNode() (asn1Node, error) {
	offset := p.pos
	byte0, err := p.readByte()
	if err != nil {
		return asn1Node{}, err
	}

	var class TagClass
	switch byte0 & 0xc0 {
	case 0x00:
		class = ClassUniversal
	case 0x40:
		class = ClassApplication
	case 0x80:
		class = ClassContext
	default:
		class = ClassPrivate
	}

	constructed := byte0&0x20 != 0
	tagNumber := int(byte0 & 0x1f)

	// Long-form tag (tag number >= 31)
	if tagNumber == 0x1f {
		tagNumber = 0
		var b byte
		for {
			b, err = p.readByte()
			if err != nil {
				return asn1Node{}, err
			}
			tagNumber = (tagNumber << 7) | int(b&0x7f)
			if b&0x80 == 0 {
				break
			}
		}
	}

	length, err := p.readLength()
	if err != nil {
		return asn1Node{}, err
	}
	if p.pos+length > len(p.buf) {
		return asn1Node{}, fmt.Errorf("Truncated DER: need %d bytes at offset %d, but only %d remain",
			length, p.pos, len(p.buf)-p.pos)
	}

	rawValue := p.buf[p.pos : p.pos+length]
	p.pos += length

	node := asn1Node{class: class, constructed: constructed, tagNumber: tagNumber, rawValue: rawValue, offset: offset}

	if constructed && len(rawValue) > 0 {
		childParser := &derParser{buf: rawValue}
		for !childParser.exhausted() {
			child, err := childParser.readNode()
			if err != nil {
				return asn1Node{}, err
			}
			node.children = append(node.children, child)
		}
	}

	return node, nil
}

// ── OID decoding ──────────────────────────────────────────────────────────

// decodeOID decodes OID content bytes to dotted-decimal form.
func decodeOID(bytes []byte) (string, error) {
	if len(bytes) == 0 {
		return "", errors.New("Empty OID")
	}
	parts := []string{
		strconv.Itoa(int(bytes[0] / 40)),
		strconv.Itoa(int(bytes[0] % 40)),
	}

	value := 0
	for _, b := range bytes[1:] {
		value = (value << 7) | int(b&0x7f)
		if b&0x80 == 0 {
			parts = append(parts, strconv.Itoa(value))
			value = 0
		}
	}
	return strings.Join(parts, "."), nil
}

func oidName(oid string) string {
	if n, ok := OIDNames[oid]; ok {
		return n
	}
	return oid
}

// ── RDN (Relative Distinguished Name) helpers ─────────────────────────────

// RDNAttribute is one typed attribute of a distinguished name
// (Type is the short name like "CN", "O", …). Mirrors RDNAttribute in the TS lib.
type RDNAttribute struct {
	Type  string
	Value string
}

// parseRDN walks Name ::= SEQUENCE OF SET OF SEQUENCE { type OID, value ANY }.
func parseRDN(node asn1Node) ([]RDNAttribute, error) {
	var attrs []RDNAttribute
	for _, rdnSet := range node.children {
		for _, attrSeq := range rdnSet.children {
			if len(attrSeq.children) < 2 {
				continue
			}
			oid, err := decodeOID(attrSeq.children[0].rawValue)
			if err != nil {
				return nil, err
			}
			attrs = append(attrs, RDNAttribute{Type: oidName(oid), Value: readString(attrSeq.children[1])})
		}
	}
	return attrs, nil
}

// formatDN joins attributes as "TYPE=value, TYPE=value".
func formatDN(attrs []RDNAttribute) string {
	parts := make([]string, len(attrs))
	for i, a := range attrs {
		parts[i] = a.Type + "=" + a.Value
	}
	return strings.Join(parts, ", ")
}

// readString decodes a node's content as text, falling back to hex when the
// bytes are not valid UTF-8. Mirrors readString in the TS lib (tags 12/19/22/
// 30/36 decode as text unconditionally, like TextDecoder's lenient mode).
func readString(node asn1Node) string {
	tag := node.tagNumber
	if tag == 12 || tag == 19 || tag == 22 || tag == 30 || tag == 36 {
		// UTF8String(12), PrintableString(19), IA5String(22),
		// BMPString(30), etc. — invalid bytes become U+FFFD, like TextDecoder.
		return string(node.rawValue)
	}
	if utf8.Valid(node.rawValue) {
		return string(node.rawValue)
	}
	// Last resort: colon-separated hex.
	parts := make([]string, len(node.rawValue))
	for i, b := range node.rawValue {
		parts[i] = fmt.Sprintf("%02x", b)
	}
	return strings.Join(parts, ":")
}

// ── Time helpers ──────────────────────────────────────────────────────────

var (
	utcTimeRe = regexp.MustCompile(`^(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})Z$`)
	genTimeRe = regexp.MustCompile(`^(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})Z$`)
)

// parseTime reads UTCTime (tag 23) and GeneralizedTime (tag 24).
func parseTime(node asn1Node) (time.Time, error) {
	str := readString(node)
	if node.tagNumber == 23 {
		m := utcTimeRe.FindStringSubmatch(str)
		if m == nil {
			return time.Time{}, fmt.Errorf("Invalid UTCTime: %s", str)
		}
		year, _ := strconv.Atoi(m[1])
		if year >= 50 {
			year += 1900
		} else {
			year += 2000
		}
		return timeFromDate(year, m[2], m[3], m[4], m[5], m[6]), nil
	}
	if node.tagNumber == 24 {
		m := genTimeRe.FindStringSubmatch(str)
		if m == nil {
			return time.Time{}, fmt.Errorf("Invalid GeneralizedTime: %s", str)
		}
		year, _ := strconv.Atoi(m[1])
		return timeFromDate(year, m[2], m[3], m[4], m[5], m[6]), nil
	}
	return time.Time{}, fmt.Errorf("Unknown time tag: %d", node.tagNumber)
}

func timeFromDate(year int, mon, day, hour, min, sec string) time.Time {
	mo, _ := strconv.Atoi(mon)
	d, _ := strconv.Atoi(day)
	h, _ := strconv.Atoi(hour)
	mi, _ := strconv.Atoi(min)
	s, _ := strconv.Atoi(sec)
	return time.Date(year, time.Month(mo), d, h, mi, s, 0, time.UTC)
}

// ── Extension parsing ─────────────────────────────────────────────────────

// extensionInfo holds the decoded subset of X.509 extensions the tool shows.
// A nil pointer / nil slice means the extension was absent.
type extensionInfo struct {
	basicConstraintsCA *bool
	keyUsage           []string
	extKeyUsage        []string
	sanDNS             []string
	sanIP              []string
	sanEmail           []string
}

// parseExtensions decodes the extension entries the tool understands.
// Mirrors parseExtensions in the TS lib.
func parseExtensions(nodes []asn1Node) (extensionInfo, error) {
	ext := extensionInfo{
		sanDNS:   []string{},
		sanIP:    []string{},
		sanEmail: []string{},
	}

	for _, extNode := range nodes {
		if len(extNode.children) < 2 {
			continue
		}
		oid, err := decodeOID(extNode.children[0].rawValue)
		if err != nil {
			return ext, err
		}

		// Skip critical boolean if present
		valueIdx := 1
		if len(extNode.children) >= 3 &&
			extNode.children[1].tagNumber == 1 && extNode.children[1].class == ClassUniversal {
			valueIdx = 2
		}

		valueNode := extNode.children[valueIdx]
		// The value is wrapped in an OCTET STRING containing the actual DER
		octetContent := valueNode.rawValue
		if len(octetContent) == 0 {
			continue
		}

		inner := &derParser{buf: octetContent}
		if inner.exhausted() {
			continue
		}
		content, err := inner.readNode()
		if err != nil {
			return ext, err
		}

		switch oid {
		case "2.5.29.19": // Basic Constraints
			ca := false
			if len(content.children) > 0 {
				boolVal := content.children[0]
				if boolVal.tagNumber == 1 && len(boolVal.rawValue) == 1 && boolVal.rawValue[0] == 0xff {
					ca = true
				}
			}
			ext.basicConstraintsCA = &ca
		case "2.5.29.15": // Key Usage — BIT STRING
			ext.keyUsage = parseBitString(content)
		case "2.5.29.37": // Extended Key Usage
			ext.extKeyUsage = []string{}
			for _, child := range content.children {
				oid, err := decodeOID(child.rawValue)
				if err != nil {
					return ext, err
				}
				ext.extKeyUsage = append(ext.extKeyUsage, oidName(oid))
			}
		case "2.5.29.17": // Subject Alternative Name
			for _, child := range content.children {
				if child.class != ClassContext {
					continue
				}
				switch child.tagNumber {
				case 2: // DNS
					ext.sanDNS = append(ext.sanDNS, readString(child))
				case 7: // IP
					ipBytes := child.rawValue
					if len(ipBytes) == 4 {
						ext.sanIP = append(ext.sanIP,
							strconv.Itoa(int(ipBytes[0]))+"."+strconv.Itoa(int(ipBytes[1]))+"."+
								strconv.Itoa(int(ipBytes[2]))+"."+strconv.Itoa(int(ipBytes[3])))
					} else if len(ipBytes) == 16 {
						// IPv6 — standard (lowercase, uncompressed) hex representation
						parts := make([]string, 0, 8)
						for i := 0; i < 16; i += 2 {
							parts = append(parts, strconv.FormatInt(int64(ipBytes[i])<<8|int64(ipBytes[i+1]), 16))
						}
						ext.sanIP = append(ext.sanIP, strings.Join(parts, ":"))
					}
				case 1: // Email
					ext.sanEmail = append(ext.sanEmail, readString(child))
				}
			}
		}
	}

	return ext, nil
}

// parseBitString maps Key Usage BIT STRING bits to their names.
// Mirrors parseBitString in the TS lib, including the unused-bits masking.
func parseBitString(node asn1Node) []string {
	if len(node.rawValue) < 2 {
		return []string{}
	}
	unusedBits := int(node.rawValue[0])
	octets := node.rawValue[1:]
	var flags []string

	for i, name := range keyUsageBits {
		octetIdx := i / 8
		bitIdx := 7 - (i % 8)
		if octetIdx < len(octets) {
			if octets[octetIdx]&(1<<bitIdx) != 0 {
				flags = append(flags, name)
			}
		}
	}

	// Mask out unused bits
	if unusedBits > 0 && len(flags) > 0 {
		totalBits := len(octets)*8 - unusedBits
		for len(flags) > totalBits {
			flags = flags[:len(flags)-1]
		}
	}

	return flags
}

// ── Public types ──────────────────────────────────────────────────────────

// CertificateInfo is the decoded view of one X.509 certificate.
// Mirrors CertificateInfo in src/lib/cert-decoder.ts.
type CertificateInfo struct {
	// Subject contains the parsed subject RDN attributes.
	Subject []RDNAttribute
	// SubjectDN is the formatted subject DN string.
	SubjectDN string
	// Issuer contains the parsed issuer RDN attributes.
	Issuer []RDNAttribute
	// IssuerDN is the formatted issuer DN string.
	IssuerDN string
	// NotBefore is the not-before date.
	NotBefore time.Time
	// NotAfter is the not-after date.
	NotAfter time.Time
	// SerialNumber is the serial number as an uppercase hex string.
	SerialNumber string
	// SignatureAlgorithm is the human-readable signature algorithm name.
	SignatureAlgorithm string
	// KeyAlgorithm is the public key algorithm name.
	KeyAlgorithm string
	// KeySize is the public key size in bits.
	KeySize int
	// BasicConstraintsCA is the CA flag; nil when the extension is absent.
	BasicConstraintsCA *bool
	// KeyUsage contains the Key Usage flag names.
	KeyUsage []string
	// ExtKeyUsage contains the Extended Key Usage purpose names.
	ExtKeyUsage []string
	// SanDNS holds Subject Alternative Name DNS entries.
	SanDNS []string
	// SanIP holds Subject Alternative Name IP entries.
	SanIP []string
	// SanEmail holds Subject Alternative Name email entries.
	SanEmail []string
	// Version is the version number (0=v1, 1=v2, 2=v3).
	Version int
	// RawDER holds the raw DER bytes (for fingerprinting).
	RawDER []byte
}

// ── PEM handling ──────────────────────────────────────────────────────────

var (
	pemRe = regexp.MustCompile(`-----BEGIN\s+CERTIFICATE-----\s*\r?\n([\s\S]*?)\r?\n-----END\s+CERTIFICATE-----`)
	wsRe  = regexp.MustCompile(`\s+`)
)

// extractPEMBlocks returns the base64 body of every CERTIFICATE block.
func extractPEMBlocks(pem string) []string {
	var blocks []string
	for _, m := range pemRe.FindAllStringSubmatch(pem, -1) {
		blocks = append(blocks, m[1])
	}
	return blocks
}

// pemToDER strips whitespace and decodes base64.
func pemToDER(pem string) ([]byte, error) {
	b64 := wsRe.ReplaceAllString(pem, "")
	return base64.StdEncoding.DecodeString(b64)
}

// ── Main decoder ──────────────────────────────────────────────────────────

// DecodeCertificate parses the first PEM CERTIFICATE block in the input and
// returns its decoded fields. It is the Go twin of decodeCertificate() in
// src/lib/cert-decoder.ts and must agree with it on every shared vector.
func DecodeCertificate(pem string) (CertificateInfo, error) {
	if strings.TrimSpace(pem) == "" {
		return CertificateInfo{}, errors.New("Empty input — paste a PEM certificate")
	}

	blocks := extractPEMBlocks(pem)
	if len(blocks) == 0 {
		return CertificateInfo{}, errors.New("No PEM certificate block found — expected -----BEGIN CERTIFICATE-----")
	}

	return decodeBlock(blocks[0])
}

// decodeBlock decodes one base64 PEM body. It is the shared core of
// DecodeCertificate and DecodeCertificateChain.
func decodeBlock(block string) (CertificateInfo, error) {
	der, err := pemToDER(block)
	if err != nil {
		return CertificateInfo{}, err
	}

	// Parse outer SEQUENCE
	parser := &derParser{buf: der}
	certSeq, err := parser.readNode()
	if err != nil {
		return CertificateInfo{}, err
	}
	if len(certSeq.children) < 3 {
		return CertificateInfo{}, errors.New("Invalid certificate structure: expected TBSCertificate, signatureAlgorithm, signatureValue")
	}

	tbs := certSeq.children[0]
	sigAlgNode := certSeq.children[1]
	sigAlgOID := ""
	if sigAlgNode.children != nil {
		sigAlgOID, err = decodeOID(sigAlgNode.children[0].rawValue)
		if err != nil {
			return CertificateInfo{}, err
		}
	}

	// Parse TBSCertificate
	if len(tbs.children) < 7 {
		return CertificateInfo{}, errors.New("Invalid TBSCertificate structure")
	}

	idx := 0

	// Version (explicit context [0])
	version := 0 // default v1
	if tbs.children[idx].class == ClassContext && tbs.children[idx].tagNumber == 0 {
		if len(tbs.children[idx].children) > 0 {
			versionNode := tbs.children[idx].children[0]
			if len(versionNode.rawValue) == 1 {
				version = int(versionNode.rawValue[0])
			}
		}
		idx++
	}

	// Serial Number
	serialNode := tbs.children[idx]
	idx++

	// Signature Algorithm (inside TBS)
	idx++ // skip inner sig algorithm

	// Issuer
	issuer, err := parseRDN(tbs.children[idx])
	if err != nil {
		return CertificateInfo{}, err
	}
	idx++

	// Validity
	validityNode := tbs.children[idx]
	var notBefore, notAfter time.Time
	if len(validityNode.children) >= 2 {
		notBefore, err = parseTime(validityNode.children[0])
		if err != nil {
			return CertificateInfo{}, err
		}
		notAfter, err = parseTime(validityNode.children[1])
		if err != nil {
			return CertificateInfo{}, err
		}
	}
	idx++

	// Subject
	subject, err := parseRDN(tbs.children[idx])
	if err != nil {
		return CertificateInfo{}, err
	}
	idx++

	// SubjectPublicKeyInfo
	spkiNode := tbs.children[idx]
	keyAlgorithm := "unknown"
	keySize := 0

	if len(spkiNode.children) >= 2 {
		algSeq := spkiNode.children[0]
		keyBits := spkiNode.children[1].rawValue

		if len(algSeq.children) >= 1 {
			algOID, err := decodeOID(algSeq.children[0].rawValue)
			if err != nil {
				return CertificateInfo{}, err
			}
			keyAlgorithm = oidName(algOID)

			// Key size estimation
			if algOID == "1.2.840.113549.1.1.1" {
				// RSA: the BIT STRING value starts with an unused-bits byte
				// (0x00), then a DER SEQUENCE of { modulus INTEGER, exponent
				// INTEGER }. The modulus bit length is the key size.
				if len(keyBits) > 1 {
					rsaInner := &derParser{buf: keyBits[1:]} // skip unused-bits byte
					if !rsaInner.exhausted() {
						rsaSeq, err := rsaInner.readNode()
						if err != nil {
							return CertificateInfo{}, err
						}
						if len(rsaSeq.children) > 0 {
							modBytes := rsaSeq.children[0].rawValue
							// First byte may be 0x00 padding for positive sign
							effectiveLen := len(modBytes)
							if len(modBytes) > 0 && modBytes[0] == 0x00 {
								effectiveLen = len(modBytes) - 1
							}
							keySize = effectiveLen * 8
						}
					}
				}
			} else if algOID == "1.2.840.10045.2.1" {
				// ECDSA: look at the curve OID parameter
				if len(algSeq.children) >= 2 {
					curveOID, err := decodeOID(algSeq.children[1].rawValue)
					if err != nil {
						return CertificateInfo{}, err
					}
					if curveName, ok := ECCurveNames[curveOID]; ok {
						keyAlgorithm = keyAlgorithm + " (" + curveName + ")"
					}
				}
				// EC public key: BIT STRING value = 0x00 (unused) +
				// uncompressed point. Size from the point byte count.
				if len(keyBits) > 1 {
					keySize = (len(keyBits) - 1 - 1) * 8 // subtract unused-bits byte + 0x04 prefix
				}
			} else {
				if len(keyBits) > 1 {
					keySize = (len(keyBits) - 1) * 8
				}
			}
		}
	}
	idx++

	// Extensions — look for context [3] after subjectPublicKeyInfo
	extensions := extensionInfo{
		sanDNS:   []string{},
		sanIP:    []string{},
		sanEmail: []string{},
	}

	for ; idx < len(tbs.children); idx++ {
		child := tbs.children[idx]
		if child.class == ClassContext && child.tagNumber == 3 && child.children != nil {
			// context [3] wraps a single outer SEQUENCE of Extension entries
			if len(child.children) > 0 {
				outerSeq := child.children[0]
				if outerSeq.children != nil {
					extensions, err = parseExtensions(outerSeq.children)
					if err != nil {
						return CertificateInfo{}, err
					}
				}
			}
		}
	}

	// Serial number as uppercase hex
	serialHex := ""
	if len(serialNode.rawValue) > 0 {
		serialBytes := serialNode.rawValue
		// Remove leading zero if it's just padding
		if serialBytes[0] == 0x00 && len(serialBytes) > 1 {
			serialBytes = serialBytes[1:]
		}
		parts := make([]string, len(serialBytes))
		for i, b := range serialBytes {
			parts[i] = strings.ToUpper(fmt.Sprintf("%02x", b))
		}
		serialHex = strings.Join(parts, ":")
	}

	keyUsage := []string{}
	if extensions.keyUsage != nil {
		keyUsage = extensions.keyUsage
	}
	extKeyUsage := []string{}
	if extensions.extKeyUsage != nil {
		extKeyUsage = extensions.extKeyUsage
	}

	return CertificateInfo{
		Subject:            subject,
		SubjectDN:          formatDN(subject),
		Issuer:             issuer,
		IssuerDN:           formatDN(issuer),
		NotBefore:          notBefore,
		NotAfter:           notAfter,
		SerialNumber:       serialHex,
		SignatureAlgorithm: oidName(sigAlgOID),
		KeyAlgorithm:       keyAlgorithm,
		KeySize:            keySize,
		BasicConstraintsCA: extensions.basicConstraintsCA,
		KeyUsage:           keyUsage,
		ExtKeyUsage:        extKeyUsage,
		SanDNS:             extensions.sanDNS,
		SanIP:              extensions.sanIP,
		SanEmail:           extensions.sanEmail,
		Version:            version,
		RawDER:             der,
	}, nil
}

// IsExpired reports whether the certificate's notAfter is in the past.
// It is the Go twin of isExpired() in src/lib/cert-decoder.ts.
func IsExpired(cert CertificateInfo) bool {
	return cert.NotAfter.Before(time.Now())
}

// DaysUntilExpiry returns the whole days (rounded up) until notAfter.
// It is the Go twin of daysUntilExpiry() in src/lib/cert-decoder.ts.
func DaysUntilExpiry(cert CertificateInfo) int {
	diffMs := cert.NotAfter.Sub(time.Now())
	return int(math.Ceil(float64(diffMs) / float64(24*time.Hour)))
}

// DecodeCertificateChain extracts all PEM certificate blocks and returns info
// for each. It is the Go twin of decodeCertificateChain() in the TS lib.
func DecodeCertificateChain(pem string) ([]CertificateInfo, error) {
	if strings.TrimSpace(pem) == "" {
		return nil, errors.New("Empty input — paste a PEM certificate(s)")
	}

	blocks := extractPEMBlocks(pem)
	if len(blocks) == 0 {
		return nil, errors.New("No PEM certificate block found — expected -----BEGIN CERTIFICATE-----")
	}

	certs := make([]CertificateInfo, 0, len(blocks))
	for _, block := range blocks {
		cert, err := decodeBlock(block)
		if err != nil {
			return nil, err
		}
		certs = append(certs, cert)
	}
	return certs, nil
}

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 →