Skip to content

micro509/x509

Canonical advanced X.509 domain surface. Owns certificate, CSR, extension, name, and parse APIs behind one stable entrypoint.

CertificateMaterial

Encoded certificate material in common interchange formats.

ts
interface CertificateMaterial {
	readonly der: Uint8Array;
	readonly pem: string;
	readonly base64: string;
}

Properties

  • readonly der: Uint8Array — DER-encoded certificate bytes.
  • readonly pem: string — PEM-encoded certificate.
  • readonly base64: string — Base64 encoding of der without PEM armor.

CreateCertificateInput

Input for createCertificate.

ts
interface CreateCertificateInput {
	readonly issuer: NameInput;
	readonly subject: NameInput;
	readonly publicKey: CryptoKey;
	readonly signerPrivateKey: CryptoKey;
	readonly issuerPublicKey?: CryptoKey;
	readonly validity?: ValidityInput;
	readonly serialNumber?: Uint8Array;
	readonly extensions?: CertificateExtensionsInput;
	readonly signature?: SignatureProfileInput;
}

Properties

  • readonly issuer: NameInput — Issuer distinguished name.

  • readonly subject: NameInput — Subject distinguished name.

  • readonly publicKey: CryptoKey — Subject public key to encode into the certificate.

  • readonly signerPrivateKey: CryptoKey — Private key used to sign the certificate.

  • readonly issuerPublicKey?: CryptoKey — Issuer public key.

    Provide this when extension builders need issuer key material, such as authority key identifier derivation.

  • readonly validity?: ValidityInput — Validity window configuration.

  • readonly serialNumber?: Uint8Array — DER integer bytes for the certificate serial number.

    When omitted, a random positive 16-byte serial number is generated.

  • readonly extensions?: CertificateExtensionsInput — X.509 extensions to encode into the certificate.

  • readonly signature?: SignatureProfileInput — Signature algorithm override.

    When omitted, the library selects a compatible profile from the signing key.

CreateSelfSignedCertificateInput

Input for createSelfSignedCertificate.

ts
interface CreateSelfSignedCertificateInput {
	readonly subject: NameInput;
	readonly algorithm?: KeyAlgorithmInput;
	readonly keyPair?: KeyPairMaterial;
	readonly validity?: ValidityInput;
	readonly serialNumber?: Uint8Array;
	readonly extensions?: CertificateExtensionsInput;
	readonly signature?: SignatureProfileInput;
}

Properties

  • readonly subject: NameInput — Subject distinguished name used as both subject and issuer.

  • readonly algorithm?: KeyAlgorithmInput — Key generation parameters.

    Ignored when keyPair is provided.

  • readonly keyPair?: KeyPairMaterial — Existing key pair to reuse for both subject and issuer.

    When omitted, a new key pair is generated.

  • readonly validity?: ValidityInput — Validity window configuration.

  • readonly serialNumber?: Uint8Array — DER integer bytes for the certificate serial number.

  • readonly extensions?: CertificateExtensionsInput — X.509 extensions to encode into the certificate.

  • readonly signature?: SignatureProfileInput — Signature algorithm override.

SelfSignedCertificateResult

Result returned by createSelfSignedCertificate.

ts
interface SelfSignedCertificateResult {
	readonly certificate: CertificateMaterial;
	readonly keyPair: KeyPairMaterial;
}

Properties

SignatureProfileInput

Controls how the signature algorithm is chosen.

'auto' (default) infers the algorithm from the key. 'rsa-pss' forces RSA-PSS padding and requires an RSA-PSS private key.

ts
type SignatureProfileInput = {
  readonly kind?: auto
} | {
  readonly kind: rsa-pss;
  readonly saltLength?: 32 | 48 | 64
}

ValidityInput

Configures the certificate validity window.

If notAfter is omitted, it is derived from notBefore plus days. If both notAfter and days are omitted, the certificate is valid for 30 days.

ts
interface ValidityInput {
	readonly notBefore?: Date;
	readonly notAfter?: Date;
	readonly days?: number;
}

Properties

  • readonly notBefore?: Date — Start of the validity window.

    Defaults to the current time.

  • readonly notAfter?: Date — End of the validity window.

    Must be later than notBefore.

  • readonly days?: number — Number of days to add to notBefore when notAfter is omitted.

createCertificate

Create an X.509 certificate signed by input.signerPrivateKey.

The certificate encodes input.subject, input.publicKey, and any supplied extensions. When serialNumber is omitted, a random positive serial number is generated. When validity is omitted, the certificate is valid from now for 30 days.

ts
function createCertificate(
	input: CreateCertificateInput,
): Promise<CertificateMaterial>

Parameters

Returns — The encoded certificate material.

Examples

ts
const certificate = await createCertificate({
	issuer: { commonName: 'Example Root CA' },
	subject: { commonName: 'example.com' },
	publicKey: leafKeys.publicKey,
	signerPrivateKey: issuerKeys.privateKey,
	issuerPublicKey: issuerKeys.publicKey,
});

createSelfSignedCertificate

Create a self-signed certificate.

Reuses input.keyPair when provided; otherwise generates a new key pair from input.algorithm. The returned certificate uses input.subject as both issuer and subject.

ts
function createSelfSignedCertificate(
	input: CreateSelfSignedCertificateInput,
): Promise<SelfSignedCertificateResult>

Parameters

Returns — The certificate plus the key pair used to sign it.

Examples

ts
const { certificate, keyPair } = await createSelfSignedCertificate({
	subject: { commonName: 'example.com' },
	algorithm: { kind: 'ecdsa', curve: 'P-256' },
});

CreateCsrInput

Input for createCertificateSigningRequest.

ts
interface CreateCsrInput {
	readonly subject: NameInput;
	readonly publicKey: CryptoKey;
	readonly signerPrivateKey: CryptoKey;
	readonly extensions?: CertificateExtensionsInput;
	readonly signature?: SignatureProfileInput;
}

Properties

  • readonly subject: NameInput — Distinguished name for the CSR subject (e.g. { commonName: 'example.com' }).
  • readonly publicKey: CryptoKey — WebCrypto public key to embed in the CSR's SubjectPublicKeyInfo.
  • readonly signerPrivateKey: CryptoKey — WebCrypto private key used to self-sign the CSR (proves key possession).
  • readonly extensions?: CertificateExtensionsInput — Requested X.509v3 extensions to include in the CSR attributes.
  • readonly signature?: SignatureProfileInput — Override the signature algorithm profile (hash, salt length, etc.).

CsrMaterial

DER, PEM, and base64 encodings of a CSR produced by createCertificateSigningRequest.

ts
interface CsrMaterial {
	readonly der: Uint8Array;
	readonly pem: string;
	readonly base64: string;
}

Properties

  • readonly der: Uint8Array — Raw DER-encoded PKCS#10 CertificationRequest.
  • readonly pem: string — PEM-armored CSR (-----BEGIN CERTIFICATE REQUEST-----).
  • readonly base64: string — Base64-encoded DER (no PEM armor).

createCertificateSigningRequest

Creates a PKCS#10 Certificate Signing Request signed with the given private key.

The CSR embeds the public key's SPKI, the subject name, and any requested extensions as attributes. The signature proves possession of the private key.

ts
function createCertificateSigningRequest(
	input: CreateCsrInput,
): Promise<CsrMaterial>

Parameters

Examples

ts
import { createCertificateSigningRequest } from 'micro509';

const keyPair = await crypto.subtle.generateKey(
  { name: 'ECDSA', namedCurve: 'P-256' },
  true,
  ['sign', 'verify'],
);
const csr = await createCertificateSigningRequest({
  subject: { commonName: 'example.com' },
  publicKey: keyPair.publicKey,
  signerPrivateKey: keyPair.privateKey,
  extensions: { subjectAltNames: [{ type: 'dns', value: 'example.com' }] },
});
console.log(csr.pem);

AuthorityInfoAccessMethod

AIA access method — either a well-known string or a custom OID.

ts
type AuthorityInfoAccessMethod = KnownAuthorityInfoAccessMethod | CustomAuthorityInfoAccessMethod

AuthorityInformationAccess

A single entry in the Authority Information Access extension (RFC 5280 §4.2.2.1).

ts
interface AuthorityInformationAccess {
	readonly method: ocsp | caIssuers | {
  readonly type: oid;
  readonly value: string
};
	readonly uri: string;
}

Properties

  • readonly method: ocsp | caIssuers | { readonly type: oid; readonly value: string } — Access method ('ocsp', 'caIssuers', or custom OID).
  • readonly uri: string — URI where the resource can be fetched.

BasicConstraints

RFC 5280 §4.2.1.9 Basic Constraints.

A certificate with ca: true may issue other certificates; pathLength limits how many additional CAs may appear below it in the chain.

ts
type BasicConstraints = {
  readonly ca: false;
  readonly pathLength?: undefined
} | {
  readonly ca: true;
  readonly pathLength?: number
}

CertificateExtensionsInput

Input for createCertificate, createSelfSignedCertificate, and createCertificateSigningRequest.

Every field is optional. Omitted extensions are not encoded. Built-in extensions (SKI, AKI, basicConstraints defaults) are handled automatically by the builder.

ts
interface CertificateExtensionsInput {
	readonly subjectAltNames?: readonly SubjectAltName[];
	readonly keyUsage?: readonly KeyUsage[];
	readonly basicConstraints?: BasicConstraints;
	readonly extendedKeyUsage?: readonly ExtendedKeyUsage[];
	readonly nameConstraints?: NameConstraints;
	readonly certificatePolicies?: CertificatePolicies;
	readonly policyMappings?: PolicyMappings;
	readonly policyConstraints?: PolicyConstraints;
	readonly inhibitAnyPolicy?: InhibitAnyPolicy;
	readonly authorityInfoAccess?: readonly AuthorityInformationAccess[];
	readonly crlDistributionPoints?: readonly DistributionPoint[];
	readonly customExtensions?: readonly CustomExtension[];
}

Properties

  • readonly subjectAltNames?: readonly SubjectAltName[] — Subject Alternative Names (dns, ip, email, uri, srv, directoryName).
  • readonly keyUsage?: readonly KeyUsage[] — Key Usage flags (digitalSignature, keyCertSign, etc.).
  • readonly basicConstraints?: BasicConstraints — Basic Constraints (CA flag + optional pathLength). Defaults to { ca: false } for certs.
  • readonly extendedKeyUsage?: readonly ExtendedKeyUsage[] — Extended Key Usage purposes (serverAuth, clientAuth, etc.).
  • readonly nameConstraints?: NameConstraints — Name Constraints — permitted and/or excluded subtrees.
  • readonly certificatePolicies?: CertificatePolicies — Certificate Policies with optional qualifiers.
  • readonly policyMappings?: PolicyMappings — Policy Mappings between issuer and subject policy domains.
  • readonly policyConstraints?: PolicyConstraints — Policy Constraints (requireExplicitPolicy / inhibitPolicyMapping thresholds).
  • readonly inhibitAnyPolicy?: InhibitAnyPolicy — Inhibit anyPolicy skip-certs threshold.
  • readonly authorityInfoAccess?: readonly AuthorityInformationAccess[] — Authority Information Access — OCSP responder and CA issuer URIs.
  • readonly crlDistributionPoints?: readonly DistributionPoint[] — CRL Distribution Points — where to check revocation status.
  • readonly customExtensions?: readonly CustomExtension[] — Arbitrary extensions not covered by the built-in fields.

CertificatePolicies

RFC 5280 §4.2.1.4 — array of policy OIDs with optional qualifiers.

ts
type CertificatePolicies = readonly {
  readonly policyIdentifier: string;
  readonly policyQualifiers?: readonly ({
  readonly type: cps;
  readonly uri: string
} | {
  readonly type: userNotice;
  readonly noticeRef?: {
  readonly organization: string;
  readonly noticeNumbers: readonly number[]
};
  readonly explicitText?: string
} | {
  readonly type: oid;
  readonly oid: string;
  readonly qualifierDer: Uint8Array
})[]
}[]

CpsPolicyQualifierInfo

CPS (Certification Practice Statement) URI policy qualifier.

ts
interface CpsPolicyQualifierInfo {
	readonly type: cps;
	readonly uri: string;
}

Properties

  • readonly type: cps — Discriminant for the 'cps' qualifier variant.
  • readonly uri: string — URL of the Certification Practice Statement document.

CustomAuthorityInfoAccessMethod

AIA access method identified by a custom OID not in the well-known set.

ts
interface CustomAuthorityInfoAccessMethod {
	readonly type: oid;
	readonly value: string;
}

Properties

  • readonly type: oid — Discriminant for the custom-OID access method variant.
  • readonly value: string — Dotted-decimal OID of the access method.

CustomExtendedKeyUsage

Extended Key Usage purpose identified by a custom OID.

ts
interface CustomExtendedKeyUsage {
	readonly type: oid;
	readonly value: string;
}

Properties

  • readonly type: oid — Discriminant for the custom-OID EKU variant.
  • readonly value: string — Dotted-decimal OID of the usage purpose.

CustomExtension

An extension not covered by the typed fields in CertificateExtensionsInput.

ts
interface CustomExtension {
	readonly oid: string;
	readonly value: Uint8Array;
	readonly critical?: boolean;
}

Properties

  • readonly oid: string — Dotted-decimal OID of the extension.
  • readonly value: Uint8Array — Pre-encoded DER content for the extnValue OCTET STRING.
  • readonly critical?: boolean — Whether the extension is critical. Default false.

CustomPolicyQualifierInfo

Opaque policy qualifier identified by a custom OID, carried as raw DER.

ts
interface CustomPolicyQualifierInfo {
	readonly type: oid;
	readonly oid: string;
	readonly qualifierDer: Uint8Array;
}

Properties

  • readonly type: oid — Discriminant for the custom-OID qualifier variant.
  • readonly oid: string — Dotted-decimal OID of the qualifier.
  • readonly qualifierDer: Uint8Array — DER-encoded qualifier payload.

DistributionPoint

Input for a single CRL Distribution Point (RFC 5280 §4.2.1.13).

At least one of distributionPoint or crlIssuer must be provided. The union enforces this constraint at the type level.

ts
type DistributionPoint = {
  readonly distributionPoint: DistributionPointName;
  readonly reasons?: readonly DistributionPointReason[];
  readonly crlIssuer?: readonly GeneralName[]
} | {
  readonly distributionPoint?: DistributionPointName;
  readonly reasons?: readonly DistributionPointReason[];
  readonly crlIssuer: readonly GeneralName[]
}

DistributionPointName

Name component of a CRL Distribution Point (RFC 5280 §4.2.1.13).

Supply exactly one of fullName or relativeName.

ts
interface DistributionPointName {
	readonly fullName?: readonly GeneralName[];
	readonly relativeName?: RelativeDistinguishedNameInput;
}

Properties

DistributionPointReason

Revocation reason flags for CRL Distribution Points and Issuing Distribution Points (RFC 5280 §4.2.1.13, §5.2.5).

ts
type DistributionPointReason = keyCompromise | cACompromise | affiliationChanged | superseded | cessationOfOperation | certificateHold | privilegeWithdrawn | aACompromise

ExtendedKeyUsage

Extended Key Usage — either a well-known purpose string or a custom OID.

ts
type ExtendedKeyUsage = serverAuth | clientAuth | codeSigning | emailProtection | timeStamping | ocspSigning | {
  readonly type: oid;
  readonly value: string
}

GeneralName

Alias for SubjectAltName — used where RFC 5280 says "GeneralName".

ts
type GeneralName = SubjectAltName

GeneralSubtree

A single subtree entry in a Name Constraints permitted/excluded list.

ts
interface GeneralSubtree<TForm extends ParsedNameConstraintForm> {
	readonly base: TForm;
}

Properties

  • readonly base: TForm — The name form that defines this constraint boundary.

InhibitAnyPolicy

RFC 5280 §4.2.1.14 Inhibit anyPolicy.

After skipCerts additional certificates in the path, the special anyPolicy OID is no longer considered a match.

ts
interface InhibitAnyPolicy {
	readonly skipCerts: number;
}

Properties

  • readonly skipCerts: number — Number of additional certificates before anyPolicy stops being valid.

KeyUsage

RFC 5280 §4.2.1.3 Key Usage bit flag.

Each value corresponds to one bit in the KeyUsage BIT STRING.

ts
type KeyUsage = digitalSignature | nonRepudiation | keyEncipherment | dataEncipherment | keyAgreement | keyCertSign | cRLSign | encipherOnly | decipherOnly

See also

KnownAuthorityInfoAccessMethod

Well-known AIA access methods: OCSP responder or CA issuer certificate.

ts
type KnownAuthorityInfoAccessMethod = ocsp | caIssuers

KnownExtendedKeyUsage

Well-known Extended Key Usage purpose strings (RFC 5280 §4.2.1.12).

ts
type KnownExtendedKeyUsage = serverAuth | clientAuth | codeSigning | emailProtection | timeStamping | ocspSigning

NameConstraintForm

A name form used as a constraint base in namEConstraints. Distinct from SubjectAltName because IP constraints carry address + mask bytes (8 for IPv4, 32 for IPv6) rather than bare addresses.

ts
type NameConstraintForm = {
  readonly type: dns;
  readonly value: string
} | {
  readonly type: email;
  readonly value: string
} | {
  readonly type: uri;
  readonly value: string
} | {
  readonly type: ip;
  readonly addressBytes: Uint8Array;
  readonly maskBytes: Uint8Array
} | {
  readonly type: directoryName;
  readonly derHex: string
}

NameConstraints

RFC 5280 §4.2.1.10 Name Constraints.

A CA certificate may restrict the namespace of all subject names in subsequent certificates in the path.

ts
interface NameConstraints<TForm extends ParsedNameConstraintForm> {
	readonly permittedSubtrees?: readonly GeneralSubtree<TForm>[];
	readonly excludedSubtrees?: readonly GeneralSubtree<TForm>[];
}

Properties

  • readonly permittedSubtrees?: readonly GeneralSubtree<TForm>[] — Names that MUST fall within these subtrees to be valid.
  • readonly excludedSubtrees?: readonly GeneralSubtree<TForm>[] — Names that MUST NOT fall within these subtrees. Takes precedence over permitted.

ParsedNameConstraintForm

Union of supported and unsupported name constraint forms as produced by parsing.

ts
type ParsedNameConstraintForm = {
  readonly type: dns;
  readonly value: string
} | {
  readonly type: email;
  readonly value: string
} | {
  readonly type: uri;
  readonly value: string
} | {
  readonly type: ip;
  readonly addressBytes: Uint8Array;
  readonly maskBytes: Uint8Array
} | {
  readonly type: directoryName;
  readonly derHex: string
} | {
  readonly type: otherName;
  readonly value: Uint8Array
} | {
  readonly type: x400Address;
  readonly value: Uint8Array
} | {
  readonly type: ediPartyName;
  readonly value: Uint8Array
} | {
  readonly type: registeredID;
  readonly value: string
}

PolicyConstraints

RFC 5280 §4.2.1.11 Policy Constraints.

At least one field must be present. Values are certificate-count thresholds measured from the current certificate toward the end entity.

ts
interface PolicyConstraints {
	readonly requireExplicitPolicy?: number;
	readonly inhibitPolicyMapping?: number;
}

Properties

  • readonly requireExplicitPolicy?: number — After this many certificates, an acceptable policy must be in the path.
  • readonly inhibitPolicyMapping?: number — After this many certificates, policy mapping is no longer allowed.

PolicyInformation

A single certificate policy: an OID plus optional qualifiers.

ts
interface PolicyInformation {
	readonly policyIdentifier: string;
	readonly policyQualifiers?: readonly PolicyQualifierInfo[];
}

Properties

  • readonly policyIdentifier: string — Dotted-decimal OID of the policy (e.g. "2.23.140.1.2.1" for DV).
  • readonly policyQualifiers?: readonly PolicyQualifierInfo[] — Optional CPS URIs or user notices attached to this policy.

PolicyMapping

Maps a policy OID in the issuer's domain to an equivalent OID in the subject's domain.

ts
interface PolicyMapping {
	readonly issuerDomainPolicy: string;
	readonly subjectDomainPolicy: string;
}

Properties

  • readonly issuerDomainPolicy: string — Policy OID as defined by the issuing CA. Must not be anyPolicy.
  • readonly subjectDomainPolicy: string — Equivalent policy OID in the subject CA's domain. Must not be anyPolicy.

PolicyMappings

RFC 5280 §4.2.1.5 — array of issuer-to-subject policy OID pairs.

ts
type PolicyMappings = readonly {
  readonly issuerDomainPolicy: string;
  readonly subjectDomainPolicy: string
}[]

PolicyNoticeReference

Reference to a numbered notice within an organization's practice statement.

ts
interface PolicyNoticeReference {
	readonly organization: string;
	readonly noticeNumbers: readonly number[];
}

Properties

  • readonly organization: string — Organization name that published the notice.
  • readonly noticeNumbers: readonly number``[] — One-based notice numbers within that organization's documentation.

PolicyQualifierInfo

Discriminated union of all supported policy qualifier types.

ts
type PolicyQualifierInfo = CpsPolicyQualifierInfo | UserNoticePolicyQualifierInfo | CustomPolicyQualifierInfo

SubjectAltName

RFC 5280 §4.2.1.6 Subject Alternative Name / GeneralName.

Discriminated union keyed on type.

The 'unknown' variant preserves unrecognized GeneralName tags for round-trip fidelity.

ts
type SubjectAltName = {
  readonly type: dns;
  readonly value: string
} | {
  readonly type: ip;
  readonly value: string
} | {
  readonly type: email;
  readonly value: string
} | {
  readonly type: uri;
  readonly value: string
} | {
  readonly type: srv;
  readonly value: string
} | {
  readonly type: directoryName;
  readonly derHex: string
} | {
  readonly type: unknown;
  readonly tag: number;
  readonly value: Uint8Array
}

UnsupportedNameConstraintForm

Name constraint forms parsed from DER but not supported for encoding or validation. Preserved for diagnostic round-tripping.

ts
type UnsupportedNameConstraintForm = {
  readonly type: otherName;
  readonly value: Uint8Array
} | {
  readonly type: x400Address;
  readonly value: Uint8Array
} | {
  readonly type: ediPartyName;
  readonly value: Uint8Array
} | {
  readonly type: registeredID;
  readonly value: string
}

UserNoticePolicyQualifierInfo

UserNotice policy qualifier — human-readable notice text and/or a notice reference.

ts
interface UserNoticePolicyQualifierInfo {
	readonly type: userNotice;
	readonly noticeRef?: PolicyNoticeReference;
	readonly explicitText?: string;
}

Properties

  • readonly type: userNotice — Discriminant for the 'userNotice' qualifier variant.
  • readonly noticeRef?: PolicyNoticeReference — Pointer to a numbered notice in an organization's practice statement.
  • readonly explicitText?: string — Free-form text to display to relying parties.

buildCertificateExtensions

Build the v3 extensions block for a certificate.

Automatically adds SKI, AKI (when issuer key is available), and basicConstraints (defaults to { ca: false }). Additional extensions come from the caller's CertificateExtensionsInput.

ts
function buildCertificateExtensions(
	subjectPublicKeyInfo: Uint8Array,
	issuerPublicKeyInfo: Uint8Array | undefined,
	input: CertificateExtensionsInput | undefined,
	_: unknown,
): Uint8Array[]

Parameters

  • subjectPublicKeyInfo: Uint8Array — DER-encoded SPKI of the subject.
  • issuerPublicKeyInfo: Uint8Array | undefined — DER-encoded SPKI of the issuer, or undefined for self-signed.
  • input: CertificateExtensionsInput | undefined — Optional extension configuration.
  • _: unknown

Returns — Array of DER-encoded Extension SEQUENCEs.

buildRequestedExtensions

Build the extensions for a CSR's extensionRequest attribute.

Unlike buildCertificateExtensions, SKI/AKI are not auto-generated.

ts
function buildRequestedExtensions(
	input: CertificateExtensionsInput | undefined,
): Uint8Array[]

Parameters

Returns — Array of DER-encoded Extension SEQUENCEs.

encodeAuthorityInfoAccess

DER-encode an Authority Information Access SEQUENCE.

ts
function encodeAuthorityInfoAccess(
	entries: readonly AuthorityInformationAccess[],
): Uint8Array

Parameters

encodeBasicConstraints

DER-encode a BasicConstraints value.

ts
function encodeBasicConstraints(
	input: BasicConstraints,
): Uint8Array

Parameters

Returns — DER SEQUENCE suitable for wrapping in an Extension OCTET STRING.

encodeCertificatePolicies

DER-encode a Certificate Policies extension value.

ts
function encodeCertificatePolicies(
	policies: CertificatePolicies,
): Uint8Array

Parameters

encodeCrlDistributionPoints

DER-encode a CRL Distribution Points SEQUENCE.

ts
function encodeCrlDistributionPoints(
	points: readonly DistributionPoint[],
): Uint8Array

Parameters

encodeExtendedKeyUsage

DER-encode an Extended Key Usage SEQUENCE OF OIDs.

ts
function encodeExtendedKeyUsage(
	usages: readonly ExtendedKeyUsage[],
): Uint8Array

Parameters

encodeExtension

Encode a single X.509 Extension SEQUENCE (OID + optional critical BOOLEAN + OCTET STRING).

ts
function encodeExtension(
	oid: string,
	extnValue: Uint8Array,
	_: unknown,
): Uint8Array

Parameters

  • oid: string — Dotted-decimal extension OID.
  • extnValue: Uint8Array — DER-encoded extension payload.
  • _: unknown

encodeInhibitAnyPolicy

DER-encode an Inhibit anyPolicy extension value (single INTEGER).

ts
function encodeInhibitAnyPolicy(
	input: InhibitAnyPolicy,
): Uint8Array

Parameters

encodeKeyUsage

DER-encode a Key Usage BIT STRING from an array of KeyUsage flags.

ts
function encodeKeyUsage(
	usages: readonly KeyUsage[],
): Uint8Array

Parameters

  • usages: readonly KeyUsage[] — Flags to set in the bit string.

encodeNameConstraints

DER-encode a Name Constraints extension value.

ts
function encodeNameConstraints(
	constraints: NameConstraints,
): Uint8Array

Parameters

encodePolicyConstraints

DER-encode a Policy Constraints extension value.

ts
function encodePolicyConstraints(
	constraints: PolicyConstraints,
): Uint8Array

Parameters

  • constraints: PolicyConstraints — At least one of requireExplicitPolicy or inhibitPolicyMapping must be set.

encodePolicyMappings

DER-encode a Policy Mappings extension value.

ts
function encodePolicyMappings(
	mappings: PolicyMappings,
): Uint8Array

Parameters

  • mappings: PolicyMappings — Non-empty array of issuer-to-subject policy pairs. Neither OID may be anyPolicy.

encodeSubjectAltName

DER-encode a single SubjectAltName GeneralName element.

ts
function encodeSubjectAltName(
	value: SubjectAltName,
): Uint8Array

Parameters

getAuthorityInfoAccessMethodOid

Resolve an AuthorityInfoAccessMethod to its dotted-decimal OID.

ts
function getAuthorityInfoAccessMethodOid(
	method: AuthorityInfoAccessMethod,
): string

Parameters

getExtendedKeyUsageOid

Resolve an ExtendedKeyUsage to its dotted-decimal OID.

ts
function getExtendedKeyUsageOid(
	usage: ExtendedKeyUsage,
): string

Parameters

parseAuthorityInfoAccessMethodOid

Map a dotted-decimal OID to an AuthorityInfoAccessMethod value.

Returns 'ocsp' or 'caIssuers' for recognized OIDs, or { type: 'oid', value } otherwise.

ts
function parseAuthorityInfoAccessMethodOid(
	oid: string,
): AuthorityInfoAccessMethod

Parameters

  • oid: string

parseExtendedKeyUsageOid

Map a dotted-decimal OID to an ExtendedKeyUsage value.

Returns a well-known string for recognized OIDs, or { type: 'oid', value } otherwise.

ts
function parseExtendedKeyUsageOid(
	oid: string,
): ExtendedKeyUsage

Parameters

  • oid: string

CertificateFingerprint

The three rendered forms of a certificate fingerprint.

ts
interface CertificateFingerprint {
	readonly bytes: Uint8Array;
	readonly hex: string;
	readonly colonHex: string;
}

Properties

  • readonly bytes: Uint8Array — Raw digest bytes.
  • readonly hex: string — Lowercase hex, no separators (e.g. "a1b2c3…").
  • readonly colonHex: string — Uppercase hex, colon-separated (e.g. "A1:B2:C3:…", openssl x509 -fingerprint style).

CertificateFingerprintAlgorithm

Digest algorithms supported by certificateFingerprint.

SHA-1 is intentionally included: legacy ecosystems (PGP-adjacent tooling, older certificate pinning) still identify certificates by their SHA-1 fingerprint. Prefer SHA-256 for anything new.

ts
type CertificateFingerprintAlgorithm = SHA-1 | SHA-256 | SHA-384 | SHA-512

CertificateFingerprintSource

A PEM string, raw DER bytes, or an already-parsed certificate.

Mirrors the source union accepted by the verification, revocation, and PKCS APIs so a fingerprint can be taken from whatever a caller already holds.

ts
type CertificateFingerprintSource = string | Uint8Array | ParsedCertificate

certificateFingerprint

Compute a certificate fingerprint — a hash over the DER encoding.

The certificate is parsed (validating the input and, for PEM, decoding it to DER) before hashing, so the digest is always taken over the canonical DER of a well-formed certificate. Malformed input throws, matching the other DER/PEM boundaries in the library.

ts
function certificateFingerprint(
	certificate: CertificateFingerprintSource,
	_: unknown,
): Promise<CertificateFingerprint>

Parameters

Examples

ts
const fingerprint = await certificateFingerprint(pemString);
console.log(fingerprint.colonHex); // "AB:CD:…" — matches `openssl x509 -fingerprint -sha256`
ts
// Reuse an already-parsed certificate and request SHA-1.
const parsed = parseCertificatePemOrThrow(pemString);
const legacy = await certificateFingerprint(parsed, 'SHA-1');
console.log(legacy.hex);

NameAttribute

Single name attribute within a distinguished name.

RFC 5280 / X.501 call this structure an AttributeTypeAndValue.

ts
interface NameAttribute {
	readonly type: NameFieldKey;
	readonly value: string;
}

Properties

  • readonly type: NameFieldKey — Which attribute type this pair represents.
  • readonly value: string — The string value for this attribute (encoding chosen per field definition).

See also

NameFieldKey

Union of recognized X.501 attribute type shorthand names.

Each key maps to an OID + ASN.1 string encoding in NAME_FIELD_DEFINITIONS.

ts
type NameFieldKey = commonName | surname | serialNumber | country | locality | state | street | organization | organizationalUnit | title | givenName | emailAddress

NameInput

Input for encodeName.

Accepts either a NameObject convenience shape or an ordered array of NameAttribute pairs.
Both forms encode one attribute per RDN.

ts
type NameInput = NameObject | readonly NameAttribute[]

NameObject

Convenience object form of an X.501 distinguished name.

Populated fields are emitted in the order defined by NAME_OBJECT_ORDER.
Each populated field becomes its own single-attribute RDN.

For caller-controlled ordering, pass a NameAttribute array to encodeName.
For multi-valued RDNs, use encodeRelativeDistinguishedName.

ts
interface NameObject {
	readonly commonName?: string;
	readonly surname?: string;
	readonly serialNumber?: string;
	readonly country?: string;
	readonly locality?: string;
	readonly state?: string;
	readonly street?: string;
	readonly organization?: string;
	readonly organizationalUnit?: string;
	readonly title?: string;
	readonly givenName?: string;
	readonly emailAddress?: string;
}

Properties

  • readonly commonName?: string — Subject or issuer common name (CN).
  • readonly surname?: string — Subject surname (SN).
  • readonly serialNumber?: string — Device or entity serial number — not the certificate serial.
  • readonly country?: string — ISO 3166 two-letter country code (C). Must be exactly 2 characters.
  • readonly locality?: string — City or locality (L).
  • readonly state?: string — State or province (ST).
  • readonly street?: string — Street address.
  • readonly organization?: string — Organization name (O).
  • readonly organizationalUnit?: string — Organizational unit (OU). Deprecated in modern CA practice.
  • readonly title?: string — Job title or functional designation.
  • readonly givenName?: string — First / given name (GN).
  • readonly emailAddress?: string — RFC 822 email address. Encoded as IA5String, not UTF-8.

RelativeDistinguishedNameInput

Input for encodeRelativeDistinguishedName.

Each entry becomes one name attribute inside the RDN's SET OF.
Use this shape for multi-valued RDNs.

ts
type RelativeDistinguishedNameInput = readonly NameAttribute[]

See also

encodeName

DER-encodes an X.509 Name.

Returns a DER SEQUENCE of RelativeDistinguishedNames (RDNs).
Each RDN emitted by this helper contains exactly one name attribute.

ts
function encodeName(
	input: NameInput,
): Uint8Array

Parameters

  • input: NameInput — Name fields in convenience-object form or caller-ordered attribute form.

Returns — DER-encoded X.509 Name bytes.

Throws

  • Error — If the input produces no attributes, contains an unsupported field key, or uses an invalid country code.

See also

  • RFC 5280 Appendix A.1

    NameObject input emits populated fields in the canonical order from NAME_OBJECT_ORDER.
    NameAttribute array input preserves caller-supplied ordering, but each entry still becomes its own single-attribute RDN.

    Attribute OIDs and ASN.1 string encodings come from NAME_FIELD_DEFINITIONS.
    Empty strings and undefined fields are ignored when the input is a NameObject.

Examples

ts
const der = encodeName({ country: 'US', commonName: 'example.com' });

// emits two single-attribute RDNs: C=US, then CN=example.com
ts
const der = encodeName([
	{ type: 'country', value: 'US' },
	{ type: 'commonName', value: 'example.com' },
]);

// preserves caller order: C first, then CN

encodeRelativeDistinguishedName

DER-encodes a single RelativeDistinguishedName (RDN).

Returns a DER SET OF name attributes for one X.509 name segment.
Use this when you need a multi-valued RDN.

ts
function encodeRelativeDistinguishedName(
	attributes: RelativeDistinguishedNameInput,
): Uint8Array

Parameters

Returns — DER-encoded RelativeDistinguishedName bytes.

Throws

  • Error — If the attribute list is empty, contains an unsupported field key, or uses an invalid country code.

See also

Examples

ts
const rdn = encodeRelativeDistinguishedName([
	{ type: 'commonName', value: 'example.com' },
	{ type: 'serialNumber', value: 'device-7' },
]);

// emits one RDN with both attributes in the same SET

DecodedExtensionMap

Inferred result type when decoding extensions via an ExtensionDecoderMap.

ts
type DecodedExtensionMap<TMap extends ExtensionDecoderMap> = undefined

DecodedExtensionValue

A successfully decoded extension value paired with its OID and criticality.

ts
interface DecodedExtensionValue<TValue> {
	readonly oid: string;
	readonly critical: boolean;
	readonly value: TValue;
}

Properties

  • readonly oid: string — Dotted-decimal OID of the decoded extension.
  • readonly critical: boolean — Whether the extension was marked critical in the certificate.
  • readonly value: TValue — Typed value produced by the ExtensionDecoder.

ExtensionDecoder

User-supplied decoder for a single extension OID.

Register with ParseOptions.decoders or ParseOptions.decoderMap to decode custom extensions during parsing.

ts
interface ExtensionDecoder<TValue> {
	readonly oid: string;
	decode(extension: ParsedExtension): TValue;
}

Properties

  • readonly oid: string — OID this decoder handles.

ExtensionDecoderMap

String-keyed map of ExtensionDecoders, used with ParseOptions.decoderMap.

ts
type ExtensionDecoderMap = Record<string, ExtensionDecoder<unknown>>

MatchCertificatePrivateKeyErrorCode

Machine-readable failure reason for matchCertificatePrivateKey.

ts
type MatchCertificatePrivateKeyErrorCode = malformed_certificate | unsupported_private_key | key_type_mismatch | key_mismatch

MatchCertificatePrivateKeyFailure

Structured failure payload for matchCertificatePrivateKey.

ts
interface MatchCertificatePrivateKeyFailure extends Micro509Error<MatchCertificatePrivateKeyErrorCode> {
	readonly ok: false;
}

Properties

  • readonly ok: false — Always false for failures.

MatchCertificatePrivateKeyFailureResult

Failure branch of MatchCertificatePrivateKeyResult with structured error details.

ts
type MatchCertificatePrivateKeyFailureResult = ErrorResult<MatchCertificatePrivateKeyErrorCode, Record<never, never>, MatchCertificatePrivateKeyFailure>

MatchCertificatePrivateKeyResult

Result of matchCertificatePrivateKey.

ts
type MatchCertificatePrivateKeyResult = MatchCertificatePrivateKeySuccess | MatchCertificatePrivateKeyFailureResult

MatchCertificatePrivateKeySuccess

A successful match: the private key's public half is the certificate's subject public key.

ts
interface MatchCertificatePrivateKeySuccess {
	readonly ok: true;
	readonly value: undefined;
}

Properties

  • readonly ok: true — Always true for success.
  • readonly value: undefined — No payload on success — the match itself is the signal.

ParseCertificateErrorCode

Machine-readable failure reason for parseCertificateDer / parseCertificatePem.

ts
type ParseCertificateErrorCode = malformed

ParseCertificateFailure

Structured failure payload for certificate parsing.

ts
interface ParseCertificateFailure extends Micro509Error<ParseCertificateErrorCode> {
	readonly ok: false;
}

Properties

  • readonly ok: false — Always false for failures.

ParseCertificateResult

Success-or-failure result from parseCertificateDer / parseCertificatePem.

ts
type ParseCertificateResult<TMap extends ExtensionDecoderMap> = {
  readonly ok: true;
  readonly value: ParsedCertificate<TMap>
} | ErrorResult<ParseCertificateErrorCode, Record<never, never>, ParseCertificateFailure>

ParseCertificateSigningRequestErrorCode

Machine-readable failure reason for the CSR parsers.

ts
type ParseCertificateSigningRequestErrorCode = malformed

ParseCertificateSigningRequestFailure

Structured failure payload for CSR parsing.

ts
interface ParseCertificateSigningRequestFailure extends Micro509Error<ParseCertificateSigningRequestErrorCode> {
	readonly ok: false;
}

Properties

  • readonly ok: false — Always false for failures.

ParseCertificateSigningRequestResult

Success-or-failure result from parseCertificateSigningRequestDer / parseCertificateSigningRequestPem.

ts
type ParseCertificateSigningRequestResult<TMap extends ExtensionDecoderMap> = {
  readonly ok: true;
  readonly value: ParsedCertificateSigningRequest<TMap>
} | ErrorResult<ParseCertificateSigningRequestErrorCode, Record<never, never>, ParseCertificateSigningRequestFailure>

ParsedBitFlags

A decoded BIT STRING flag set.

flags contains the recognized flag values with any non-zero padding bits masked out. nonZeroPadding is true when the original BIT STRING encoding had non-zero bits in positions that DER (X.690 §11.2.2) requires to be zero. Verification layers can use this signal to reject non-conformant encodings.

ts
interface ParsedBitFlags<T extends string> {
	readonly flags: readonly T[];
	readonly nonZeroPadding: boolean;
}

Properties

  • readonly flags: readonly T``[] — Decoded flag values, padding bits masked.
  • readonly nonZeroPadding: booleantrue when the original encoding had non-zero padding bits (DER violation).

ParsedCertificate

A fully decoded X.509 certificate.

Built-in extensions (basicConstraints, keyUsage, etc.) are decoded into typed fields automatically.
Supply ParseOptions to also decode custom extensions.

ts
interface ParsedCertificate<TMap extends ExtensionDecoderMap> {
	readonly der: Uint8Array;
	readonly version: number;
	readonly serialNumberHex: string;
	readonly tbsCertificateDer: Uint8Array;
	readonly subjectPublicKeyInfoDer: Uint8Array;
	readonly signatureValue: Uint8Array;
	readonly issuer: ParsedName;
	readonly subject: ParsedName;
	readonly notBefore: Date;
	readonly notAfter: Date;
	readonly signatureAlgorithmOid: string;
	readonly signatureAlgorithmName: string;
	readonly signatureAlgorithmParametersDer?: Uint8Array;
	readonly publicKeyAlgorithmOid: string;
	readonly publicKeyAlgorithmName: string;
	readonly publicKeyAlgorithmParametersDer?: Uint8Array;
	readonly publicKeyParametersOid?: string;
	readonly extensions: readonly ParsedExtension[];
	readonly basicConstraints?: BasicConstraints;
	readonly keyUsage?: ParsedBitFlags<KeyUsage>;
	readonly extendedKeyUsage?: readonly ExtendedKeyUsage[];
	readonly subjectAltNames?: readonly SubjectAltName[];
	readonly nameConstraints?: NameConstraints<ParsedNameConstraintForm>;
	readonly certificatePolicies?: CertificatePolicies;
	readonly policyMappings?: PolicyMappings;
	readonly policyConstraints?: PolicyConstraints;
	readonly inhibitAnyPolicy?: InhibitAnyPolicy;
	readonly authorityInfoAccess?: readonly AuthorityInformationAccess[];
	readonly crlDistributionPoints?: readonly ParsedDistributionPoint[];
	readonly decodedExtensions?: readonly DecodedExtensionValue<unknown>[];
	readonly decodedExtensionMap?: DecodedExtensionMap<TMap>;
	readonly subjectKeyIdentifier?: string;
	readonly authorityKeyIdentifier?: string;
}

Properties

  • readonly der: Uint8Array — Complete DER encoding of the certificate (copied from the input).
  • readonly version: number — X.509 version number (1, 2, or 3). Almost always 3.
  • readonly serialNumberHex: string — Hex-encoded serial number assigned by the issuing CA.
  • readonly tbsCertificateDer: Uint8Array — DER encoding of the TBSCertificate, used for signature verification.
  • readonly subjectPublicKeyInfoDer: Uint8Array — DER encoding of the SubjectPublicKeyInfo, used for key import.
  • readonly signatureValue: Uint8Array — Raw signature bytes (BIT STRING content, padding removed).
  • readonly issuer: ParsedName — Distinguished name of the certificate issuer.
  • readonly subject: ParsedName — Distinguished name of the certificate subject.
  • readonly notBefore: Date — Start of the certificate validity period.
  • readonly notAfter: Date — End of the certificate validity period.
  • readonly signatureAlgorithmOid: string — OID of the algorithm used to sign this certificate (e.g. "1.2.840.113549.1.1.11" for SHA-256 with RSA).
  • readonly signatureAlgorithmName: string — Human-readable signature algorithm name (e.g. "ECDSA with SHA-256").
  • readonly signatureAlgorithmParametersDer?: Uint8Array — DER-encoded parameters for the signature algorithm. Absent for algorithms with no parameters.
  • readonly publicKeyAlgorithmOid: string — OID of the subject's public key algorithm (e.g. "1.2.840.10045.2.1" for EC).
  • readonly publicKeyAlgorithmName: string — Human-readable public key algorithm name (e.g. "EC P-256").
  • readonly publicKeyAlgorithmParametersDer?: Uint8Array — DER-encoded parameters for the public key algorithm. Absent when implicit.
  • readonly publicKeyParametersOid?: string — OID of the named curve or other key sub-parameter, when present.
  • readonly extensions: readonly ParsedExtension[] — All extensions as raw ParsedExtensions, in certificate order.
  • readonly basicConstraints?: BasicConstraints — Decoded Basic Constraints (RFC 5280 §4.2.1.9).
  • readonly keyUsage?: ParsedBitFlags<KeyUsage> — Decoded Key Usage bit flags (RFC 5280 §4.2.1.3).
  • readonly extendedKeyUsage?: readonly ExtendedKeyUsage[] — Decoded Extended Key Usage purposes (RFC 5280 §4.2.1.12).
  • readonly subjectAltNames?: readonly SubjectAltName[] — Decoded Subject Alternative Names (RFC 5280 §4.2.1.6).
  • readonly nameConstraints?: NameConstraints<ParsedNameConstraintForm> — Decoded Name Constraints (RFC 5280 §4.2.1.10).
  • readonly certificatePolicies?: CertificatePolicies — Decoded Certificate Policies (RFC 5280 §4.2.1.4).
  • readonly policyMappings?: PolicyMappings — Decoded Policy Mappings (RFC 5280 §4.2.1.5).
  • readonly policyConstraints?: PolicyConstraints — Decoded Policy Constraints (RFC 5280 §4.2.1.11).
  • readonly inhibitAnyPolicy?: InhibitAnyPolicy — Decoded Inhibit anyPolicy (RFC 5280 §4.2.1.14).
  • readonly authorityInfoAccess?: readonly AuthorityInformationAccess[] — Decoded Authority Information Access — OCSP and CA Issuer URIs (RFC 5280 §4.2.2.1).
  • readonly crlDistributionPoints?: readonly ParsedDistributionPoint[] — Decoded CRL Distribution Points (RFC 5280 §4.2.1.13).
  • readonly decodedExtensions?: readonly DecodedExtensionValue<unknown>[] — Custom-decoded extensions from ParseOptions.decoders.
  • readonly decodedExtensionMap?: DecodedExtensionMap<TMap> — Custom-decoded extensions from ParseOptions.decoderMap, keyed by map key.
  • readonly subjectKeyIdentifier?: string — Hex-encoded Subject Key Identifier (RFC 5280 §4.2.1.2).
  • readonly authorityKeyIdentifier?: string — Hex-encoded Authority Key Identifier (RFC 5280 §4.2.1.1).

ParsedCertificateSigningRequest

A fully decoded PKCS#10 Certificate Signing Request.

Extension fields mirror ParsedCertificate but come from the CSR's extensionRequest attribute rather than the v3 extensions block.

ts
interface ParsedCertificateSigningRequest<TMap extends ExtensionDecoderMap> {
	readonly version: number;
	readonly certificationRequestInfoDer: Uint8Array;
	readonly subjectPublicKeyInfoDer: Uint8Array;
	readonly signatureValue: Uint8Array;
	readonly subject: ParsedName;
	readonly signatureAlgorithmOid: string;
	readonly signatureAlgorithmName: string;
	readonly signatureAlgorithmParametersDer?: Uint8Array;
	readonly publicKeyAlgorithmOid: string;
	readonly publicKeyAlgorithmName: string;
	readonly publicKeyAlgorithmParametersDer?: Uint8Array;
	readonly publicKeyParametersOid?: string;
	readonly requestedExtensions: readonly ParsedExtension[];
	readonly basicConstraints?: BasicConstraints;
	readonly keyUsage?: ParsedBitFlags<KeyUsage>;
	readonly extendedKeyUsage?: readonly ExtendedKeyUsage[];
	readonly subjectAltNames?: readonly SubjectAltName[];
	readonly nameConstraints?: NameConstraints<ParsedNameConstraintForm>;
	readonly certificatePolicies?: CertificatePolicies;
	readonly policyMappings?: PolicyMappings;
	readonly policyConstraints?: PolicyConstraints;
	readonly inhibitAnyPolicy?: InhibitAnyPolicy;
	readonly authorityInfoAccess?: readonly AuthorityInformationAccess[];
	readonly crlDistributionPoints?: readonly ParsedDistributionPoint[];
	readonly decodedExtensions?: readonly DecodedExtensionValue<unknown>[];
	readonly decodedExtensionMap?: DecodedExtensionMap<TMap>;
}

Properties

  • readonly version: number — PKCS#10 version number (always 1).
  • readonly certificationRequestInfoDer: Uint8Array — DER encoding of the CertificationRequestInfo, used for signature verification.
  • readonly subjectPublicKeyInfoDer: Uint8Array — DER encoding of the SubjectPublicKeyInfo.
  • readonly signatureValue: Uint8Array — Raw signature bytes (BIT STRING content, padding removed).
  • readonly subject: ParsedName — Distinguished name the requester wants on the certificate.
  • readonly signatureAlgorithmOid: string — OID of the algorithm used to sign this CSR.
  • readonly signatureAlgorithmName: string — Human-readable signature algorithm name (e.g. "ECDSA with SHA-256").
  • readonly signatureAlgorithmParametersDer?: Uint8Array — DER-encoded parameters for the signature algorithm. Absent for algorithms with no parameters.
  • readonly publicKeyAlgorithmOid: string — OID of the subject's public key algorithm.
  • readonly publicKeyAlgorithmName: string — Human-readable public key algorithm name (e.g. "EC P-256").
  • readonly publicKeyAlgorithmParametersDer?: Uint8Array — DER-encoded parameters for the public key algorithm.
  • readonly publicKeyParametersOid?: string — OID of the named curve or other key sub-parameter, when present.
  • readonly requestedExtensions: readonly ParsedExtension[] — All requested extensions as raw ParsedExtensions.
  • readonly basicConstraints?: BasicConstraints — Decoded Basic Constraints from the extensionRequest attribute.
  • readonly keyUsage?: ParsedBitFlags<KeyUsage> — Decoded Key Usage from the extensionRequest attribute.
  • readonly extendedKeyUsage?: readonly ExtendedKeyUsage[] — Decoded Extended Key Usage from the extensionRequest attribute.
  • readonly subjectAltNames?: readonly SubjectAltName[] — Decoded Subject Alternative Names from the extensionRequest attribute.
  • readonly nameConstraints?: NameConstraints<ParsedNameConstraintForm> — Decoded Name Constraints from the extensionRequest attribute.
  • readonly certificatePolicies?: CertificatePolicies — Decoded Certificate Policies from the extensionRequest attribute.
  • readonly policyMappings?: PolicyMappings — Decoded Policy Mappings from the extensionRequest attribute.
  • readonly policyConstraints?: PolicyConstraints — Decoded Policy Constraints from the extensionRequest attribute.
  • readonly inhibitAnyPolicy?: InhibitAnyPolicy — Decoded Inhibit anyPolicy from the extensionRequest attribute.
  • readonly authorityInfoAccess?: readonly AuthorityInformationAccess[] — Decoded Authority Information Access from the extensionRequest attribute.
  • readonly crlDistributionPoints?: readonly ParsedDistributionPoint[] — Decoded CRL Distribution Points from the extensionRequest attribute.
  • readonly decodedExtensions?: readonly DecodedExtensionValue<unknown>[] — Custom-decoded extensions from ParseOptions.decoders.
  • readonly decodedExtensionMap?: DecodedExtensionMap<TMap> — Custom-decoded extensions from ParseOptions.decoderMap.

ParsedDistributionPoint

A decoded DistributionPoint from the CRL Distribution Points extension.

ts
interface ParsedDistributionPoint {
	readonly distributionPoint?: ParsedDistributionPointName;
	readonly reasons?: ParsedBitFlags<DistributionPointReason>;
	readonly crlIssuer?: readonly GeneralName[];
}

Properties

  • readonly distributionPoint?: ParsedDistributionPointName — Where to fetch the CRL — a fullName URI or relativeName.
  • readonly reasons?: ParsedBitFlags<DistributionPointReason> — Revocation reason subset this distribution point covers. Absent means all reasons.
  • readonly crlIssuer?: readonly GeneralName[] — Entity that signed the CRL, when different from the certificate issuer.

ParsedDistributionPointName

The name component of a CRL Distribution Point (RFC 5280 §4.2.1.13). Exactly one of fullName or relativeName will be present.

ts
interface ParsedDistributionPointName {
	readonly fullName?: readonly GeneralName[];
	readonly relativeName?: ParsedRelativeDistinguishedName;
}

Properties

  • readonly fullName?: readonly GeneralName[] — Absolute GeneralName(s) identifying the distribution point.
  • readonly relativeName?: ParsedRelativeDistinguishedName — Name relative to the CRL issuer's distinguished name.

ParsedExtension

A raw X.509v3 extension before type-specific decoding.

ts
interface ParsedExtension {
	readonly oid: string;
	readonly critical: boolean;
	readonly valueDer: Uint8Array;
	readonly valueHex: string;
}

Properties

  • readonly oid: string — Dotted-decimal OID identifying this extension.
  • readonly critical: boolean — Whether a validator MUST reject the certificate if it cannot process this extension.
  • readonly valueDer: Uint8Array — DER-encoded OCTET STRING payload (extnValue).
  • readonly valueHex: string — Hex-encoded form of valueDer for display and comparison.

ParsedName

An X.501 Distinguished Name decoded from an issuer or subject field.

Provides three views of the same data: ordered RDNs, a flat attribute list, and a convenience key-value map for well-known fields.

ts
interface ParsedName {
	readonly derHex: string;
	readonly rdns: readonly ParsedRelativeDistinguishedName[];
	readonly attributes: readonly ParsedNameAttribute[];
	readonly values: Readonly<Partial<Record<NameFieldKey, string>>>;
}

Properties

  • readonly derHex: string — Hex-encoded DER of the complete Name SEQUENCE, usable for byte-exact comparisons.
  • readonly rdns: readonly ParsedRelativeDistinguishedName[] — Ordered list of RelativeDistinguishedNames, preserving multi-valued RDN structure.
  • readonly attributes: readonly ParsedNameAttribute[] — Flat list of every attribute across all RDNs, in encounter order.
  • readonly values: Readonly<Partial<Record<NameFieldKey, string>>> — First-occurrence map of well-known fields (CN, O, OU, etc.) for quick lookups.

ParsedNameAttribute

A single decoded name attribute from an X.501 RelativeDistinguishedName.

RFC 5280 / X.501 call this structure an AttributeTypeAndValue.

ts
interface ParsedNameAttribute {
	readonly oid: string;
	readonly key?: NameFieldKey;
	readonly valueTag: number;
	readonly value: string;
}

Properties

  • readonly oid: string — Dotted-decimal OID of the attribute type (e.g. "2.5.4.3" for CN).
  • readonly key?: NameFieldKey — Friendly key when the OID maps to a well-known field (CN, O, etc.).
  • readonly valueTag: number — ASN.1 tag of the value encoding (UTF8String = 0x0c, PrintableString = 0x13, etc.).
  • readonly value: string — Decoded string content of the attribute value.

See also

ParsedRelativeDistinguishedName

A single RelativeDistinguishedName SET from an X.501 Name.

ts
interface ParsedRelativeDistinguishedName {
	readonly derHex: string;
	readonly attributes: readonly ParsedNameAttribute[];
	readonly values: Readonly<Partial<Record<NameFieldKey, string>>>;
}

Properties

  • readonly derHex: string — Hex-encoded DER of this RDN SET element.
  • readonly attributes: readonly ParsedNameAttribute[] — Attributes within this RDN (usually one, but multi-valued RDNs are legal).
  • readonly values: Readonly<Partial<Record<NameFieldKey, string>>> — First-occurrence map of well-known fields within this RDN.

ParseOptions

Options for parseCertificateDer, parseCertificatePem, and CSR parse functions.

Supply custom extension decoders to have their results included in the parsed output alongside the built-in extensions.

ts
interface ParseOptions<TMap extends ExtensionDecoderMap> {
	readonly decoders?: readonly ExtensionDecoder<unknown>[];
	readonly decoderMap?: TMap;
}

Properties

  • readonly decoders?: readonly ExtensionDecoder<unknown>[] — Array of decoders; decoded values appear in decodedExtensions.
  • readonly decoderMap?: TMap — Named decoder map; decoded values appear in decodedExtensionMap keyed by map key.

certificateMatchesPrivateKey

Check whether a certificate's subject public key belongs to a private key.

Confirming that an uploaded private key actually matches the certificate it was submitted with is the first thing a key-intake or issuance endpoint must do. This derives the public half of privateKey, exports it as SubjectPublicKeyInfo DER, and compares those bytes against the certificate's own SubjectPublicKeyInfo — the canonical, algorithm-agnostic way to test key ownership. (Comparing JWKs field by field, or signing a probe and verifying it, are both more fragile.)

A private key of a different type — e.g. an ECDSA key against an RSA certificate — simply produces different SPKI DER and returns false, so callers get a single boolean without branching on the kind of mismatch. Reach for matchCertificatePrivateKey when you need the reason a match failed (or a typed failure instead of a thrown error) at a trust boundary.

The comparison is over the exact DER encoding. A certificate whose SubjectPublicKeyInfo pins RSASSA-PSS parameters (rather than the plain rsaEncryption OID that WebCrypto emits) therefore will not match even for the same modulus; such certificates are rare in practice.

ts
function certificateMatchesPrivateKey<TMap extends ExtensionDecoderMap>(
	certificate: ParsedCertificate<TMap> | string | Uint8Array,
	privateKey: CryptoKey,
): Promise<boolean>

Parameters

  • certificate: ParsedCertificate<TMap> | string | Uint8Array — PEM string, DER bytes, or an already-parsed certificate.
  • privateKey: CryptoKey — An extractable private CryptoKey.

Returnstrue when the private key's public half matches the certificate's subject public key.

Throws

  • Error — If certificate is malformed, or privateKey is not an extractable private key of a supported type (propagated from derivePublicKey). Use matchCertificatePrivateKey for a typed Result instead of thrown errors.

See also

Examples

ts
const privateKey = await importPkcs8PemOrThrow(keyPem, { kind: 'ecdsa', curve: 'P-256' });
if (!(await certificateMatchesPrivateKey(certificatePem, privateKey))) {
  throw new Error('uploaded key does not match the certificate');
}

decodeExtension

Decode a single extension using a custom ExtensionDecoder.

ts
function decodeExtension<TValue>(
	extensions: readonly ParsedExtension[],
	decoder: ExtensionDecoder<TValue>,
): TValue | undefined

Parameters

Returns — The decoded value, or undefined if the extension is absent.

decodeExtensionMap

Decode all matching extensions using a named ExtensionDecoderMap.

ts
function decodeExtensionMap<TMap extends ExtensionDecoderMap>(
	extensions: readonly ParsedExtension[],
	decoderMap: TMap,
): DecodedExtensionMap<TMap>

Parameters

  • extensions: readonly ParsedExtension[] — Extension list to search.
  • decoderMap: TMap — Named decoders. Results are keyed by the same map keys.

decodeExtensions

Decode all matching extensions using an array of ExtensionDecoders.

ts
function decodeExtensions(
	extensions: readonly ParsedExtension[],
	decoders: readonly ExtensionDecoder<unknown>[],
): readonly DecodedExtensionValue<unknown>[]

Parameters

  • extensions: readonly ParsedExtension[] — Extension list to search.
  • decoders: readonly ExtensionDecoder<unknown>[] — Decoders to apply. Only matching OIDs produce output.

defineExtensionDecoder

Identity helper that narrows the type of a custom ExtensionDecoder literal.

ts
function defineExtensionDecoder<TValue>(
	decoder: ExtensionDecoder<TValue>,
): ExtensionDecoder<TValue>

Parameters

Returns — The same decoder, properly typed.

defineExtensionDecoderMap

Identity helper that narrows the type of a custom ExtensionDecoderMap literal.

ts
function defineExtensionDecoderMap<TMap extends ExtensionDecoderMap>(
	decoderMap: TMap,
): TMap

Parameters

  • decoderMap: TMap — Map of named decoders to return unchanged.

Returns — The same map, properly typed.

findExtension

Find a raw extension by OID within a parsed extension list.

ts
function findExtension(
	extensions: readonly ParsedExtension[],
	oid: string,
): ParsedExtension | undefined

Parameters

Returns — The matching extension, or undefined if not present.

getSubjectPublicKey

Import the subject public key of a parsed certificate or CSR as a WebCrypto CryptoKey.

ts
function getSubjectPublicKey<TMap extends ExtensionDecoderMap>(
	parsed: ParsedCertificate<TMap> | ParsedCertificateSigningRequest<TMap>,
	algorithm?: PublicKeyImportInput,
): Promise<ImportKeyResult<CryptoKey>>

Parameters

See also

  • getSubjectPublicKeyOrThrow for the throwing variant

getSubjectPublicKeyOrThrow

Import the subject public key of a parsed certificate or CSR as a WebCrypto CryptoKey.

The key algorithm — and, for EC keys, the curve — is inferred from the SubjectPublicKeyInfo's own AlgorithmIdentifier (the same resolution importSpkiDerOrThrow applies when no algorithm is given), so callers never map ParsedCertificate.publicKeyAlgorithmOid / ParsedCertificate.publicKeyParametersOid by hand.
RSA keys import with the default pkcs1-v1_5/SHA-256 parameters (a plain rsaEncryption SPKI encodes neither padding scheme nor hash); pass algorithm to choose other RSA parameters or to assert an expected algorithm.

ts
function getSubjectPublicKeyOrThrow<TMap extends ExtensionDecoderMap>(
	parsed: ParsedCertificate<TMap> | ParsedCertificateSigningRequest<TMap>,
	algorithm?: PublicKeyImportInput,
): Promise<CryptoKey>

Parameters

Returns — Extractable CryptoKey with verify usage.

Throws

  • Error — If the SubjectPublicKeyInfo is malformed, encodes an unsupported algorithm, or doesn't match algorithm

See also

Examples

ts
const parsed = parseCertificatePemOrThrow(pem);
const publicKey = await getSubjectPublicKeyOrThrow(parsed);

matchCertificatePrivateKey

Check whether a certificate's subject public key belongs to a private key, returning a typed MatchCertificatePrivateKeyResult.

The Result-returning companion to certificateMatchesPrivateKey: where the boolean helper answers only "does it match?" (and throws on bad input), this surfaces the expected failures a key-intake or issuance endpoint meets on untrusted input as typed codes rather than exceptions — matching the house rule of returning Result for expected failures and throwing only for invariants. ok: true means the key owns the certificate; a failure carries one of:

  • malformed_certificatecertificate could not be parsed.
  • unsupported_private_keyprivateKey is not an extractable private key of a supported type (from derivePublicKey).
  • key_type_mismatch — the key is a different algorithm than the certificate's subject public key.
  • key_mismatch — the key is the right algorithm but a different key.

As with certificateMatchesPrivateKey, the comparison is over exact SPKI DER, so a certificate pinning RSASSA-PSS parameters reports key_type_mismatch against the rsaEncryption SPKI WebCrypto emits.

ts
function matchCertificatePrivateKey<TMap extends ExtensionDecoderMap>(
	certificate: ParsedCertificate<TMap> | string | Uint8Array,
	privateKey: CryptoKey,
): Promise<MatchCertificatePrivateKeyResult>

Parameters

  • certificate: ParsedCertificate<TMap> | string | Uint8Array — PEM string, DER bytes, or an already-parsed certificate.
  • privateKey: CryptoKey — An extractable private CryptoKey.

Returns — A success when the key matches, or a typed failure otherwise.

See also

Examples

ts
const result = await matchCertificatePrivateKey(certificatePem, privateKey);
if (!result.ok) {
  // result.code is 'malformed_certificate' | 'unsupported_private_key'
  //              | 'key_type_mismatch' | 'key_mismatch'
  throw new Error(`key does not match certificate: ${result.code}`);
}

parseCertificateChainPem

Decode a PEM bundle containing one or more certificates.

Non-CERTIFICATE blocks (e.g. private keys) are silently skipped.

ts
function parseCertificateChainPem<TMap extends ExtensionDecoderMap>(
	pemBundle: string,
	options?: ParseOptions<TMap>,
): readonly ParsedCertificate<TMap>[]

Parameters

  • pemBundle: string — PEM text that may contain multiple CERTIFICATE blocks.
  • options?: ParseOptions<TMap> — Custom extension decoders to apply during parsing.

parseCertificateDer

Decode a DER-encoded X.509 certificate into a ParsedCertificate.

ts
function parseCertificateDer<TMap extends ExtensionDecoderMap>(
	der: Uint8Array,
	options?: ParseOptions<TMap>,
): ParseCertificateResult<TMap>

Parameters

  • der: Uint8Array — Raw DER bytes of an X.509 certificate.
  • options?: ParseOptions<TMap> — Custom extension decoders to apply during parsing.

Examples

ts
import { parseCertificateDer } from 'micro509';

const result = parseCertificateDer(derBytes);
if (result.ok) {
	console.log(result.value.subject.values.commonName); // "example.com"
}

parseCertificateDerOrThrow

Throwing core for parseCertificateDer.

Decodes a DER-encoded X.509 certificate into a ParsedCertificate, throwing on malformed input. All built-in extensions (basicConstraints, keyUsage, subjectAltNames, etc.) are decoded automatically.
Pass ParseOptions to also decode custom extensions.

ts
function parseCertificateDerOrThrow<TMap extends ExtensionDecoderMap>(
	der: Uint8Array,
	options?: ParseOptions<TMap>,
): ParsedCertificate<TMap>

Parameters

  • der: Uint8Array — Raw DER bytes of an X.509 certificate.
  • options?: ParseOptions<TMap> — Custom extension decoders to apply during parsing.

parseCertificatePem

Decode a PEM-encoded X.509 certificate into a ParsedCertificate.

Expects a single -----BEGIN CERTIFICATE----- block. For bundles containing multiple certificates, use parseCertificateChainPem.

ts
function parseCertificatePem<TMap extends ExtensionDecoderMap>(
	pem: string,
	options?: ParseOptions<TMap>,
): ParseCertificateResult<TMap>

Parameters

  • pem: string — PEM string with a CERTIFICATE block.
  • options?: ParseOptions<TMap> — Custom extension decoders to apply during parsing.

parseCertificatePemOrThrow

Decode a PEM-encoded X.509 certificate into a ParsedCertificate.

Expects a single -----BEGIN CERTIFICATE----- block. For bundles containing multiple certificates, use parseCertificateChainPem.

ts
function parseCertificatePemOrThrow<TMap extends ExtensionDecoderMap>(
	pem: string,
	options?: ParseOptions<TMap>,
): ParsedCertificate<TMap>

Parameters

  • pem: string — PEM string with a CERTIFICATE block.
  • options?: ParseOptions<TMap> — Custom extension decoders to apply during parsing.

Examples

Throws on malformed input. For a typed failure instead, use the Result-returning {@linkcode parseCertificatePem}.

ts
const certificate = parseCertificatePemOrThrow(pemString); // throws if malformed
console.log(certificate.issuer.values.organization); // "Let's Encrypt"

parseCertificateSigningRequestDer

Decode a DER-encoded PKCS#10 CSR into a ParsedCertificateSigningRequest.

ts
function parseCertificateSigningRequestDer<TMap extends ExtensionDecoderMap>(
	der: Uint8Array,
	options?: ParseOptions<TMap>,
): ParseCertificateSigningRequestResult<TMap>

Parameters

  • der: Uint8Array — Raw DER bytes of a PKCS#10 certificate signing request.
  • options?: ParseOptions<TMap> — Custom extension decoders to apply during parsing.

parseCertificateSigningRequestDerOrThrow

Decode a DER-encoded PKCS#10 CSR into a ParsedCertificateSigningRequest.

ts
function parseCertificateSigningRequestDerOrThrow<TMap extends ExtensionDecoderMap>(
	der: Uint8Array,
	options?: ParseOptions<TMap>,
): ParsedCertificateSigningRequest<TMap>

Parameters

  • der: Uint8Array — Raw DER bytes of a PKCS#10 certificate signing request.
  • options?: ParseOptions<TMap> — Custom extension decoders to apply during parsing.

parseCertificateSigningRequestPem

Decode a PEM-encoded PKCS#10 CSR into a ParsedCertificateSigningRequest.

ts
function parseCertificateSigningRequestPem<TMap extends ExtensionDecoderMap>(
	pem: string,
	options?: ParseOptions<TMap>,
): ParseCertificateSigningRequestResult<TMap>

Parameters

  • pem: string — PEM string with a CERTIFICATE REQUEST block.
  • options?: ParseOptions<TMap> — Custom extension decoders to apply during parsing.

parseCertificateSigningRequestPemOrThrow

Decode a PEM-encoded PKCS#10 CSR into a ParsedCertificateSigningRequest.

ts
function parseCertificateSigningRequestPemOrThrow<TMap extends ExtensionDecoderMap>(
	pem: string,
	options?: ParseOptions<TMap>,
): ParsedCertificateSigningRequest<TMap>

Parameters

  • pem: string — PEM string with a CERTIFICATE REQUEST block.
  • options?: ParseOptions<TMap> — Custom extension decoders to apply during parsing.

Released under the MIT License.