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.
interface CertificateMaterial {
readonly der: Uint8Array;
readonly pem: string;
readonly base64: string;
}Properties
readonlyder:Uint8Array— DER-encoded certificate bytes.readonlypem:string— PEM-encoded certificate.readonlybase64:string— Base64 encoding ofderwithout PEM armor.
CreateCertificateInput
Input for createCertificate.
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
readonlyissuer:NameInput— Issuer distinguished name.readonlysubject:NameInput— Subject distinguished name.readonlypublicKey:CryptoKey— Subject public key to encode into the certificate.readonlysignerPrivateKey:CryptoKey— Private key used to sign the certificate.readonlyissuerPublicKey?:CryptoKey— Issuer public key.Provide this when extension builders need issuer key material, such as authority key identifier derivation.
readonlyvalidity?:ValidityInput— Validity window configuration.readonlyserialNumber?:Uint8Array— DER integer bytes for the certificate serial number.When omitted, a random positive 16-byte serial number is generated.
readonlyextensions?:CertificateExtensionsInput— X.509 extensions to encode into the certificate.readonlysignature?:SignatureProfileInput— Signature algorithm override.When omitted, the library selects a compatible profile from the signing key.
CreateSelfSignedCertificateInput
Input for createSelfSignedCertificate.
interface CreateSelfSignedCertificateInput {
readonly subject: NameInput;
readonly algorithm?: KeyAlgorithmInput;
readonly keyPair?: KeyPairMaterial;
readonly validity?: ValidityInput;
readonly serialNumber?: Uint8Array;
readonly extensions?: CertificateExtensionsInput;
readonly signature?: SignatureProfileInput;
}Properties
readonlysubject:NameInput— Subject distinguished name used as both subject and issuer.readonlyalgorithm?:KeyAlgorithmInput— Key generation parameters.Ignored when
keyPairis provided.readonlykeyPair?:KeyPairMaterial— Existing key pair to reuse for both subject and issuer.When omitted, a new key pair is generated.
readonlyvalidity?:ValidityInput— Validity window configuration.readonlyserialNumber?:Uint8Array— DER integer bytes for the certificate serial number.readonlyextensions?:CertificateExtensionsInput— X.509 extensions to encode into the certificate.readonlysignature?:SignatureProfileInput— Signature algorithm override.
SelfSignedCertificateResult
Result returned by createSelfSignedCertificate.
interface SelfSignedCertificateResult {
readonly certificate: CertificateMaterial;
readonly keyPair: KeyPairMaterial;
}Properties
readonlycertificate:CertificateMaterial— Encoded certificate outputs.readonlykeyPair:KeyPairMaterial— Key pair used to issue the certificate.
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.
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.
interface ValidityInput {
readonly notBefore?: Date;
readonly notAfter?: Date;
readonly days?: number;
}Properties
readonlynotBefore?:Date— Start of the validity window.Defaults to the current time.
readonlynotAfter?:Date— End of the validity window.Must be later than
notBefore.readonlydays?:number— Number of days to add tonotBeforewhennotAfteris 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.
function createCertificate(
input: CreateCertificateInput,
): Promise<CertificateMaterial>Parameters
input:CreateCertificateInput— Issuer, subject, key, validity, and extension settings.
Returns — The encoded certificate material.
Examples
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.
function createSelfSignedCertificate(
input: CreateSelfSignedCertificateInput,
): Promise<SelfSignedCertificateResult>Parameters
input:CreateSelfSignedCertificateInput— Certificate subject, key, validity, and extension settings.
Returns — The certificate plus the key pair used to sign it.
Examples
const { certificate, keyPair } = await createSelfSignedCertificate({
subject: { commonName: 'example.com' },
algorithm: { kind: 'ecdsa', curve: 'P-256' },
});CreateCsrInput
Input for createCertificateSigningRequest.
interface CreateCsrInput {
readonly subject: NameInput;
readonly publicKey: CryptoKey;
readonly signerPrivateKey: CryptoKey;
readonly extensions?: CertificateExtensionsInput;
readonly signature?: SignatureProfileInput;
}Properties
readonlysubject:NameInput— Distinguished name for the CSR subject (e.g.{ commonName: 'example.com' }).readonlypublicKey:CryptoKey— WebCrypto public key to embed in the CSR's SubjectPublicKeyInfo.readonlysignerPrivateKey:CryptoKey— WebCrypto private key used to self-sign the CSR (proves key possession).readonlyextensions?:CertificateExtensionsInput— Requested X.509v3 extensions to include in the CSR attributes.readonlysignature?:SignatureProfileInput— Override the signature algorithm profile (hash, salt length, etc.).
CsrMaterial
DER, PEM, and base64 encodings of a CSR produced by createCertificateSigningRequest.
interface CsrMaterial {
readonly der: Uint8Array;
readonly pem: string;
readonly base64: string;
}Properties
readonlyder:Uint8Array— Raw DER-encoded PKCS#10 CertificationRequest.readonlypem:string— PEM-armored CSR (-----BEGIN CERTIFICATE REQUEST-----).readonlybase64: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.
function createCertificateSigningRequest(
input: CreateCsrInput,
): Promise<CsrMaterial>Parameters
input:CreateCsrInput
Examples
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.
type AuthorityInfoAccessMethod = KnownAuthorityInfoAccessMethod | CustomAuthorityInfoAccessMethodAuthorityInformationAccess
A single entry in the Authority Information Access extension (RFC 5280 §4.2.2.1).
interface AuthorityInformationAccess {
readonly method: ocsp | caIssuers | {
readonly type: oid;
readonly value: string
};
readonly uri: string;
}Properties
readonlymethod:ocsp|caIssuers| {readonlytype:oid;readonlyvalue:string} — Access method ('ocsp','caIssuers', or custom OID).readonlyuri: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.
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.
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
readonlysubjectAltNames?:readonlySubjectAltName[]— Subject Alternative Names (dns, ip, email, uri, srv, directoryName).readonlykeyUsage?:readonlyKeyUsage[]— Key Usage flags (digitalSignature, keyCertSign, etc.).readonlybasicConstraints?:BasicConstraints— Basic Constraints (CA flag + optional pathLength). Defaults to{ ca: false }for certs.readonlyextendedKeyUsage?:readonlyExtendedKeyUsage[]— Extended Key Usage purposes (serverAuth, clientAuth, etc.).readonlynameConstraints?:NameConstraints— Name Constraints — permitted and/or excluded subtrees.readonlycertificatePolicies?:CertificatePolicies— Certificate Policies with optional qualifiers.readonlypolicyMappings?:PolicyMappings— Policy Mappings between issuer and subject policy domains.readonlypolicyConstraints?:PolicyConstraints— Policy Constraints (requireExplicitPolicy / inhibitPolicyMapping thresholds).readonlyinhibitAnyPolicy?:InhibitAnyPolicy— Inhibit anyPolicy skip-certs threshold.readonlyauthorityInfoAccess?:readonlyAuthorityInformationAccess[]— Authority Information Access — OCSP responder and CA issuer URIs.readonlycrlDistributionPoints?:readonlyDistributionPoint[]— CRL Distribution Points — where to check revocation status.readonlycustomExtensions?:readonlyCustomExtension[]— Arbitrary extensions not covered by the built-in fields.
CertificatePolicies
RFC 5280 §4.2.1.4 — array of policy OIDs with optional qualifiers.
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.
interface CpsPolicyQualifierInfo {
readonly type: cps;
readonly uri: string;
}Properties
readonlytype:cps— Discriminant for the'cps'qualifier variant.readonlyuri:string— URL of the Certification Practice Statement document.
CustomAuthorityInfoAccessMethod
AIA access method identified by a custom OID not in the well-known set.
interface CustomAuthorityInfoAccessMethod {
readonly type: oid;
readonly value: string;
}Properties
readonlytype:oid— Discriminant for the custom-OID access method variant.readonlyvalue:string— Dotted-decimal OID of the access method.
CustomExtendedKeyUsage
Extended Key Usage purpose identified by a custom OID.
interface CustomExtendedKeyUsage {
readonly type: oid;
readonly value: string;
}Properties
readonlytype:oid— Discriminant for the custom-OID EKU variant.readonlyvalue:string— Dotted-decimal OID of the usage purpose.
CustomExtension
An extension not covered by the typed fields in CertificateExtensionsInput.
interface CustomExtension {
readonly oid: string;
readonly value: Uint8Array;
readonly critical?: boolean;
}Properties
readonlyoid:string— Dotted-decimal OID of the extension.readonlyvalue:Uint8Array— Pre-encoded DER content for the extnValue OCTET STRING.readonlycritical?:boolean— Whether the extension is critical. Defaultfalse.
CustomPolicyQualifierInfo
Opaque policy qualifier identified by a custom OID, carried as raw DER.
interface CustomPolicyQualifierInfo {
readonly type: oid;
readonly oid: string;
readonly qualifierDer: Uint8Array;
}Properties
readonlytype:oid— Discriminant for the custom-OID qualifier variant.readonlyoid:string— Dotted-decimal OID of the qualifier.readonlyqualifierDer: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.
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.
interface DistributionPointName {
readonly fullName?: readonly GeneralName[];
readonly relativeName?: RelativeDistinguishedNameInput;
}Properties
readonlyfullName?:readonlyGeneralName[]— AbsoluteGeneralName(s) identifying the distribution point (usually a URI).readonlyrelativeName?:RelativeDistinguishedNameInput— Name relative to the issuer's DN; mutually exclusive withfullName.
DistributionPointReason
Revocation reason flags for CRL Distribution Points and Issuing Distribution Points (RFC 5280 §4.2.1.13, §5.2.5).
type DistributionPointReason = keyCompromise | cACompromise | affiliationChanged | superseded | cessationOfOperation | certificateHold | privilegeWithdrawn | aACompromiseExtendedKeyUsage
Extended Key Usage — either a well-known purpose string or a custom OID.
type ExtendedKeyUsage = serverAuth | clientAuth | codeSigning | emailProtection | timeStamping | ocspSigning | {
readonly type: oid;
readonly value: string
}GeneralName
Alias for SubjectAltName — used where RFC 5280 says "GeneralName".
type GeneralName = SubjectAltNameGeneralSubtree
A single subtree entry in a Name Constraints permitted/excluded list.
interface GeneralSubtree<TForm extends ParsedNameConstraintForm> {
readonly base: TForm;
}Properties
readonlybase: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.
interface InhibitAnyPolicy {
readonly skipCerts: number;
}Properties
readonlyskipCerts: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.
type KeyUsage = digitalSignature | nonRepudiation | keyEncipherment | dataEncipherment | keyAgreement | keyCertSign | cRLSign | encipherOnly | decipherOnlySee also
KnownAuthorityInfoAccessMethod
Well-known AIA access methods: OCSP responder or CA issuer certificate.
type KnownAuthorityInfoAccessMethod = ocsp | caIssuersKnownExtendedKeyUsage
Well-known Extended Key Usage purpose strings (RFC 5280 §4.2.1.12).
type KnownExtendedKeyUsage = serverAuth | clientAuth | codeSigning | emailProtection | timeStamping | ocspSigningNameConstraintForm
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.
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.
interface NameConstraints<TForm extends ParsedNameConstraintForm> {
readonly permittedSubtrees?: readonly GeneralSubtree<TForm>[];
readonly excludedSubtrees?: readonly GeneralSubtree<TForm>[];
}Properties
readonlypermittedSubtrees?:readonlyGeneralSubtree<TForm>[]— Names that MUST fall within these subtrees to be valid.readonlyexcludedSubtrees?:readonlyGeneralSubtree<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.
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.
interface PolicyConstraints {
readonly requireExplicitPolicy?: number;
readonly inhibitPolicyMapping?: number;
}Properties
readonlyrequireExplicitPolicy?:number— After this many certificates, an acceptable policy must be in the path.readonlyinhibitPolicyMapping?:number— After this many certificates, policy mapping is no longer allowed.
PolicyInformation
A single certificate policy: an OID plus optional qualifiers.
interface PolicyInformation {
readonly policyIdentifier: string;
readonly policyQualifiers?: readonly PolicyQualifierInfo[];
}Properties
readonlypolicyIdentifier:string— Dotted-decimal OID of the policy (e.g."2.23.140.1.2.1"for DV).readonlypolicyQualifiers?:readonlyPolicyQualifierInfo[]— 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.
interface PolicyMapping {
readonly issuerDomainPolicy: string;
readonly subjectDomainPolicy: string;
}Properties
readonlyissuerDomainPolicy:string— Policy OID as defined by the issuing CA. Must not be anyPolicy.readonlysubjectDomainPolicy: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.
type PolicyMappings = readonly {
readonly issuerDomainPolicy: string;
readonly subjectDomainPolicy: string
}[]PolicyNoticeReference
Reference to a numbered notice within an organization's practice statement.
interface PolicyNoticeReference {
readonly organization: string;
readonly noticeNumbers: readonly number[];
}Properties
readonlyorganization:string— Organization name that published the notice.readonlynoticeNumbers:readonlynumber``[]— One-based notice numbers within that organization's documentation.
PolicyQualifierInfo
Discriminated union of all supported policy qualifier types.
type PolicyQualifierInfo = CpsPolicyQualifierInfo | UserNoticePolicyQualifierInfo | CustomPolicyQualifierInfoSubjectAltName
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.
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.
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.
interface UserNoticePolicyQualifierInfo {
readonly type: userNotice;
readonly noticeRef?: PolicyNoticeReference;
readonly explicitText?: string;
}Properties
readonlytype:userNotice— Discriminant for the'userNotice'qualifier variant.readonlynoticeRef?:PolicyNoticeReference— Pointer to a numbered notice in an organization's practice statement.readonlyexplicitText?: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.
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, orundefinedfor 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.
function buildRequestedExtensions(
input: CertificateExtensionsInput | undefined,
): Uint8Array[]Parameters
input:CertificateExtensionsInput|undefined— Optional extension configuration.
Returns — Array of DER-encoded Extension SEQUENCEs.
encodeAuthorityInfoAccess
DER-encode an Authority Information Access SEQUENCE.
function encodeAuthorityInfoAccess(
entries: readonly AuthorityInformationAccess[],
): Uint8ArrayParameters
entries:readonlyAuthorityInformationAccess[]— AIA entries (OCSP, caIssuers, or custom) to encode.
encodeBasicConstraints
DER-encode a BasicConstraints value.
function encodeBasicConstraints(
input: BasicConstraints,
): Uint8ArrayParameters
input:BasicConstraints— CA flag and optional pathLength.
Returns — DER SEQUENCE suitable for wrapping in an Extension OCTET STRING.
encodeCertificatePolicies
DER-encode a Certificate Policies extension value.
function encodeCertificatePolicies(
policies: CertificatePolicies,
): Uint8ArrayParameters
policies:CertificatePolicies— Non-empty array of policy information entries.
encodeCrlDistributionPoints
DER-encode a CRL Distribution Points SEQUENCE.
function encodeCrlDistributionPoints(
points: readonly DistributionPoint[],
): Uint8ArrayParameters
points:readonlyDistributionPoint[]— Distribution points to encode.
encodeExtendedKeyUsage
DER-encode an Extended Key Usage SEQUENCE OF OIDs.
function encodeExtendedKeyUsage(
usages: readonly ExtendedKeyUsage[],
): Uint8ArrayParameters
usages:readonlyExtendedKeyUsage[]— EKU purposes to encode.
encodeExtension
Encode a single X.509 Extension SEQUENCE (OID + optional critical BOOLEAN + OCTET STRING).
function encodeExtension(
oid: string,
extnValue: Uint8Array,
_: unknown,
): Uint8ArrayParameters
oid:string— Dotted-decimal extension OID.extnValue:Uint8Array— DER-encoded extension payload._:unknown
encodeInhibitAnyPolicy
DER-encode an Inhibit anyPolicy extension value (single INTEGER).
function encodeInhibitAnyPolicy(
input: InhibitAnyPolicy,
): Uint8ArrayParameters
input:InhibitAnyPolicy— The skipCerts threshold.
encodeKeyUsage
DER-encode a Key Usage BIT STRING from an array of KeyUsage flags.
function encodeKeyUsage(
usages: readonly KeyUsage[],
): Uint8ArrayParameters
usages:readonlyKeyUsage[]— Flags to set in the bit string.
encodeNameConstraints
DER-encode a Name Constraints extension value.
function encodeNameConstraints(
constraints: NameConstraints,
): Uint8ArrayParameters
constraints:NameConstraints— Permitted and/or excluded subtrees.
encodePolicyConstraints
DER-encode a Policy Constraints extension value.
function encodePolicyConstraints(
constraints: PolicyConstraints,
): Uint8ArrayParameters
constraints:PolicyConstraints— At least one ofrequireExplicitPolicyorinhibitPolicyMappingmust be set.
encodePolicyMappings
DER-encode a Policy Mappings extension value.
function encodePolicyMappings(
mappings: PolicyMappings,
): Uint8ArrayParameters
mappings:PolicyMappings— Non-empty array of issuer-to-subject policy pairs. Neither OID may be anyPolicy.
encodeSubjectAltName
DER-encode a single SubjectAltName GeneralName element.
function encodeSubjectAltName(
value: SubjectAltName,
): Uint8ArrayParameters
value:SubjectAltName— The SAN entry to encode.
getAuthorityInfoAccessMethodOid
Resolve an AuthorityInfoAccessMethod to its dotted-decimal OID.
function getAuthorityInfoAccessMethodOid(
method: AuthorityInfoAccessMethod,
): stringParameters
method:AuthorityInfoAccessMethod— Well-known string or custom OID object.
getExtendedKeyUsageOid
Resolve an ExtendedKeyUsage to its dotted-decimal OID.
function getExtendedKeyUsageOid(
usage: ExtendedKeyUsage,
): stringParameters
usage:ExtendedKeyUsage— Well-known string or custom OID object.
parseAuthorityInfoAccessMethodOid
Map a dotted-decimal OID to an AuthorityInfoAccessMethod value.
Returns 'ocsp' or 'caIssuers' for recognized OIDs, or { type: 'oid', value } otherwise.
function parseAuthorityInfoAccessMethodOid(
oid: string,
): AuthorityInfoAccessMethodParameters
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.
function parseExtendedKeyUsageOid(
oid: string,
): ExtendedKeyUsageParameters
oid:string
CertificateFingerprint
The three rendered forms of a certificate fingerprint.
interface CertificateFingerprint {
readonly bytes: Uint8Array;
readonly hex: string;
readonly colonHex: string;
}Properties
readonlybytes:Uint8Array— Raw digest bytes.readonlyhex:string— Lowercase hex, no separators (e.g."a1b2c3…").readonlycolonHex:string— Uppercase hex, colon-separated (e.g."A1:B2:C3:…",openssl x509 -fingerprintstyle).
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.
type CertificateFingerprintAlgorithm = SHA-1 | SHA-256 | SHA-384 | SHA-512CertificateFingerprintSource
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.
type CertificateFingerprintSource = string | Uint8Array | ParsedCertificatecertificateFingerprint
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.
function certificateFingerprint(
certificate: CertificateFingerprintSource,
_: unknown,
): Promise<CertificateFingerprint>Parameters
certificate:CertificateFingerprintSource— PEM string, DER bytes, or aParsedCertificate._:unknown
Examples
const fingerprint = await certificateFingerprint(pemString);
console.log(fingerprint.colonHex); // "AB:CD:…" — matches `openssl x509 -fingerprint -sha256`// 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.
interface NameAttribute {
readonly type: NameFieldKey;
readonly value: string;
}Properties
readonlytype:NameFieldKey— Which attribute type this pair represents.readonlyvalue:string— The string value for this attribute (encoding chosen per field definition).
See also
- RFC 5280 Appendix A.1
encodeNameplaces each attribute in its own single-attribute RDN.encodeRelativeDistinguishedNamepacks several attributes into one RDN.
NameFieldKey
Union of recognized X.501 attribute type shorthand names.
Each key maps to an OID + ASN.1 string encoding in NAME_FIELD_DEFINITIONS.
type NameFieldKey = commonName | surname | serialNumber | country | locality | state | street | organization | organizationalUnit | title | givenName | emailAddressNameInput
Input for encodeName.
Accepts either a NameObject convenience shape or an ordered array of NameAttribute pairs.
Both forms encode one attribute per RDN.
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.
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
readonlycommonName?:string— Subject or issuer common name (CN).readonlysurname?:string— Subject surname (SN).readonlyserialNumber?:string— Device or entity serial number — not the certificate serial.readonlycountry?:string— ISO 3166 two-letter country code (C). Must be exactly 2 characters.readonlylocality?:string— City or locality (L).readonlystate?:string— State or province (ST).readonlystreet?:string— Street address.readonlyorganization?:string— Organization name (O).readonlyorganizationalUnit?:string— Organizational unit (OU). Deprecated in modern CA practice.readonlytitle?:string— Job title or functional designation.readonlygivenName?:string— First / given name (GN).readonlyemailAddress?: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.
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.
function encodeName(
input: NameInput,
): Uint8ArrayParameters
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
NameObjectinput emits populated fields in the canonical order fromNAME_OBJECT_ORDER.NameAttributearray 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 andundefinedfields are ignored when the input is aNameObject.
Examples
const der = encodeName({ country: 'US', commonName: 'example.com' });
// emits two single-attribute RDNs: C=US, then CN=example.comconst der = encodeName([
{ type: 'country', value: 'US' },
{ type: 'commonName', value: 'example.com' },
]);
// preserves caller order: C first, then CNencodeRelativeDistinguishedName
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.
function encodeRelativeDistinguishedName(
attributes: RelativeDistinguishedNameInput,
): Uint8ArrayParameters
attributes:RelativeDistinguishedNameInput— Attribute list to encode inside one RDN.
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
Attribute OIDs and ASN.1 string encodings come from
NAME_FIELD_DEFINITIONS.
Examples
const rdn = encodeRelativeDistinguishedName([
{ type: 'commonName', value: 'example.com' },
{ type: 'serialNumber', value: 'device-7' },
]);
// emits one RDN with both attributes in the same SETDecodedExtensionMap
Inferred result type when decoding extensions via an ExtensionDecoderMap.
type DecodedExtensionMap<TMap extends ExtensionDecoderMap> = undefinedDecodedExtensionValue
A successfully decoded extension value paired with its OID and criticality.
interface DecodedExtensionValue<TValue> {
readonly oid: string;
readonly critical: boolean;
readonly value: TValue;
}Properties
readonlyoid:string— Dotted-decimal OID of the decoded extension.readonlycritical:boolean— Whether the extension was marked critical in the certificate.readonlyvalue:TValue— Typed value produced by theExtensionDecoder.
ExtensionDecoder
User-supplied decoder for a single extension OID.
Register with ParseOptions.decoders or ParseOptions.decoderMap to decode custom extensions during parsing.
interface ExtensionDecoder<TValue> {
readonly oid: string;
decode(extension: ParsedExtension): TValue;
}Properties
readonlyoid:string— OID this decoder handles.
ExtensionDecoderMap
String-keyed map of ExtensionDecoders, used with ParseOptions.decoderMap.
type ExtensionDecoderMap = Record<string, ExtensionDecoder<unknown>>MatchCertificatePrivateKeyErrorCode
Machine-readable failure reason for matchCertificatePrivateKey.
type MatchCertificatePrivateKeyErrorCode = malformed_certificate | unsupported_private_key | key_type_mismatch | key_mismatchMatchCertificatePrivateKeyFailure
Structured failure payload for matchCertificatePrivateKey.
interface MatchCertificatePrivateKeyFailure extends Micro509Error<MatchCertificatePrivateKeyErrorCode> {
readonly ok: false;
}Properties
readonlyok:false— Alwaysfalsefor failures.
MatchCertificatePrivateKeyFailureResult
Failure branch of MatchCertificatePrivateKeyResult with structured error details.
type MatchCertificatePrivateKeyFailureResult = ErrorResult<MatchCertificatePrivateKeyErrorCode, Record<never, never>, MatchCertificatePrivateKeyFailure>MatchCertificatePrivateKeyResult
Result of matchCertificatePrivateKey.
type MatchCertificatePrivateKeyResult = MatchCertificatePrivateKeySuccess | MatchCertificatePrivateKeyFailureResultMatchCertificatePrivateKeySuccess
A successful match: the private key's public half is the certificate's subject public key.
interface MatchCertificatePrivateKeySuccess {
readonly ok: true;
readonly value: undefined;
}Properties
readonlyok:true— Alwaystruefor success.readonlyvalue:undefined— No payload on success — the match itself is the signal.
ParseCertificateErrorCode
Machine-readable failure reason for parseCertificateDer / parseCertificatePem.
type ParseCertificateErrorCode = malformedParseCertificateFailure
Structured failure payload for certificate parsing.
interface ParseCertificateFailure extends Micro509Error<ParseCertificateErrorCode> {
readonly ok: false;
}Properties
readonlyok:false— Alwaysfalsefor failures.
ParseCertificateResult
Success-or-failure result from parseCertificateDer / parseCertificatePem.
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.
type ParseCertificateSigningRequestErrorCode = malformedParseCertificateSigningRequestFailure
Structured failure payload for CSR parsing.
interface ParseCertificateSigningRequestFailure extends Micro509Error<ParseCertificateSigningRequestErrorCode> {
readonly ok: false;
}Properties
readonlyok:false— Alwaysfalsefor failures.
ParseCertificateSigningRequestResult
Success-or-failure result from parseCertificateSigningRequestDer / parseCertificateSigningRequestPem.
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.
interface ParsedBitFlags<T extends string> {
readonly flags: readonly T[];
readonly nonZeroPadding: boolean;
}Properties
readonlyflags:readonlyT``[]— Decoded flag values, padding bits masked.readonlynonZeroPadding:boolean—truewhen 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.
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
readonlyder:Uint8Array— Complete DER encoding of the certificate (copied from the input).readonlyversion:number— X.509 version number (1, 2, or 3). Almost always 3.readonlyserialNumberHex:string— Hex-encoded serial number assigned by the issuing CA.readonlytbsCertificateDer:Uint8Array— DER encoding of the TBSCertificate, used for signature verification.readonlysubjectPublicKeyInfoDer:Uint8Array— DER encoding of the SubjectPublicKeyInfo, used for key import.readonlysignatureValue:Uint8Array— Raw signature bytes (BIT STRING content, padding removed).readonlyissuer:ParsedName— Distinguished name of the certificate issuer.readonlysubject:ParsedName— Distinguished name of the certificate subject.readonlynotBefore:Date— Start of the certificate validity period.readonlynotAfter:Date— End of the certificate validity period.readonlysignatureAlgorithmOid:string— OID of the algorithm used to sign this certificate (e.g."1.2.840.113549.1.1.11"for SHA-256 with RSA).readonlysignatureAlgorithmName:string— Human-readable signature algorithm name (e.g."ECDSA with SHA-256").readonlysignatureAlgorithmParametersDer?:Uint8Array— DER-encoded parameters for the signature algorithm. Absent for algorithms with no parameters.readonlypublicKeyAlgorithmOid:string— OID of the subject's public key algorithm (e.g."1.2.840.10045.2.1"for EC).readonlypublicKeyAlgorithmName:string— Human-readable public key algorithm name (e.g."EC P-256").readonlypublicKeyAlgorithmParametersDer?:Uint8Array— DER-encoded parameters for the public key algorithm. Absent when implicit.readonlypublicKeyParametersOid?:string— OID of the named curve or other key sub-parameter, when present.readonlyextensions:readonlyParsedExtension[]— All extensions as rawParsedExtensions, in certificate order.readonlybasicConstraints?:BasicConstraints— Decoded Basic Constraints (RFC 5280 §4.2.1.9).readonlykeyUsage?:ParsedBitFlags<KeyUsage> — Decoded Key Usage bit flags (RFC 5280 §4.2.1.3).readonlyextendedKeyUsage?:readonlyExtendedKeyUsage[]— Decoded Extended Key Usage purposes (RFC 5280 §4.2.1.12).readonlysubjectAltNames?:readonlySubjectAltName[]— Decoded Subject Alternative Names (RFC 5280 §4.2.1.6).readonlynameConstraints?:NameConstraints<ParsedNameConstraintForm> — Decoded Name Constraints (RFC 5280 §4.2.1.10).readonlycertificatePolicies?:CertificatePolicies— Decoded Certificate Policies (RFC 5280 §4.2.1.4).readonlypolicyMappings?:PolicyMappings— Decoded Policy Mappings (RFC 5280 §4.2.1.5).readonlypolicyConstraints?:PolicyConstraints— Decoded Policy Constraints (RFC 5280 §4.2.1.11).readonlyinhibitAnyPolicy?:InhibitAnyPolicy— Decoded Inhibit anyPolicy (RFC 5280 §4.2.1.14).readonlyauthorityInfoAccess?:readonlyAuthorityInformationAccess[]— Decoded Authority Information Access — OCSP and CA Issuer URIs (RFC 5280 §4.2.2.1).readonlycrlDistributionPoints?:readonlyParsedDistributionPoint[]— Decoded CRL Distribution Points (RFC 5280 §4.2.1.13).readonlydecodedExtensions?:readonlyDecodedExtensionValue<unknown>[]— Custom-decoded extensions fromParseOptions.decoders.readonlydecodedExtensionMap?:DecodedExtensionMap<TMap> — Custom-decoded extensions fromParseOptions.decoderMap, keyed by map key.readonlysubjectKeyIdentifier?:string— Hex-encoded Subject Key Identifier (RFC 5280 §4.2.1.2).readonlyauthorityKeyIdentifier?: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.
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
readonlyversion:number— PKCS#10 version number (always 1).readonlycertificationRequestInfoDer:Uint8Array— DER encoding of the CertificationRequestInfo, used for signature verification.readonlysubjectPublicKeyInfoDer:Uint8Array— DER encoding of the SubjectPublicKeyInfo.readonlysignatureValue:Uint8Array— Raw signature bytes (BIT STRING content, padding removed).readonlysubject:ParsedName— Distinguished name the requester wants on the certificate.readonlysignatureAlgorithmOid:string— OID of the algorithm used to sign this CSR.readonlysignatureAlgorithmName:string— Human-readable signature algorithm name (e.g."ECDSA with SHA-256").readonlysignatureAlgorithmParametersDer?:Uint8Array— DER-encoded parameters for the signature algorithm. Absent for algorithms with no parameters.readonlypublicKeyAlgorithmOid:string— OID of the subject's public key algorithm.readonlypublicKeyAlgorithmName:string— Human-readable public key algorithm name (e.g."EC P-256").readonlypublicKeyAlgorithmParametersDer?:Uint8Array— DER-encoded parameters for the public key algorithm.readonlypublicKeyParametersOid?:string— OID of the named curve or other key sub-parameter, when present.readonlyrequestedExtensions:readonlyParsedExtension[]— All requested extensions as rawParsedExtensions.readonlybasicConstraints?:BasicConstraints— Decoded Basic Constraints from the extensionRequest attribute.readonlykeyUsage?:ParsedBitFlags<KeyUsage> — Decoded Key Usage from the extensionRequest attribute.readonlyextendedKeyUsage?:readonlyExtendedKeyUsage[]— Decoded Extended Key Usage from the extensionRequest attribute.readonlysubjectAltNames?:readonlySubjectAltName[]— Decoded Subject Alternative Names from the extensionRequest attribute.readonlynameConstraints?:NameConstraints<ParsedNameConstraintForm> — Decoded Name Constraints from the extensionRequest attribute.readonlycertificatePolicies?:CertificatePolicies— Decoded Certificate Policies from the extensionRequest attribute.readonlypolicyMappings?:PolicyMappings— Decoded Policy Mappings from the extensionRequest attribute.readonlypolicyConstraints?:PolicyConstraints— Decoded Policy Constraints from the extensionRequest attribute.readonlyinhibitAnyPolicy?:InhibitAnyPolicy— Decoded Inhibit anyPolicy from the extensionRequest attribute.readonlyauthorityInfoAccess?:readonlyAuthorityInformationAccess[]— Decoded Authority Information Access from the extensionRequest attribute.readonlycrlDistributionPoints?:readonlyParsedDistributionPoint[]— Decoded CRL Distribution Points from the extensionRequest attribute.readonlydecodedExtensions?:readonlyDecodedExtensionValue<unknown>[]— Custom-decoded extensions fromParseOptions.decoders.readonlydecodedExtensionMap?:DecodedExtensionMap<TMap> — Custom-decoded extensions fromParseOptions.decoderMap.
ParsedDistributionPoint
A decoded DistributionPoint from the CRL Distribution Points extension.
interface ParsedDistributionPoint {
readonly distributionPoint?: ParsedDistributionPointName;
readonly reasons?: ParsedBitFlags<DistributionPointReason>;
readonly crlIssuer?: readonly GeneralName[];
}Properties
readonlydistributionPoint?:ParsedDistributionPointName— Where to fetch the CRL — a fullName URI or relativeName.readonlyreasons?:ParsedBitFlags<DistributionPointReason> — Revocation reason subset this distribution point covers. Absent means all reasons.readonlycrlIssuer?:readonlyGeneralName[]— 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.
interface ParsedDistributionPointName {
readonly fullName?: readonly GeneralName[];
readonly relativeName?: ParsedRelativeDistinguishedName;
}Properties
readonlyfullName?:readonlyGeneralName[]— Absolute GeneralName(s) identifying the distribution point.readonlyrelativeName?:ParsedRelativeDistinguishedName— Name relative to the CRL issuer's distinguished name.
ParsedExtension
A raw X.509v3 extension before type-specific decoding.
interface ParsedExtension {
readonly oid: string;
readonly critical: boolean;
readonly valueDer: Uint8Array;
readonly valueHex: string;
}Properties
readonlyoid:string— Dotted-decimal OID identifying this extension.readonlycritical:boolean— Whether a validator MUST reject the certificate if it cannot process this extension.readonlyvalueDer:Uint8Array— DER-encoded OCTET STRING payload (extnValue).readonlyvalueHex:string— Hex-encoded form ofvalueDerfor 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.
interface ParsedName {
readonly derHex: string;
readonly rdns: readonly ParsedRelativeDistinguishedName[];
readonly attributes: readonly ParsedNameAttribute[];
readonly values: Readonly<Partial<Record<NameFieldKey, string>>>;
}Properties
readonlyderHex:string— Hex-encoded DER of the complete Name SEQUENCE, usable for byte-exact comparisons.readonlyrdns:readonlyParsedRelativeDistinguishedName[]— Ordered list of RelativeDistinguishedNames, preserving multi-valued RDN structure.readonlyattributes:readonlyParsedNameAttribute[]— Flat list of every attribute across all RDNs, in encounter order.readonlyvalues: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.
interface ParsedNameAttribute {
readonly oid: string;
readonly key?: NameFieldKey;
readonly valueTag: number;
readonly value: string;
}Properties
readonlyoid:string— Dotted-decimal OID of the attribute type (e.g."2.5.4.3"for CN).readonlykey?:NameFieldKey— Friendly key when the OID maps to a well-known field (CN, O, etc.).readonlyvalueTag:number— ASN.1 tag of the value encoding (UTF8String = 0x0c, PrintableString = 0x13, etc.).readonlyvalue:string— Decoded string content of the attribute value.
See also
ParsedRelativeDistinguishedName
A single RelativeDistinguishedName SET from an X.501 Name.
interface ParsedRelativeDistinguishedName {
readonly derHex: string;
readonly attributes: readonly ParsedNameAttribute[];
readonly values: Readonly<Partial<Record<NameFieldKey, string>>>;
}Properties
readonlyderHex:string— Hex-encoded DER of this RDN SET element.readonlyattributes:readonlyParsedNameAttribute[]— Attributes within this RDN (usually one, but multi-valued RDNs are legal).readonlyvalues: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.
interface ParseOptions<TMap extends ExtensionDecoderMap> {
readonly decoders?: readonly ExtensionDecoder<unknown>[];
readonly decoderMap?: TMap;
}Properties
readonlydecoders?:readonlyExtensionDecoder<unknown>[]— Array of decoders; decoded values appear indecodedExtensions.readonlydecoderMap?:TMap— Named decoder map; decoded values appear indecodedExtensionMapkeyed 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.
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 privateCryptoKey.
Returns — true when the private key's public half matches the certificate's subject public key.
Throws
Error— Ifcertificateis malformed, orprivateKeyis not an extractable private key of a supported type (propagated fromderivePublicKey). UsematchCertificatePrivateKeyfor a typedResultinstead of thrown errors.
See also
matchCertificatePrivateKeyfor the typed-Resultvariant with a mismatch reasongetSubjectPublicKeyOrThrowto obtain the certificate's public key directlyderivePublicKeyfor the private-to-public bridge this builds on
Examples
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.
function decodeExtension<TValue>(
extensions: readonly ParsedExtension[],
decoder: ExtensionDecoder<TValue>,
): TValue | undefinedParameters
extensions:readonlyParsedExtension[]— Extension list to search.decoder:ExtensionDecoder<TValue> — Decoder whose OID will be matched.
Returns — The decoded value, or undefined if the extension is absent.
decodeExtensionMap
Decode all matching extensions using a named ExtensionDecoderMap.
function decodeExtensionMap<TMap extends ExtensionDecoderMap>(
extensions: readonly ParsedExtension[],
decoderMap: TMap,
): DecodedExtensionMap<TMap>Parameters
extensions:readonlyParsedExtension[]— 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.
function decodeExtensions(
extensions: readonly ParsedExtension[],
decoders: readonly ExtensionDecoder<unknown>[],
): readonly DecodedExtensionValue<unknown>[]Parameters
extensions:readonlyParsedExtension[]— Extension list to search.decoders:readonlyExtensionDecoder<unknown>[]— Decoders to apply. Only matching OIDs produce output.
defineExtensionDecoder
Identity helper that narrows the type of a custom ExtensionDecoder literal.
function defineExtensionDecoder<TValue>(
decoder: ExtensionDecoder<TValue>,
): ExtensionDecoder<TValue>Parameters
decoder:ExtensionDecoder<TValue> — Decoder definition to return unchanged.
Returns — The same decoder, properly typed.
defineExtensionDecoderMap
Identity helper that narrows the type of a custom ExtensionDecoderMap literal.
function defineExtensionDecoderMap<TMap extends ExtensionDecoderMap>(
decoderMap: TMap,
): TMapParameters
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.
function findExtension(
extensions: readonly ParsedExtension[],
oid: string,
): ParsedExtension | undefinedParameters
extensions:readonlyParsedExtension[]— Extension list from aParsedCertificateor CSR.oid:string— Dotted-decimal OID to look up.
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.
function getSubjectPublicKey<TMap extends ExtensionDecoderMap>(
parsed: ParsedCertificate<TMap> | ParsedCertificateSigningRequest<TMap>,
algorithm?: PublicKeyImportInput,
): Promise<ImportKeyResult<CryptoKey>>Parameters
parsed:ParsedCertificate<TMap> |ParsedCertificateSigningRequest<TMap>algorithm?:PublicKeyImportInput
See also
getSubjectPublicKeyOrThrowfor 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.
function getSubjectPublicKeyOrThrow<TMap extends ExtensionDecoderMap>(
parsed: ParsedCertificate<TMap> | ParsedCertificateSigningRequest<TMap>,
algorithm?: PublicKeyImportInput,
): Promise<CryptoKey>Parameters
parsed:ParsedCertificate<TMap> |ParsedCertificateSigningRequest<TMap> — Parsed certificate or CSR whose subject public key to import.algorithm?:PublicKeyImportInput— Optional expected algorithm; must match the key contents when given.
Returns — Extractable CryptoKey with verify usage.
Throws
Error— If the SubjectPublicKeyInfo is malformed, encodes an unsupported algorithm, or doesn't matchalgorithm
See also
getSubjectPublicKeyfor the non-throwing variant
Examples
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_certificate—certificatecould not be parsed.unsupported_private_key—privateKeyis not an extractable private key of a supported type (fromderivePublicKey).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.
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 privateCryptoKey.
Returns — A success when the key matches, or a typed failure otherwise.
See also
certificateMatchesPrivateKeyfor the plain-boolean variant
Examples
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.
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.
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
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.
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.
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.
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}.
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.
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.
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.
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.
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.