micro509
Stable root import for micro509.
Re-exports the common certificate, parsing, verification, revocation, key, and PKCS workflows from one package entrypoint.
Reach for this module when you want the default workflow-first package surface. Use domain entrypoints such as micro509/x509, micro509/verify, and micro509/revocation when you need exhaustive advanced types.
The root export is organized around common PKI flows:
- create certificates, CSRs, CRLs, OCSP responses, PKCS#7, and PFX artifacts
- parse DER or PEM inputs into typed certificate and request shapes
- verify certificate chains, service identities, CRLs, OCSP, and signed data
- import, export, generate, and encrypt key material with WebCrypto-safe algorithms
- work with the common extension inputs, revocation evidence, and validation results
Advanced PKCS#12 MAC plumbing, signature profile tuning, and other domain-specific helper types stay in their owner domains instead of being headlined here.
Examples
import {
createSelfSignedCertificate,
parseCertificatePem,
unwrap,
verifyCertificateChain,
} from 'micro509';
const { certificate } = await createSelfSignedCertificate({
subject: { commonName: 'example.com' },
algorithm: { kind: 'ecdsa', curve: 'P-256' },
});
const parsed = unwrap(parseCertificatePem(certificate.pem));
// parsed.subject.values.commonName === 'example.com'
const result = await verifyCertificateChain({
leaf: certificate.pem,
roots: [certificate.pem],
allowSelfSignedLeaf: true,
});
// result.ok === trueimport {
generateKeyPair,
parseCertificateSigningRequestPem,
createCertificateSigningRequest,
unwrap,
} from 'micro509';
const keyPair = await generateKeyPair({ kind: 'ecdsa', curve: 'P-256' });
const csr = await createCertificateSigningRequest({
subject: { commonName: 'example.com' },
publicKey: keyPair.publicKey,
signerPrivateKey: keyPair.privateKey,
});
const parsed = unwrap(parseCertificateSigningRequestPem(csr.pem));
// parsed.subject.values.commonName === 'example.com'DecryptRsaOaepErrorCode
Machine-readable failure reason for decryptRsaOaep.
'invalid_key' when the key is not an RSA-OAEP private key with decrypt usage; 'decryption_failed' for every ciphertext-level failure (wrong key, wrong label, tampered or truncated ciphertext) — OAEP deliberately does not reveal which.
type DecryptRsaOaepErrorCode = invalid_key | decryption_failedDecryptRsaOaepFailure
Structured failure payload for decryptRsaOaep.
interface DecryptRsaOaepFailure extends Micro509Error<DecryptRsaOaepErrorCode> {
readonly ok: false;
}Properties
readonlyok:false— Alwaysfalsefor failures.
DecryptRsaOaepResult
Success-or-failure result returned by decryptRsaOaep.
type DecryptRsaOaepResult = {
readonly ok: true;
readonly value: Uint8Array
} | ErrorResult<DecryptRsaOaepErrorCode, Record<never, never>, DecryptRsaOaepFailure>EcKeyAlgorithmInput
ECDSA variant of KeyAlgorithmInput.
interface EcKeyAlgorithmInput {
readonly kind: ecdsa;
readonly curve?: EcNamedCurve;
}Properties
readonlykind:ecdsa— Discriminant selecting ECDSA key generation.readonlycurve?:EcNamedCurve— NIST curve. Defaults to'P-256'.
EcNamedCurve
NIST elliptic curve for ECDSA keys.
type EcNamedCurve = P-256 | P-384 | P-521Ed25519KeyAlgorithmInput
Ed25519 variant of KeyAlgorithmInput.
interface Ed25519KeyAlgorithmInput {
readonly kind: ed25519;
}Properties
readonlykind:ed25519— Discriminant selecting Ed25519 key generation.
EncryptedPkcs8Options
PBES2 encryption options for the encrypted PKCS#8 export/import functions.
interface EncryptedPkcs8Options {
readonly password: string;
readonly iterations?: number;
readonly salt?: Uint8Array;
readonly iv?: Uint8Array;
readonly cipher?: AES-128-CBC | AES-192-CBC | AES-256-CBC;
readonly prf?: HMAC-SHA-1 | HMAC-SHA-256;
}Properties
readonlypassword:string— Password fed to PBKDF2 for key derivation.readonlyiterations?:number— PBKDF2 iteration count. Default:100_000.readonlysalt?:Uint8Array— PBKDF2 salt. Default: 16 cryptographically random bytes.readonlyiv?:Uint8Array— AES-CBC initialization vector. Default: 16 cryptographically random bytes.readonlycipher?:AES-128-CBC|AES-192-CBC|AES-256-CBC— AES-CBC cipher. Default:'AES-256-CBC'.readonlyprf?:HMAC-SHA-1|HMAC-SHA-256— PBKDF2 pseudo-random function. Default:'HMAC-SHA-256'.
EncryptRsaOaepErrorCode
Machine-readable failure reason for encryptRsaOaep.
'invalid_key' when the key is not an RSA-OAEP public key with encrypt usage; 'message_too_long' when the plaintext exceeds the OAEP capacity of the key (modulus bytes − 2 × hash bytes − 2).
type EncryptRsaOaepErrorCode = invalid_key | message_too_longEncryptRsaOaepFailure
Structured failure payload for encryptRsaOaep.
interface EncryptRsaOaepFailure extends Micro509Error<EncryptRsaOaepErrorCode> {
readonly ok: false;
}Properties
readonlyok:false— Alwaysfalsefor failures.
EncryptRsaOaepResult
Success-or-failure result returned by encryptRsaOaep.
type EncryptRsaOaepResult = {
readonly ok: true;
readonly value: Uint8Array
} | ErrorResult<EncryptRsaOaepErrorCode, Record<never, never>, EncryptRsaOaepFailure>ImportEcKeyInput
ECDSA variant of PublicKeyImportInput / PrivateKeyImportInput.
interface ImportEcKeyInput {
readonly kind: ecdsa;
readonly curve: EcNamedCurve;
}Properties
readonlykind:ecdsa— Discriminant selecting ECDSA import.readonlycurve:EcNamedCurve— NIST curve the key belongs to. Required for EC import.
ImportEd25519KeyInput
Ed25519 variant of PublicKeyImportInput / PrivateKeyImportInput.
interface ImportEd25519KeyInput {
readonly kind: ed25519;
}Properties
readonlykind:ed25519— Discriminant selecting Ed25519 import.
ImportEncryptedKeyErrorCode
Machine-readable failure reason for the importEncrypted* key functions.
Distinguishes a wrong decryption password ('invalid_password') from structurally invalid input or algorithm mismatches ('malformed').
type ImportEncryptedKeyErrorCode = malformed | invalid_passwordImportEncryptedKeyFailure
Structured failure payload for encrypted key import.
interface ImportEncryptedKeyFailure extends Micro509Error<ImportEncryptedKeyErrorCode> {
readonly ok: false;
}Properties
readonlyok:false— Alwaysfalsefor failures.
ImportEncryptedKeyResult
Success-or-failure result returned by the public importEncrypted* key functions.
On failure, code is 'invalid_password' when decryption failed (wrong password or corrupted ciphertext) and 'malformed' for everything else.
type ImportEncryptedKeyResult<T> = {
readonly ok: true;
readonly value: T
} | ErrorResult<ImportEncryptedKeyErrorCode, Record<never, never>, ImportEncryptedKeyFailure>ImportKeyErrorCode
Machine-readable failure reason for the import* key functions.
type ImportKeyErrorCode = malformedImportKeyFailure
Structured failure payload for key import.
interface ImportKeyFailure extends Micro509Error<ImportKeyErrorCode> {
readonly ok: false;
}Properties
readonlyok:false— Alwaysfalsefor failures.
ImportKeyResult
Success-or-failure result returned by the public import* key functions.
On failure, code is always 'malformed': structurally invalid input, algorithm mismatches, and wrong-password decryption failures all surface the same way (see the throwing *OrThrow variants for raw error messages).
type ImportKeyResult<T> = {
readonly ok: true;
readonly value: T
} | ErrorResult<ImportKeyErrorCode, Record<never, never>, ImportKeyFailure>ImportRsaKeyInput
RSA variant of PublicKeyImportInput / PrivateKeyImportInput.
interface ImportRsaKeyInput {
readonly kind: rsa;
readonly hash?: RsaHash;
readonly scheme?: RsaScheme;
}Properties
readonlykind:rsa— Discriminant selecting RSA import.readonlyhash?:RsaHash— Hash algorithm. Defaults to'SHA-256'.readonlyscheme?:RsaScheme— Padding scheme. Defaults to'pkcs1-v1_5'. Pass'oaep'to import an RSA-OAEP encryption key (encrypt/decryptusage instead ofverify/sign).
KeyAlgorithmInput
Input for generateKeyPair. Selects algorithm family and parameters.
type KeyAlgorithmInput = RsaKeyAlgorithmInput | EcKeyAlgorithmInput | Ed25519KeyAlgorithmInputKeyPairMaterial
Key pair with convenience export helpers. Returned by generateKeyPair.
interface KeyPairMaterial {
readonly publicKey: CryptoKey;
readonly privateKey: CryptoKey;
exportSpkiDer(): Promise<Uint8Array>;
exportSpkiPem(): Promise<string>;
exportPkcs8Der(): Promise<Uint8Array>;
exportPkcs8Pem(): Promise<string>;
exportPublicJwk(): Promise<JsonWebKey>;
exportPrivateJwk(): Promise<JsonWebKey>;
}Properties
readonlypublicKey:CryptoKey— The WebCrypto public key (extractable,verifyusage;encryptfor RSA-OAEP).readonlyprivateKey:CryptoKey— The WebCrypto private key (extractable,signusage;decryptfor RSA-OAEP).
LegacyPemEncryptionOptions
Options for OpenSSL-style Proc-Type: 4,ENCRYPTED PEM encryption (PKCS#1/SEC1).
interface LegacyPemEncryptionOptions {
readonly password: string;
readonly iv?: Uint8Array;
readonly cipher?: AES-128-CBC | AES-192-CBC | AES-256-CBC;
}Properties
readonlypassword:string— Passphrase used to derive the encryption key.readonlyiv?:Uint8Array— 16-byte initialization vector. Random when omitted.readonlycipher?:AES-128-CBC|AES-192-CBC|AES-256-CBC— AES-CBC cipher. Defaults to'AES-256-CBC'.
PrivateKeyImportInput
Algorithm descriptor for private key import functions. Same shape as PublicKeyImportInput.
type PrivateKeyImportInput = PublicKeyImportInputPublicKeyImportInput
Algorithm descriptor for public key import functions.
type PublicKeyImportInput = ImportRsaKeyInput | ImportEcKeyInput | ImportEd25519KeyInputRsaHash
Hash algorithm paired with an RSA key.
type RsaHash = SHA-256 | SHA-384 | SHA-512RsaKeyAlgorithmInput
RSA variant of KeyAlgorithmInput.
interface RsaKeyAlgorithmInput {
readonly kind: rsa;
readonly modulusLength?: 2048 | 3072 | 4096;
readonly hash?: RsaHash;
readonly scheme?: RsaScheme;
}Properties
readonlykind:rsa— Discriminant selecting RSA key generation.readonlymodulusLength?:2048|3072|4096— RSA modulus size in bits. Defaults to2048.readonlyhash?:RsaHash— Hash algorithm for the key. Defaults to'SHA-256'.readonlyscheme?:RsaScheme— Padding scheme. Defaults to'pkcs1-v1_5'. Pass'oaep'to generate an RSA-OAEP encryption pair (encrypt/decryptusages instead ofsign/verify).
RsaOaepOptions
Options shared by encryptRsaOaep and decryptRsaOaep.
interface RsaOaepOptions {
readonly label?: Uint8Array;
}Properties
readonlylabel?:Uint8Array— Optional OAEP label bound to the ciphertext. Not encrypted, but decryption fails unless the exact same label is presented. Default: empty.
RsaScheme
RSA padding scheme: a signature scheme, or 'oaep' for RSA-OAEP encryption keys (usable with encryptRsaOaep / decryptRsaOaep).
type RsaScheme = RsaSignatureScheme | oaepRsaSignatureScheme
RSA signature padding scheme.
type RsaSignatureScheme = pkcs1-v1_5 | pssdecryptRsaOaep
Decrypt an RSA-OAEP ciphertext with the matching private key.
function decryptRsaOaep(
privateKey: CryptoKey,
ciphertext: Uint8Array,
options: RsaOaepOptions,
): Promise<DecryptRsaOaepResult>Parameters
privateKey:CryptoKeyciphertext:Uint8Arrayoptions:RsaOaepOptions
See also
decryptRsaOaepOrThrowfor the throwing variant
Examples
const decrypted = await decryptRsaOaep(keys.privateKey, ciphertext);
if (!decrypted.ok) {
// decrypted.code: 'invalid_key' | 'decryption_failed'
throw new Error(decrypted.message);
}
const plaintext = decrypted.value;decryptRsaOaepOrThrow
Decrypt an RSA-OAEP ciphertext with the matching private key.
The key must have been generated or imported with { kind: 'rsa', scheme: 'oaep' }, and options.label must repeat the label used at encryption time (if any).
function decryptRsaOaepOrThrow(
privateKey: CryptoKey,
ciphertext: Uint8Array,
options: RsaOaepOptions,
): Promise<Uint8Array>Parameters
privateKey:CryptoKey— RSA-OAEP privateCryptoKeywithdecryptusageciphertext:Uint8Array— Ciphertext produced byencryptRsaOaep(or any RSA-OAEP encryptor)options:RsaOaepOptions— OAEP label matching the one bound at encryption
Throws
Error— If the key is not an RSA-OAEP private decryption key, or decryption fails — wrong key, wrong label, or corrupted ciphertext (OAEP deliberately does not reveal which)
See also
encryptRsaOaepOrThrowfor the inverse operationdecryptRsaOaepfor the Result-returning variant
Examples
const plaintext = await decryptRsaOaepOrThrow(keys.privateKey, ciphertext);derivePublicKey
Derive the matching public key from an imported (or generated) private key.
The import* functions that read a PKCS#8 / PKCS#1 / SEC 1 / JWK private key return a bare CryptoKey with only sign (or, for RSA-OAEP, decrypt) usage — there is no accompanying public handle. This bridges that gap: it exports the private key's JWK, strips the private components, and re-imports the public half with verify (RSA-OAEP: encrypt) usage, so callers can go straight to exportSpkiDer / exportSpkiPem (e.g. to rebuild a self-signed cert or distribute the public key when only the private key is on disk).
Supports RSA (n/e), ECDSA (x/y), and Ed25519 (x). The derived key inherits the private key's algorithm parameters (hash, curve).
function derivePublicKey(
privateKey: CryptoKey,
): Promise<CryptoKey>Parameters
privateKey:CryptoKey— An extractable privateCryptoKey
Returns — Extractable public CryptoKey with verify (RSA-OAEP: encrypt) usage
Throws
Error— If the key is not a private key, is non-extractable, or uses an unsupported key type
See also
exportSpkiDerfor exporting the derived key
Examples
const privateKey = await importPkcs8PemOrThrow(pem, { kind: 'ecdsa', curve: 'P-256' });
const publicKey = await derivePublicKey(privateKey);
const spkiPem = await exportSpkiPem(publicKey);encryptRsaOaep
Encrypt a small message with an RSA-OAEP public key.
function encryptRsaOaep(
publicKey: CryptoKey,
plaintext: Uint8Array,
options: RsaOaepOptions,
): Promise<EncryptRsaOaepResult>Parameters
publicKey:CryptoKeyplaintext:Uint8Arrayoptions:RsaOaepOptions
See also
encryptRsaOaepOrThrowfor the throwing variant
Examples
const keys = await generateKeyPair({ kind: 'rsa', scheme: 'oaep' });
const encrypted = await encryptRsaOaep(keys.publicKey, plaintext);
if (!encrypted.ok) {
// encrypted.code: 'invalid_key' | 'message_too_long'
throw new Error(encrypted.message);
}
const ciphertext = encrypted.value;encryptRsaOaepOrThrow
Encrypt a small message with an RSA-OAEP public key.
The key must have been generated or imported with { kind: 'rsa', scheme: 'oaep' }. RSA-OAEP encrypts at most modulus bytes − 2 × hash bytes − 2 per call (190 bytes for a 2048-bit key with SHA-256) — encrypt a symmetric key, not bulk data.
function encryptRsaOaepOrThrow(
publicKey: CryptoKey,
plaintext: Uint8Array,
options: RsaOaepOptions,
): Promise<Uint8Array>Parameters
publicKey:CryptoKey— RSA-OAEP publicCryptoKeywithencryptusageplaintext:Uint8Array— Message bytes, at most the OAEP capacity of the keyoptions:RsaOaepOptions— Optional OAEP label bound to the ciphertext
Throws
Error— If the key is not an RSA-OAEP public encryption key, or the plaintext exceeds the key's OAEP capacity
See also
decryptRsaOaepOrThrowfor the inverse operationencryptRsaOaepfor the Result-returning variant
Examples
const keys = await generateKeyPair({ kind: 'rsa', scheme: 'oaep' });
const ciphertext = await encryptRsaOaepOrThrow(
keys.publicKey,
new TextEncoder().encode('session key'),
);exportBinaryBase64
Export a key as raw base64 (no PEM headers).
Returns SPKI-encoded base64 for public keys, PKCS#8-encoded base64 for private keys. Useful for compact storage or transmission where PEM overhead is undesirable.
function exportBinaryBase64(
key: CryptoKey,
): Promise<string>Parameters
key:CryptoKey
Throws
Error— If the key is a symmetric/secret key
See also
importSpkiBase64for public key importimportPkcs8Base64for private key import
exportEncryptedPkcs1Pem
Export an RSA private key as legacy Proc-Type: 4,ENCRYPTED PEM (PKCS#1).
Uses OpenSSL's traditional PEM encryption with MD5-based key derivation. For modern encryption, prefer exportEncryptedPkcs8Pem.
function exportEncryptedPkcs1Pem(
privateKey: CryptoKey,
options: LegacyPemEncryptionOptions,
): Promise<string>Parameters
privateKey:CryptoKeyoptions:LegacyPemEncryptionOptions
Throws
Error— If the key is not an RSA key
See also
importEncryptedPkcs1Pemfor the inverse operation
exportEncryptedPkcs8Der
Export a private key as DER-encoded PBES2-encrypted PKCS#8 EncryptedPrivateKeyInfo.
Uses PBES2 (PKCS#5 v2.1) with AES-CBC and PBKDF2. Compatible with OpenSSL.
function exportEncryptedPkcs8Der(
privateKey: CryptoKey,
options: EncryptedPkcs8Options,
): Promise<Uint8Array>Parameters
privateKey:CryptoKey— The private key to exportoptions:EncryptedPkcs8Options— Encryption options including password and optional algorithm settings
See also
importEncryptedPkcs8Derfor the inverse operationexportEncryptedPkcs8Pemfor PEM output
exportEncryptedPkcs8Pem
Export a private key as PEM-encoded PBES2-encrypted PKCS#8 EncryptedPrivateKeyInfo.
function exportEncryptedPkcs8Pem(
privateKey: CryptoKey,
options: EncryptedPkcs8Options,
): Promise<string>Parameters
privateKey:CryptoKeyoptions:EncryptedPkcs8Options
See also
importEncryptedPkcs8Pemfor the inverse operation
Examples
const keys = await generateKeyPair();
const pem = await exportEncryptedPkcs8Pem(keys.privateKey, { password: 'secret' });
// -----BEGIN ENCRYPTED PRIVATE KEY-----
// MIHsMFcGCSqGSIb3DQEFDTBKMCkGCSqGSIb3DQEFDDAc...
// -----END ENCRYPTED PRIVATE KEY-----exportEncryptedSec1Pem
Export an EC private key as legacy Proc-Type: 4,ENCRYPTED PEM (SEC 1).
Uses OpenSSL's traditional PEM encryption with MD5-based key derivation. For modern encryption, prefer exportEncryptedPkcs8Pem.
function exportEncryptedSec1Pem(
privateKey: CryptoKey,
options: LegacyPemEncryptionOptions,
): Promise<string>Parameters
privateKey:CryptoKeyoptions:LegacyPemEncryptionOptions
Throws
Error— If the key is not an EC key
See also
importEncryptedSec1Pemfor the inverse operation
exportPkcs1Der
Export an RSA private key as DER-encoded PKCS#1 RSAPrivateKey.
PKCS#1 is the legacy RSA-only format. For algorithm-agnostic export, use exportPkcs8Der.
function exportPkcs1Der(
privateKey: CryptoKey,
): Promise<Uint8Array>Parameters
privateKey:CryptoKey
Throws
Error— If the key is not an RSA key
See also
importPkcs1Derfor the inverse operationexportPkcs1Pemfor PEM output
exportPkcs1Pem
Export an RSA private key as PEM-encoded PKCS#1 RSAPrivateKey.
function exportPkcs1Pem(
privateKey: CryptoKey,
): Promise<string>Parameters
privateKey:CryptoKey
Throws
Error— If the key is not an RSA key
See also
importPkcs1Pemfor the inverse operationexportEncryptedPkcs1Pemfor password-protected export
exportPkcs8Der
Export a private key as DER-encoded PKCS#8 PrivateKeyInfo.
function exportPkcs8Der(
privateKey: CryptoKey,
): Promise<Uint8Array>Parameters
privateKey:CryptoKey
See also
importPkcs8Derfor the inverse operationexportPkcs8Pemfor PEM outputexportEncryptedPkcs8Derfor password-protected export
exportPkcs8Pem
Export a private key as PEM-encoded PKCS#8 PrivateKeyInfo.
function exportPkcs8Pem(
privateKey: CryptoKey,
): Promise<string>Parameters
privateKey:CryptoKey
See also
importPkcs8Pemfor the inverse operationexportEncryptedPkcs8Pemfor password-protected export
Examples
const keys = await generateKeyPair();
const pem = await exportPkcs8Pem(keys.privateKey);
// -----BEGIN PRIVATE KEY-----
// MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEH...
// -----END PRIVATE KEY-----exportPrivateJwk
Export a private key as a JSON Web Key.
function exportPrivateJwk(
privateKey: CryptoKey,
): Promise<JsonWebKey>Parameters
privateKey:CryptoKey
See also
importPrivateJwkfor the inverse operationexportPublicJwkfor public key export
exportPublicJwk
Export a public key as a JSON Web Key.
function exportPublicJwk(
publicKey: CryptoKey,
): Promise<JsonWebKey>Parameters
publicKey:CryptoKey
Examples
const keys = await generateKeyPair({ kind: 'ecdsa', curve: 'P-256' });
const jwk = await exportPublicJwk(keys.publicKey);exportSec1Der
Export an EC private key as DER-encoded SEC 1 ECPrivateKey.
SEC 1 is the legacy EC-only format. For algorithm-agnostic export, use exportPkcs8Der.
The output always carries the RFC 5915 parameters [0] named curve (matching OpenSSL), so it re-imports via importSec1Der without an explicit curve.
function exportSec1Der(
privateKey: CryptoKey,
): Promise<Uint8Array>Parameters
privateKey:CryptoKey
Throws
Error— If the key is not an EC key
See also
importSec1Derfor the inverse operationexportSec1Pemfor PEM output
exportSec1Pem
Export an EC private key as PEM-encoded SEC 1 ECPrivateKey.
function exportSec1Pem(
privateKey: CryptoKey,
): Promise<string>Parameters
privateKey:CryptoKey
Throws
Error— If the key is not an EC key
See also
importSec1Pemfor the inverse operationexportEncryptedSec1Pemfor password-protected export
exportSpkiDer
Export a public key as DER-encoded SubjectPublicKeyInfo.
function exportSpkiDer(
publicKey: CryptoKey,
): Promise<Uint8Array>Parameters
publicKey:CryptoKey
See also
importSpkiDerfor the inverse operationexportSpkiPemfor PEM output
exportSpkiPem
Export a public key as PEM-encoded SubjectPublicKeyInfo.
function exportSpkiPem(
publicKey: CryptoKey,
): Promise<string>Parameters
publicKey:CryptoKey
Examples
const keys = await generateKeyPair();
const pem = await exportSpkiPem(keys.publicKey);generateKeyPair
Generate an asymmetric key pair for signing and verification, or — with { kind: 'rsa', scheme: 'oaep' } — for RSA-OAEP encryption and decryption.
function generateKeyPair(
algorithm: KeyAlgorithmInput,
): Promise<KeyPairMaterial>Parameters
algorithm:KeyAlgorithmInput
Examples
const ecKeys = await generateKeyPair({ kind: 'ecdsa', curve: 'P-384' });
const rsaKeys = await generateKeyPair({ kind: 'rsa', modulusLength: 4096 });
const edKeys = await generateKeyPair({ kind: 'ed25519' });
const oaepKeys = await generateKeyPair({ kind: 'rsa', scheme: 'oaep' });
// Default: ECDSA P-256
const keys = await generateKeyPair();
const pem = await keys.exportPkcs8Pem();importEncryptedPkcs1Pem
Import an RSA private key from legacy Proc-Type: 4,ENCRYPTED PEM (PKCS#1).
function importEncryptedPkcs1Pem(
pem: string,
password: string,
algorithm: ImportRsaKeyInput,
): Promise<ImportEncryptedKeyResult<CryptoKey>>Parameters
pem:stringpassword:stringalgorithm:ImportRsaKeyInput
See also
importEncryptedPkcs1PemOrThrowfor the throwing variant
importEncryptedPkcs1PemOrThrow
Import an RSA private key from legacy Proc-Type: 4,ENCRYPTED PEM (PKCS#1).
Decrypts OpenSSL's traditional PEM encryption format.
function importEncryptedPkcs1PemOrThrow(
pem: string,
password: string,
algorithm: ImportRsaKeyInput,
): Promise<CryptoKey>Parameters
pem:stringpassword:stringalgorithm:ImportRsaKeyInput
See also
exportEncryptedPkcs1Pemfor the inverse operationimportEncryptedPkcs8Pemfor modern PBES2 encryption
importEncryptedPkcs8Der
Import a private key from DER-encoded PBES2-encrypted PKCS#8 EncryptedPrivateKeyInfo.
function importEncryptedPkcs8Der(
der: Uint8Array,
password: string,
algorithm?: PrivateKeyImportInput,
): Promise<ImportEncryptedKeyResult<CryptoKey>>Parameters
der:Uint8Arraypassword:stringalgorithm?:PrivateKeyImportInput
See also
importEncryptedPkcs8DerOrThrowfor the throwing variant
importEncryptedPkcs8DerOrThrow
Import a private key from DER-encoded PBES2-encrypted PKCS#8 EncryptedPrivateKeyInfo.
Decrypts the PBES2 envelope using the provided password, then imports the key.
When algorithm is omitted, it is inferred from the decrypted key's own privateKeyAlgorithm (see importPkcs8DerOrThrow).
function importEncryptedPkcs8DerOrThrow(
der: Uint8Array,
password: string,
algorithm?: PrivateKeyImportInput,
): Promise<CryptoKey>Parameters
der:Uint8Array— DER-encoded EncryptedPrivateKeyInfo bytespassword:string— Decryption passwordalgorithm?:PrivateKeyImportInput— Optional expected algorithm; must match decrypted key when given
Throws
Error— If DER is malformed, password is wrong, or algorithm doesn't match
See also
exportEncryptedPkcs8Derfor the inverse operation
importEncryptedPkcs8Pem
Import a private key from PEM-encoded PBES2-encrypted PKCS#8 EncryptedPrivateKeyInfo.
function importEncryptedPkcs8Pem(
pem: string,
password: string,
algorithm?: PrivateKeyImportInput,
): Promise<ImportEncryptedKeyResult<CryptoKey>>Parameters
pem:stringpassword:stringalgorithm?:PrivateKeyImportInput
See also
importEncryptedPkcs8PemOrThrowfor the throwing variant
importEncryptedPkcs8PemOrThrow
Import a private key from PEM-encoded PBES2-encrypted PKCS#8 EncryptedPrivateKeyInfo.
When algorithm is omitted, it is inferred from the decrypted key's own privateKeyAlgorithm (see importPkcs8DerOrThrow).
function importEncryptedPkcs8PemOrThrow(
pem: string,
password: string,
algorithm?: PrivateKeyImportInput,
): Promise<CryptoKey>Parameters
pem:stringpassword:stringalgorithm?:PrivateKeyImportInput
Examples
const key = await importEncryptedPkcs8PemOrThrow(pem, 'secret', { kind: 'rsa' });
const inferred = await importEncryptedPkcs8PemOrThrow(pem, 'secret');importEncryptedSec1Pem
Import an EC private key from legacy Proc-Type: 4,ENCRYPTED PEM (SEC 1).
function importEncryptedSec1Pem(
pem: string,
password: string,
algorithm?: ImportEcKeyInput,
): Promise<ImportEncryptedKeyResult<CryptoKey>>Parameters
pem:stringpassword:stringalgorithm?:ImportEcKeyInput
See also
importEncryptedSec1PemOrThrowfor the throwing variant
importEncryptedSec1PemOrThrow
Import an EC private key from legacy Proc-Type: 4,ENCRYPTED PEM (SEC 1).
Decrypts OpenSSL's traditional PEM encryption format.
function importEncryptedSec1PemOrThrow(
pem: string,
password: string,
algorithm?: ImportEcKeyInput,
): Promise<CryptoKey>Parameters
pem:stringpassword:stringalgorithm?:ImportEcKeyInput
See also
exportEncryptedSec1Pemfor the inverse operationimportEncryptedPkcs8Pemfor modern PBES2 encryption
importPkcs1Der
Import an RSA private key from DER-encoded PKCS#1 RSAPrivateKey.
function importPkcs1Der(
der: Uint8Array,
algorithm: ImportRsaKeyInput,
): Promise<ImportKeyResult<CryptoKey>>Parameters
der:Uint8Arrayalgorithm:ImportRsaKeyInput
See also
importPkcs1DerOrThrowfor the throwing variant
importPkcs1DerOrThrow
Import an RSA private key from DER-encoded PKCS#1 RSAPrivateKey.
PKCS#1 is the legacy RSA-only format. Internally converts to PKCS#8 for import.
function importPkcs1DerOrThrow(
der: Uint8Array,
algorithm: ImportRsaKeyInput,
): Promise<CryptoKey>Parameters
der:Uint8Arrayalgorithm:ImportRsaKeyInput
See also
exportPkcs1Derfor the inverse operationimportPkcs1Pemfor PEM input
importPkcs1Pem
Import an RSA private key from PEM-encoded PKCS#1 RSAPrivateKey.
function importPkcs1Pem(
pem: string,
algorithm: ImportRsaKeyInput,
): Promise<ImportKeyResult<CryptoKey>>Parameters
pem:stringalgorithm:ImportRsaKeyInput
See also
importPkcs1PemOrThrowfor the throwing variant
importPkcs1PemOrThrow
Import an RSA private key from PEM-encoded PKCS#1 RSAPrivateKey.
Expects the -----BEGIN RSA PRIVATE KEY----- PEM label.
function importPkcs1PemOrThrow(
pem: string,
algorithm: ImportRsaKeyInput,
): Promise<CryptoKey>Parameters
pem:stringalgorithm:ImportRsaKeyInput
See also
exportPkcs1Pemfor the inverse operationimportEncryptedPkcs1Pemfor encrypted PEM
importPkcs8Base64
Import a private key from base64-encoded PKCS#8 PrivateKeyInfo (no PEM headers).
function importPkcs8Base64(
base64: string,
algorithm?: PrivateKeyImportInput,
): Promise<ImportKeyResult<CryptoKey>>Parameters
base64:stringalgorithm?:PrivateKeyImportInput
See also
importPkcs8Base64OrThrowfor the throwing variant
importPkcs8Base64OrThrow
Import a private key from base64-encoded PKCS#8 PrivateKeyInfo (no PEM headers).
function importPkcs8Base64OrThrow(
base64: string,
algorithm?: PrivateKeyImportInput,
): Promise<CryptoKey>Parameters
base64:stringalgorithm?:PrivateKeyImportInput
See also
exportBinaryBase64for the inverse operationimportPkcs8Pemfor PEM input with headers
importPkcs8Der
Import a private key from DER-encoded PKCS#8 PrivateKeyInfo.
function importPkcs8Der(
der: Uint8Array,
algorithm?: PrivateKeyImportInput,
): Promise<ImportKeyResult<CryptoKey>>Parameters
der:Uint8Arrayalgorithm?:PrivateKeyImportInput
See also
importPkcs8DerOrThrowfor the throwing variant
importPkcs8DerOrThrow
Import a private key from DER-encoded PKCS#8 PrivateKeyInfo.
When algorithm is omitted, the algorithm (and, for EC keys, the curve) is inferred from the PrivateKeyInfo's own privateKeyAlgorithm — useful for keys whose type isn't known ahead of time. Pass algorithm to additionally assert that the DER matches an expected algorithm.
function importPkcs8DerOrThrow(
der: Uint8Array,
algorithm?: PrivateKeyImportInput,
): Promise<CryptoKey>Parameters
der:Uint8Array— DER-encoded PKCS#8 PrivateKeyInfo bytesalgorithm?:PrivateKeyImportInput— Optional expected algorithm; must match key contents when given
Returns — Extractable CryptoKey with sign usage
Throws
Error— If DER is malformed, encodes an unsupported algorithm, or doesn't matchalgorithm
See also
exportPkcs8Derfor the inverse operationimportPkcs8Pemfor PEM inputimportEncryptedPkcs8Derfor encrypted PKCS#8
importPkcs8Pem
Import a private key from PEM-encoded PKCS#8 PrivateKeyInfo.
function importPkcs8Pem(
pem: string,
algorithm?: PrivateKeyImportInput,
): Promise<ImportKeyResult<CryptoKey>>Parameters
pem:stringalgorithm?:PrivateKeyImportInput
See also
importPkcs8PemOrThrowfor the throwing variant
importPkcs8PemOrThrow
Import a private key from PEM-encoded PKCS#8 PrivateKeyInfo.
When algorithm is omitted, it is inferred from the key's own privateKeyAlgorithm (see importPkcs8DerOrThrow).
function importPkcs8PemOrThrow(
pem: string,
algorithm?: PrivateKeyImportInput,
): Promise<CryptoKey>Parameters
pem:stringalgorithm?:PrivateKeyImportInput
Examples
const key = await importPkcs8PemOrThrow(pemString, { kind: 'ecdsa', curve: 'P-256' });
const inferred = await importPkcs8PemOrThrow(pemString);importPrivateJwk
Import a private signing key from a JSON Web Key.
function importPrivateJwk(
jwk: JsonWebKey,
algorithm?: PrivateKeyImportInput,
): Promise<ImportKeyResult<CryptoKey>>Parameters
jwk:JsonWebKeyalgorithm?:PrivateKeyImportInput
See also
importPrivateJwkOrThrowfor the throwing variant
importPrivateJwkOrThrow
Import a private signing key from a JSON Web Key.
When algorithm is omitted, it is inferred from the JWK's own kty, crv, and alg members (see importPublicJwkOrThrow).
function importPrivateJwkOrThrow(
jwk: JsonWebKey,
algorithm?: PrivateKeyImportInput,
): Promise<CryptoKey>Parameters
jwk:JsonWebKey— JSON Web Key object with private key componentsalgorithm?:PrivateKeyImportInput— Optional expected algorithm; must match JWK'sktyandcrvwhen given
Returns — Extractable CryptoKey with sign usage
Throws
Error— If JWK is malformed, lacks private key material, encodes an unsupported algorithm, or doesn't matchalgorithm
See also
exportPrivateJwkfor the inverse operation
Examples
const jwk = { kty: 'EC', crv: 'P-256', x: '...', y: '...', d: '...' };
const key = await importPrivateJwkOrThrow(jwk, { kind: 'ecdsa', curve: 'P-256' });
const inferred = await importPrivateJwkOrThrow(jwk);importPublicJwk
Import a public verification key from a JSON Web Key.
function importPublicJwk(
jwk: JsonWebKey,
algorithm?: PublicKeyImportInput,
): Promise<ImportKeyResult<CryptoKey>>Parameters
jwk:JsonWebKeyalgorithm?:PublicKeyImportInput
See also
importPublicJwkOrThrowfor the throwing variant
importPublicJwkOrThrow
Import a public verification key from a JSON Web Key.
When algorithm is omitted, it is inferred from the JWK's own kty, crv, and alg members (e.g. PS256 → RSA-PSS/SHA-256, RSA-OAEP-256 → RSA-OAEP/SHA-256; an RSA JWK without alg defaults to PKCS#1 v1.5 with SHA-256). Pass algorithm to additionally assert an expected algorithm.
function importPublicJwkOrThrow(
jwk: JsonWebKey,
algorithm?: PublicKeyImportInput,
): Promise<CryptoKey>Parameters
jwk:JsonWebKey— JSON Web Key object with public key componentsalgorithm?:PublicKeyImportInput— Optional expected algorithm; must match JWK'sktyandcrvwhen given
Returns — Extractable CryptoKey with verify usage
Throws
Error— If JWK is malformed, encodes an unsupported algorithm, or doesn't matchalgorithm
See also
exportPublicJwkfor the inverse operation
importSec1Der
Import an EC private key from DER-encoded SEC 1 ECPrivateKey.
function importSec1Der(
der: Uint8Array,
algorithm?: ImportEcKeyInput,
): Promise<ImportKeyResult<CryptoKey>>Parameters
der:Uint8Arrayalgorithm?:ImportEcKeyInput
See also
importSec1DerOrThrowfor the throwing variant
importSec1DerOrThrow
Import an EC private key from DER-encoded SEC 1 ECPrivateKey.
SEC 1 is the legacy EC-only format. Internally converts to PKCS#8 for import. When the ECPrivateKey carries the optional RFC 5915 parameters [0] field (OpenSSL always writes it), its named-curve OID must match algorithm.curve; when the field is absent, the caller-supplied curve is trusted.
When algorithm is omitted, the curve is inferred from the embedded parameters [0] field; a key without a supported named curve then fails.
function importSec1DerOrThrow(
der: Uint8Array,
algorithm?: ImportEcKeyInput,
): Promise<CryptoKey>Parameters
der:Uint8Arrayalgorithm?:ImportEcKeyInput
Throws
Error— If DER is not an ECPrivateKey, its embedded curve doesn't matchalgorithm, or no curve is available (neither embedded nor supplied)
See also
exportSec1Derfor the inverse operationimportSec1Pemfor PEM input
importSec1Pem
Import an EC private key from PEM-encoded SEC 1 ECPrivateKey.
function importSec1Pem(
pem: string,
algorithm?: ImportEcKeyInput,
): Promise<ImportKeyResult<CryptoKey>>Parameters
pem:stringalgorithm?:ImportEcKeyInput
See also
importSec1PemOrThrowfor the throwing variant
importSec1PemOrThrow
Import an EC private key from PEM-encoded SEC 1 ECPrivateKey.
Expects the -----BEGIN EC PRIVATE KEY----- PEM label. When algorithm is omitted, the curve is inferred from the embedded parameters [0] field (see importSec1DerOrThrow).
function importSec1PemOrThrow(
pem: string,
algorithm?: ImportEcKeyInput,
): Promise<CryptoKey>Parameters
pem:stringalgorithm?:ImportEcKeyInput
See also
exportSec1Pemfor the inverse operationimportEncryptedSec1Pemfor encrypted PEM
importSpkiBase64
Import a public key from base64-encoded SubjectPublicKeyInfo (no PEM headers).
function importSpkiBase64(
base64: string,
algorithm?: PublicKeyImportInput,
): Promise<ImportKeyResult<CryptoKey>>Parameters
base64:stringalgorithm?:PublicKeyImportInput
See also
importSpkiBase64OrThrowfor the throwing variant
importSpkiBase64OrThrow
Import a public key from base64-encoded SubjectPublicKeyInfo (no PEM headers).
function importSpkiBase64OrThrow(
base64: string,
algorithm?: PublicKeyImportInput,
): Promise<CryptoKey>Parameters
base64:stringalgorithm?:PublicKeyImportInput
See also
exportBinaryBase64for the inverse operationimportSpkiPemfor PEM input with headers
importSpkiDer
Import a public key from DER-encoded SubjectPublicKeyInfo.
function importSpkiDer(
der: Uint8Array,
algorithm?: PublicKeyImportInput,
): Promise<ImportKeyResult<CryptoKey>>Parameters
der:Uint8Arrayalgorithm?:PublicKeyImportInput
See also
importSpkiDerOrThrowfor the throwing variant
importSpkiDerOrThrow
Import a public key from DER-encoded SubjectPublicKeyInfo.
When algorithm is omitted, the algorithm (and, for EC keys, the curve) is inferred from the SPKI's own AlgorithmIdentifier — useful for keys whose type isn't known ahead of time. Pass algorithm to additionally assert that the DER matches an expected algorithm.
function importSpkiDerOrThrow(
der: Uint8Array,
algorithm?: PublicKeyImportInput,
): Promise<CryptoKey>Parameters
der:Uint8Array— DER-encoded SubjectPublicKeyInfo bytesalgorithm?:PublicKeyImportInput— Optional expected algorithm; must match key contents when given
Returns — Extractable CryptoKey with verify usage
Throws
Error— If DER is malformed, encodes an unsupported algorithm, or doesn't matchalgorithm
See also
exportSpkiDerfor the inverse operationimportSpkiPemfor PEM input
importSpkiPem
Import a public key from PEM-encoded SubjectPublicKeyInfo.
function importSpkiPem(
pem: string,
algorithm?: PublicKeyImportInput,
): Promise<ImportKeyResult<CryptoKey>>Parameters
pem:stringalgorithm?:PublicKeyImportInput
See also
importSpkiPemOrThrowfor the throwing variant
importSpkiPemOrThrow
Import a public key from PEM-encoded SubjectPublicKeyInfo.
function importSpkiPemOrThrow(
pem: string,
algorithm?: PublicKeyImportInput,
): Promise<CryptoKey>Parameters
pem:stringalgorithm?:PublicKeyImportInput
See also
exportSpkiPemfor the inverse operation
Examples
const pem = `-----BEGIN PUBLIC KEY-----
MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE...
-----END PUBLIC KEY-----`;
const key = await importSpkiPemOrThrow(pem, { kind: 'ecdsa', curve: 'P-256' });CategorizedPemBlocks
PEM blocks grouped by their label into well-known PKI categories. Blocks that don't match any known label land in others.
interface CategorizedPemBlocks {
readonly certificates: readonly PemBlock[];
readonly certificateRequests: readonly PemBlock[];
readonly privateKeys: readonly PemBlock[];
readonly publicKeys: readonly PemBlock[];
readonly others: readonly PemBlock[];
}Properties
readonlycertificates:readonlyPemBlock[]— Blocks with labelCERTIFICATE.readonlycertificateRequests:readonlyPemBlock[]— Blocks with labelCERTIFICATE REQUEST.readonlyprivateKeys:readonlyPemBlock[]— Blocks with labelPRIVATE KEY,RSA PRIVATE KEY, orEC PRIVATE KEY.readonlypublicKeys:readonlyPemBlock[]— Blocks with labelPUBLIC KEY.readonlyothers:readonlyPemBlock[]— Blocks whose label doesn't match any of the above categories.
CategorizePemBlocksResult
Success-or-failure result from categorizePemBlocks.
type CategorizePemBlocksResult = {
readonly ok: true;
readonly value: CategorizedPemBlocks
} | ErrorResult<PemErrorCode, Record<never, never>, PemFailure>PemBlock
A single decoded PEM block with its label, decoded DER bytes, and original PEM text.
interface PemBlock {
readonly label: string;
readonly bytes: Uint8Array;
readonly pem: string;
}Properties
readonlylabel:string— RFC 7468 label between theBEGIN/ENDmarkers (e.g."CERTIFICATE").readonlybytes:Uint8Array— Decoded DER content of this block.readonlypem:string— The original PEM text includingBEGIN/ENDlines.
PemDecodeResult
Success-or-failure result from pemDecode.
type PemDecodeResult = {
readonly ok: true;
readonly value: Uint8Array
} | ErrorResult<PemErrorCode, Record<never, never>, PemFailure>PemErrorCode
Machine-readable failure reason for the PEM decoders.
type PemErrorCode = malformedPemFailure
Structured failure payload for PEM decoding.
interface PemFailure extends Micro509Error<PemErrorCode> {
readonly ok: false;
}Properties
readonlyok:false— Alwaysfalsefor failures.
SplitPemBlocksResult
Success-or-failure result from splitPemBlocks.
type SplitPemBlocksResult = {
readonly ok: true;
readonly value: readonly PemBlock[]
} | ErrorResult<PemErrorCode, Record<never, never>, PemFailure>categorizePemBlocks
Groups PEM blocks by label into well-known PKI categories (certificates, CSRs, private keys, public keys, and everything else). Accepts either raw PEM text or pre-split PemBlock entries.
Returns a typed failure (code: 'malformed') when raw text contains stray or truncated PEM markers. For the throwing form use categorizePemBlocksOrThrow.
function categorizePemBlocks(
input: string | readonly PemBlock[],
): CategorizePemBlocksResultParameters
input:string|readonlyPemBlock[]
categorizePemBlocksOrThrow
Groups PEM blocks by label into well-known PKI categories (certificates, CSRs, private keys, public keys, and everything else). Accepts either raw PEM text or pre-split PemBlock entries.
function categorizePemBlocksOrThrow(
input: string | readonly PemBlock[],
): CategorizedPemBlocksParameters
input:string|readonlyPemBlock[]
pemDecode
Extracts and base64-decodes the DER content from a PEM string.
Returns a typed failure (code: 'malformed') when the BEGIN/END markers don't match label or the body is not valid base64. For the throwing form use pemDecodeOrThrow.
function pemDecode(
label: string,
pem: string,
): PemDecodeResultParameters
label:stringpem:string
pemDecodeOrThrow
Throwing core for pemDecode: extracts and base64-decodes the DER content from a PEM string. Throws if the BEGIN/END markers don't match label.
function pemDecodeOrThrow(
label: string,
pem: string,
): Uint8ArrayParameters
label:string— Expected PEM type label.pem:string— PEM-encoded text (may contain\r).
pemEncode
Wraps DER bytes in a PEM envelope with 64-character base64 lines.
function pemEncode(
label: string,
der: Uint8Array,
): stringParameters
label:string— PEM type label (e.g."CERTIFICATE","PRIVATE KEY").der:Uint8Array— Raw DER-encoded content.
splitPemBlocks
Finds all BEGIN/END-delimited PEM blocks in a string and returns them as parsed PemBlock entries. Handles concatenated PEM files and ignores non-PEM text between blocks.
Returns a typed failure (code: 'malformed') on stray or truncated PEM markers. For the throwing form use splitPemBlocksOrThrow.
function splitPemBlocks(
input: string,
): SplitPemBlocksResultParameters
input:string
splitPemBlocksOrThrow
Finds all BEGIN/END-delimited PEM blocks in a string and returns them as parsed PemBlock entries. Handles concatenated PEM files and ignores non-PEM text between blocks.
function splitPemBlocksOrThrow(
input: string,
): readonly PemBlock[]Parameters
input:string
CreatePfxErrorCode
Caller-correctable failure code from createPfx.
The only parse boundary in creation is the certificate source: it is normalized from untrusted PEM/DER. Private keys are either a WebCrypto CryptoKey (platform errors stay throws) or raw PKCS#8 bytes passed through unvalidated, so there is no distinct invalid_private_key failure to model.
type CreatePfxErrorCode = invalid_certificateCreatePfxFailure
Error payload for a failed PFX creation.
interface CreatePfxFailure extends Micro509Error<CreatePfxErrorCode> {
readonly ok: false;
}Properties
readonlyok:false— Alwaysfalsefor failures.
CreatePfxInput
Input for createPfx.
interface CreatePfxInput {
readonly certificates?: readonly PfxCertificateBagInput[];
readonly privateKeys?: readonly PfxPrivateKeyBagInput[];
readonly encryption?: PfxEncryptionOptions;
readonly mac?: Pkcs12MacOptions;
}Properties
readonlycertificates?:readonlyPfxCertificateBagInput[]— Certificates to include as certBag entries.readonlyprivateKeys?:readonlyPfxPrivateKeyBagInput[]— Private keys to include as keyBag entries.readonlyencryption?:PfxEncryptionOptions— PBES2 encryption settings for the key-bag ContentInfo. Omit for unencrypted.readonlymac?:Pkcs12MacOptions— PKCS#12 MAC integrity settings. Omit to skip MAC generation.
CreatePfxResult
Success-or-failure result from createPfx.
type CreatePfxResult = {
readonly ok: true;
readonly value: PfxMaterial
} | ErrorResult<CreatePfxErrorCode, Record<never, never>, CreatePfxFailure>CreatePkcs7CertBagErrorCode
Caller-correctable failure code from createPkcs7CertBag.
type CreatePkcs7CertBagErrorCode = invalid_certificateCreatePkcs7CertBagFailure
Error payload for a failed PKCS#7 certificate bag creation.
interface CreatePkcs7CertBagFailure extends Micro509Error<CreatePkcs7CertBagErrorCode> {
readonly ok: false;
}Properties
readonlyok:false— Alwaysfalsefor failures.
CreatePkcs7CertBagResult
Success-or-failure result from createPkcs7CertBag.
type CreatePkcs7CertBagResult = {
readonly ok: true;
readonly value: Pkcs7CertBagMaterial
} | ErrorResult<CreatePkcs7CertBagErrorCode, Record<never, never>, CreatePkcs7CertBagFailure>CreatePkcs7SignedDataErrorCode
Caller-correctable failure codes from createPkcs7SignedData.
type CreatePkcs7SignedDataErrorCode = no_signers | invalid_signer_certificate | invalid_certificate | unsupported_signer_keyCreatePkcs7SignedDataFailure
Error payload for a failed PKCS#7 SignedData creation.
interface CreatePkcs7SignedDataFailure extends Micro509Error<CreatePkcs7SignedDataErrorCode> {
readonly ok: false;
}Properties
readonlyok:false— Alwaysfalsefor failures.
CreatePkcs7SignedDataInput
Input for createPkcs7SignedData.
interface CreatePkcs7SignedDataInput {
readonly content: Uint8Array;
readonly signers: readonly Pkcs7Signer[];
readonly additionalCertificates?: readonly Pkcs7CertificateSource[];
readonly encapsulatedContentTypeOid?: string;
readonly detached?: boolean;
}Properties
readonlycontent:Uint8Array— Content to encapsulate and sign (the eContent).readonlysigners:readonlyPkcs7Signer[]— One or more signers. Each produces a SignerInfo with signed attributes.readonlyadditionalCertificates?:readonlyPkcs7CertificateSource[]— Additional certificates to embed (e.g. intermediates). Signer certificates are always embedded; duplicate DER is removed.readonlyencapsulatedContentTypeOid?:string— Encapsulated content type OID.readonlydetached?:boolean— OmiteContentfromencapContentInfo(RFC 5652 Section 5.2 detached form). The signature still coverscontentvia the messageDigest signed attribute, but the bytes are not embedded — the verifier must supply them externally (e.g. git x509 commit signing, S/MIME detached signatures).
CreatePkcs7SignedDataResult
Success-or-failure result from createPkcs7SignedData.
type CreatePkcs7SignedDataResult = {
readonly ok: true;
readonly value: Pkcs7SignedDataMaterial
} | ErrorResult<CreatePkcs7SignedDataErrorCode, Record<never, never>, CreatePkcs7SignedDataFailure>ParsedPfx
Fully decoded PFX container returned by parsePfxDer / parsePfxPem.
interface ParsedPfx {
readonly bags: readonly ParsedPfxBag[];
readonly certificates: readonly ParsedCertificate[];
readonly privateKeys: readonly Uint8Array[];
readonly macData?: ParsedPkcs12MacData;
}Properties
readonlybags:readonlyParsedPfxBag[]— All SafeBags in the PFX, including unknown types.readonlycertificates:readonlyParsedCertificate[]— Convenience: only the parsed certificates extracted from certBag entries.readonlyprivateKeys:readonlyUint8Array``[]— Convenience: raw PKCS#8 DER of each private key extracted from keyBag entries.readonlymacData?:ParsedPkcs12MacData— MAC verification metadata, present when the PFX includes a MacData block.
ParsedPfxAttribute
A single PKCS#12 bag attribute as decoded by parsePfxDer.
interface ParsedPfxAttribute {
readonly oid: string;
readonly valuesHex: readonly string[];
}Properties
readonlyoid:string— Dotted-decimal OID identifying this attribute type.readonlyvaluesHex:readonlystring``[]— Hex-encoded DER of each attribute value.
ParsedPfxBag
Discriminated union of SafeBag types decoded from a PFX container.
Use kind to narrow: 'certificate' | 'privateKey' | 'unknown'.
type ParsedPfxBag = {
readonly kind: certificate;
readonly bagId: string;
readonly attributes: ParsedPfxBagAttributes;
readonly certificate: ParsedCertificate
} | {
readonly kind: privateKey;
readonly bagId: string;
readonly attributes: ParsedPfxBagAttributes;
readonly pkcs8Der: Uint8Array
} | {
readonly kind: unknown;
readonly bagId: string;
readonly attributes: ParsedPfxBagAttributes;
readonly valueDer: Uint8Array
}ParsedPfxBagAttributes
Decoded bag attributes for a single SafeBag inside a PFX.
interface ParsedPfxBagAttributes {
readonly entries: readonly ParsedPfxAttribute[];
readonly friendlyName?: string;
readonly localKeyId?: string;
}Properties
readonlyentries:readonlyParsedPfxAttribute[]— All raw attributes as OID + hex-encoded values.readonlyfriendlyName?:string— Decoded BMPString friendly-name attribute, if present.readonlylocalKeyId?:string— Hex-encoded localKeyId attribute, if present.
ParsedPkcs7SignedData
Decoded PKCS#7 SignedData content, including certificates and signer info.
interface ParsedPkcs7SignedData {
readonly der?: Uint8Array;
readonly contentTypeOid: string;
readonly version: number;
readonly digestAlgorithmOids: readonly string[];
readonly digestAlgorithmNames: readonly string[];
readonly encapsulatedContentTypeOid: string;
readonly encapsulatedContent?: Uint8Array;
readonly certificates: readonly ParsedCertificate[];
readonly signerInfos: readonly ParsedPkcs7SignerInfo[];
}Properties
readonlyder?:Uint8Array— Original DER bytes when this object came fromparsePkcs7SignedDataDeror PEM parsing.readonlycontentTypeOid:string— Outer ContentInfo type OID (alwayspkcs7-signedData).readonlyversion:number— SignedData version number.readonlydigestAlgorithmOids:readonlystring``[]— OIDs of digest algorithms declared indigestAlgorithms.readonlydigestAlgorithmNames:readonlystring``[]— Human-readable digest algorithm names declared indigestAlgorithms.readonlyencapsulatedContentTypeOid:string— OID of the encapsulated content type (e.g.pkcs7-data).readonlyencapsulatedContent?:Uint8Array— Raw encapsulated content bytes. Absent in degenerate (certs-only) bags.readonlycertificates:readonlyParsedCertificate[]— Certificates included in the SignedData certificate set.readonlysignerInfos:readonlyParsedPkcs7SignerInfo[]— Decoded signer info entries. Empty for degenerate cert bags.
ParsedPkcs7SignerInfo
A single SignerInfo decoded from a PKCS#7 SignedData structure.
Discriminated on hasSignedAttrs: when true, signedAttrsDer is always present; when false, it cannot exist.
type ParsedPkcs7SignerInfo = (ParsedPkcs7SignerInfoBase & {
readonly hasSignedAttrs: true;
readonly signedAttrsDer: Uint8Array
}) | (ParsedPkcs7SignerInfoBase & {
readonly hasSignedAttrs: false;
readonly signedAttrsDer?: undefined
})ParsedPkcs7SignerInfoBase
Fields shared by every decoded SignerInfo, regardless of signed-attribute presence.
interface ParsedPkcs7SignerInfoBase {
readonly version: number;
readonly issuer?: ParsedName;
readonly serialNumberHex?: string;
readonly subjectKeyIdentifier?: string;
readonly digestAlgorithmOid: string;
readonly digestAlgorithmName: string;
readonly signatureAlgorithmOid: string;
readonly signatureAlgorithmName: string;
readonly signatureAlgorithmParametersDer?: Uint8Array;
readonly signatureHex: string;
readonly signature: Uint8Array;
}Properties
readonlyversion:number— CMS SignerInfo version (typically 1 for issuerAndSerialNumber).readonlyissuer?:ParsedName— Parsed issuer distinguished name, if present (issuerAndSerialNumber signer identifier).readonlyserialNumberHex?:string— Hex-encoded serial number used to locate the signer certificate, if present.readonlysubjectKeyIdentifier?:string— Hex-encoded SubjectKeyIdentifier used to locate the signer certificate, if present.readonlydigestAlgorithmOid:string— OID of the digest algorithm used to hash the content.readonlydigestAlgorithmName:string— Human-readable digest algorithm name (e.g."SHA-256").readonlysignatureAlgorithmOid:string— OID of the algorithm used to produce the signature.readonlysignatureAlgorithmName:string— Human-readable signature algorithm name.readonlysignatureAlgorithmParametersDer?:Uint8Array— Raw DER of the signature AlgorithmIdentifier parameters, if present.readonlysignatureHex:string— Hex-encoded raw signature bytes.readonlysignature:Uint8Array— Raw signature bytes.
ParsedPkcs12MacData
Decoded PKCS#12 MacData block returned by parsePkcs12MacData.
interface ParsedPkcs12MacData {
readonly digestAlgorithmOid: string;
readonly digestAlgorithmName: string;
readonly digestHex: string;
readonly saltHex: string;
readonly iterations: number;
readonly verification: valid | invalid | unchecked;
}Properties
readonlydigestAlgorithmOid:string— OID of the digest algorithm (currently always SHA-256).readonlydigestAlgorithmName:string— Human-readable digest algorithm name (currently"SHA-256").readonlydigestHex:string— Hex-encoded MAC digest value.readonlysaltHex:string— Hex-encoded salt bytes used during key derivation.readonlyiterations:number— Number of PKCS#12 KDF iterations.readonlyverification:valid|invalid|unchecked— MAC verification outcome:'unchecked'when no password was supplied during parsing, otherwise'valid'or'invalid'.
ParsePfxErrorCode
Error codes returned by parsePfxDer and parsePfxPem.
type ParsePfxErrorCode = malformed | invalid_password | password_requiredParsePfxFailure
Error payload for a failed PFX parse.
interface ParsePfxFailure extends Micro509Error<ParsePfxErrorCode> {
readonly ok: false;
}Properties
readonlyok:false— Alwaysfalsefor failures.
ParsePfxOptions
Options for parsePfxDer and parsePfxPem.
interface ParsePfxOptions {
readonly password?: string;
readonly macPassword?: string;
}Properties
readonlypassword?:string— Password used to decrypt PBES2-encrypted ContentInfo entries. Also used for MAC verification whenmacPasswordis omitted.readonlymacPassword?:string— Separate password for MAC verification. Falls back topasswordwhen omitted.
ParsePfxResult
Success-or-failure result from parsePfxDer / parsePfxPem.
type ParsePfxResult = {
readonly ok: true;
readonly value: ParsedPfx
} | ErrorResult<ParsePfxErrorCode, Record<never, never>, ParsePfxFailure>ParsePkcs7CertBagResult
Success-or-failure result from parsePkcs7CertBagDer / parsePkcs7CertBagPem.
type ParsePkcs7CertBagResult = {
readonly ok: true;
readonly value: readonly ParsedCertificate[]
} | ErrorResult<ParsePkcs7ErrorCode, Record<never, never>, ParsePkcs7Failure>ParsePkcs7ErrorCode
Error codes for PKCS#7 parse failures.
type ParsePkcs7ErrorCode = malformed | not_signed_dataParsePkcs7Failure
Error payload for a failed PKCS#7 parse.
interface ParsePkcs7Failure extends Micro509Error<ParsePkcs7ErrorCode> {
readonly ok: false;
}Properties
readonlyok:false— Alwaysfalsefor failures.
ParsePkcs7SignedDataResult
Success-or-failure result from parsePkcs7SignedDataDer / parsePkcs7SignedDataPem.
type ParsePkcs7SignedDataResult = {
readonly ok: true;
readonly value: ParsedPkcs7SignedData
} | ErrorResult<ParsePkcs7ErrorCode, Record<never, never>, ParsePkcs7Failure>ParsePkcs12MacDataErrorCode
Machine-readable failure reason for parsePkcs12MacData.
type ParsePkcs12MacDataErrorCode = malformedParsePkcs12MacDataFailure
Structured failure payload for MacData parsing.
interface ParsePkcs12MacDataFailure extends Micro509Error<ParsePkcs12MacDataErrorCode> {
readonly ok: false;
}Properties
readonlyok:false— Alwaysfalsefor failures.
ParsePkcs12MacDataResult
Success-or-failure result from parsePkcs12MacData.
type ParsePkcs12MacDataResult = {
readonly ok: true;
readonly value: ParsedPkcs12MacData
} | ErrorResult<ParsePkcs12MacDataErrorCode, Record<never, never>, ParsePkcs12MacDataFailure>PfxBagAttributesInput
Optional metadata attached to a certificate or key bag inside a PFX.
interface PfxBagAttributesInput {
readonly friendlyName?: string;
readonly localKeyId?: Uint8Array;
}Properties
readonlyfriendlyName?:string— Human-readable label stored as a BMPString attribute.readonlylocalKeyId?:Uint8Array— Opaque identifier linking a certificate bag to its corresponding key bag.
PfxCertificateBagInput
A certificate to embed in a PFX container. Input for createPfx.
interface PfxCertificateBagInput {
readonly certificate: PfxCertificateSource;
readonly attributes?: PfxBagAttributesInput;
}Properties
readonlycertificate:PfxCertificateSource— Certificate as PEM text or DER bytes.readonlyattributes?:PfxBagAttributesInput— Optional bag-level attributes (friendly name, local key ID).
PfxCertificateSource
PEM string or DER bytes for a certificate to include in a PFX bag.
type PfxCertificateSource = string | Uint8Array | ParsedCertificatePfxEncryptionOptions
PBES2 encryption settings for PFX key-bag protection. Alias of EncryptedPkcs8Options.
type PfxEncryptionOptions = EncryptedPkcs8OptionsPfxMaterial
DER, PEM, and base64 encodings of a PFX container produced by createPfx.
interface PfxMaterial {
readonly der: Uint8Array;
readonly pem: string;
readonly base64: string;
}Properties
readonlyder:Uint8Array— Raw DER-encoded PFX bytes.readonlypem:string— PEM-armored PFX (-----BEGIN PKCS12-----).readonlybase64:string— Base64-encoded DER (no PEM armor).
PfxPrivateKeyBagInput
A private key to embed in a PFX container. Input for createPfx.
interface PfxPrivateKeyBagInput {
readonly privateKey: PfxPrivateKeySource;
readonly attributes?: PfxBagAttributesInput;
}Properties
readonlyprivateKey:PfxPrivateKeySource— Private key as a WebCryptoCryptoKeyor raw PKCS#8 DER bytes.readonlyattributes?:PfxBagAttributesInput— Optional bag-level attributes (friendly name, local key ID).
PfxPrivateKeySource
A WebCrypto private key or raw PKCS#8 DER bytes for a PFX key bag.
type PfxPrivateKeySource = CryptoKey | Uint8ArrayPkcs7CertBagMaterial
DER, PEM, and base64 encodings of a PKCS#7 certificate bag.
interface Pkcs7CertBagMaterial {
readonly der: Uint8Array;
readonly pem: string;
readonly base64: string;
}Properties
readonlyder:Uint8Array— Raw DER-encoded PKCS#7 structure.readonlypem:string— PEM-armored PKCS#7 (-----BEGIN PKCS7-----).readonlybase64:string— Base64-encoded DER (no PEM armor).
Pkcs7CertificateSource
PEM text (may contain multiple CERTIFICATE blocks), raw DER bytes, or an already-parsed certificate.
type Pkcs7CertificateSource = string | Uint8Array | ParsedCertificatePkcs7SignedDataMaterial
DER, PEM, and base64 encodings of a PKCS#7 SignedData structure.
interface Pkcs7SignedDataMaterial {
readonly der: Uint8Array;
readonly pem: string;
readonly base64: string;
}Properties
readonlyder:Uint8Array— Raw DER-encoded PKCS#7 SignedData.readonlypem:string— PEM-armored PKCS#7 (-----BEGIN PKCS7-----).readonlybase64:string— Base64-encoded DER (no PEM armor).
Pkcs7Signer
A single signer for createPkcs7SignedData.
interface Pkcs7Signer {
readonly certificate: Pkcs7CertificateSource;
readonly privateKey: CryptoKey;
readonly signature?: SignatureProfileInput;
}Properties
readonlycertificate:Pkcs7CertificateSource— Signer certificate (PEM text with one CERTIFICATE block, or raw DER). Embedded in the SignedData certificate set and referenced by the SignerInfo via issuerAndSerialNumber.readonlyprivateKey:CryptoKey— Private key matching the certificate's public key, used to sign.readonlysignature?:SignatureProfileInput— Signature profile. Defaults to inferring the algorithm from the key (e.g. ECDSA→ecdsa-with-SHA*, RSA→sha*WithRSAEncryption, Ed25519). Pass{ kind: 'rsa-pss' }to force RSA-PSS padding for an RSA-PSS key.
Pkcs12MacOptions
Input for createPkcs12MacData.
interface Pkcs12MacOptions {
readonly password: string;
readonly iterations?: number;
readonly salt?: Uint8Array;
}Properties
readonlypassword:string— Password used to derive the HMAC key via the PKCS#12 KDF.readonlyiterations?:number— PKCS#12 KDF iteration count. Default:2048.readonlysalt?:Uint8Array— Random salt. Default: 16 cryptographically random bytes.
VerifyPkcs7SignedDataErrorCode
Error codes for verifyPkcs7SignedData failures.
detached_content_required means the SignedData carries no eContent (detached signature or degenerate cert bag) and no external content was supplied via VerifyPkcs7SignedDataOptions.
type VerifyPkcs7SignedDataErrorCode = signer_not_found | signature_invalid | message_digest_mismatch | detached_content_required | ParsePkcs7ErrorCodeVerifyPkcs7SignedDataFailure
Error payload for a failed verifyPkcs7SignedData call.
interface VerifyPkcs7SignedDataFailure extends Micro509Error<VerifyPkcs7SignedDataErrorCode> {
readonly ok: false;
}Properties
readonlyok:false— Alwaysfalsefor failures.
VerifyPkcs7SignedDataOptions
Options for verifyPkcs7SignedData.
interface VerifyPkcs7SignedDataOptions {
readonly content?: Uint8Array;
}Properties
readonlycontent?:Uint8Array— External content for a detached SignedData (RFC 5652 Section 5.2, absenteContent). Required to verify a detached signature; ignored when the SignedData embeds its own content.
VerifyPkcs7SignedDataResult
Success-or-failure result from verifyPkcs7SignedData.
type VerifyPkcs7SignedDataResult = {
readonly ok: true;
readonly value: ParsedPkcs7SignedData
} | ErrorResult<VerifyPkcs7SignedDataErrorCode, Record<never, never>, VerifyPkcs7SignedDataFailure>createPfx
Builds a PKCS#12/PFX archive containing certificates and/or private keys.
When encryption is provided, the key-bag ContentInfo is PBES2-encrypted. When mac is provided, a PKCS#12 MAC integrity block is appended.
Returns a CreatePfxResult: the container material on success, or a typed invalid_certificate failure when a certificate source is not a single PEM/DER certificate.
function createPfx(
input: CreatePfxInput,
): Promise<CreatePfxResult>Parameters
input:CreatePfxInput
Examples
import { createPfx, unwrap } from 'micro509';
const result = await createPfx({
certificates: [{ certificate: certPem }],
privateKeys: [{ privateKey: keyPair.privateKey }],
encryption: { password: 's3cret' },
mac: { password: 's3cret' },
});
if (result.ok) {
const pfx = result.value; // pfx.der, pfx.pem, pfx.base64
}
// or, when inputs are already validated: const pfx = unwrap(result);createPkcs7CertBag
Creates a degenerate PKCS#7 SignedData structure containing only certificates (no signers), returning DER, PEM, and base64 forms, or a typed invalid_certificate failure when a certificate source is not valid PEM/DER.
function createPkcs7CertBag(
certificates: readonly Pkcs7CertificateSource[],
): CreatePkcs7CertBagResultParameters
certificates:readonlyPkcs7CertificateSource[]
createPkcs7SignedData
Creates a PKCS#7/CMS SignedData with one or more signers over content.
Each signer uses the RFC 5652 Section 5.4 signed-attributes flow: the signature covers a SET OF authenticated attributes carrying contentType and messageDigest (the digest of the encapsulated content). By default the content is embedded (attached signature), so the result verifies with verifyPkcs7SignedData without any external data. With detached: true the eContent is omitted (RFC 5652 Section 5.2) and the verifier must supply the content externally.
The content digest is derived from each signer's key (P-256/RSA-SHA256 → SHA-256, P-384 → SHA-384, P-521 → SHA-512, Ed25519 → SHA-512 per RFC 8419).
Returns a CreatePkcs7SignedDataResult: DER, PEM, and base64 forms on success, or a typed failure for caller-correctable input (no signers, a signer source that is not exactly one certificate, or an unsupported signer key).
function createPkcs7SignedData(
input: CreatePkcs7SignedDataInput,
): Promise<CreatePkcs7SignedDataResult>Parameters
input:CreatePkcs7SignedDataInput
parsePfxDer
Decodes a DER-encoded PKCS#12/PFX container into its constituent bags.
Returns a result union — check ok before accessing value. Encrypted containers require options.password. MAC verification uses options.macPassword (falls back to options.password).
function parsePfxDer(
der: Uint8Array,
options?: ParsePfxOptions,
): Promise<ParsePfxResult>Parameters
der:Uint8Arrayoptions?:ParsePfxOptions
Examples
import { parsePfxDer } from 'micro509';
const result = await parsePfxDer(pfxBytes, { password: 's3cret' });
if (result.ok) {
console.log(result.value.certificates.length);
}parsePfxPem
Decodes a PEM-armored PKCS#12/PFX container. Expects exactly one PKCS12 block.
Delegates to parsePfxDer after PEM decoding.
function parsePfxPem(
pem: string,
options?: ParsePfxOptions,
): Promise<ParsePfxResult>Parameters
pem:stringoptions?:ParsePfxOptions
Examples
import { parsePfxPem } from 'micro509';
const result = await parsePfxPem(pfxPemString, { password: 's3cret' });
if (result.ok) {
console.log(result.value.privateKeys.length);
}parsePkcs7CertBagDer
Parses a DER-encoded PKCS#7 cert bag, returning the contained certificates.
function parsePkcs7CertBagDer(
der: Uint8Array,
): ParsePkcs7CertBagResultParameters
der:Uint8Array
parsePkcs7CertBagPem
Parses a PEM-armored PKCS#7 cert bag. Expects exactly one PKCS7 PEM block.
function parsePkcs7CertBagPem(
pem: string,
): ParsePkcs7CertBagResultParameters
pem:string
parsePkcs7SignedDataDer
Decodes a DER-encoded PKCS#7 ContentInfo expecting signedData content type.
function parsePkcs7SignedDataDer(
der: Uint8Array,
): ParsePkcs7SignedDataResultParameters
der:Uint8Array
parsePkcs7SignedDataPem
Decodes a PEM-armored PKCS#7 SignedData. Expects exactly one PKCS7 PEM block.
function parsePkcs7SignedDataPem(
pem: string,
): ParsePkcs7SignedDataResultParameters
pem:string
verifyPkcs7SignedData
Verifies all signer signatures in a PKCS#7 SignedData structure.
Accepts PEM text, raw DER, or an already-parsed ParsedPkcs7SignedData. For each signer, locates the matching certificate in the embedded set and verifies the signature (including signed-attribute digest checks per RFC 5652 Section 5.4).
For a detached SignedData (absent eContent), pass the externally-held content via options.content; without it, verification fails with the typed detached_content_required code. When the SignedData embeds its own content, that embedded content is verified and options.content is ignored.
function verifyPkcs7SignedData(
input: string | Uint8Array | ParsedPkcs7SignedData,
options: VerifyPkcs7SignedDataOptions,
): Promise<VerifyPkcs7SignedDataResult>Parameters
input:string|Uint8Array|ParsedPkcs7SignedDataoptions:VerifyPkcs7SignedDataOptions
Examples
import { verifyPkcs7SignedData } from 'micro509';
const result = await verifyPkcs7SignedData(pkcs7Pem);
if (result.ok) {
console.log('all signers verified');
}
// Detached signature: supply the content externally
const detached = await verifyPkcs7SignedData(cmsBlob, { content: signedBytes });ErrorResult
Failed result with a flattened code/message/details surface for ergonomic matching.
interface ErrorResult<TCode extends string, TDetails, TError extends Micro509Error<TCode, TDetails>> {
readonly ok: false;
readonly error: TError;
readonly code: TCode;
readonly message: string;
readonly details?: TDetails;
}Properties
readonlyok:false— Alwaysfalsefor failures.readonlyerror:TError— Structured error payload.readonlycode:TCode— Machine-readable failure reason, mirrored fromerror.code.readonlymessage:string— Human-readable diagnostic, mirrored fromerror.message.readonlydetails?:TDetails— Optional structured context for the failure.
IndexedErrorResult
Like ErrorResult but also carries an index into the collection that was being processed.
interface IndexedErrorResult<TCode extends string, TDetails, TError extends IndexedMicro509Error<TCode, TDetails>> extends ErrorResult<TCode, TDetails, TError> {
readonly index?: number;
}Properties
readonlyindex?:number— Zero-based position of the failing item in the input collection.
IndexedMicro509Error
Like Micro509Error but includes a positional index for collection-processing APIs.
interface IndexedMicro509Error<TCode extends string, TDetails> extends Micro509Error<TCode, TDetails> {
readonly index?: number;
}Properties
readonlyindex?:number— Zero-based position of the failing item in the input collection.
Micro509Error
Base error shape carried by all failure results in the library.
interface Micro509Error<TCode extends string, TDetails> {
readonly code: TCode;
readonly message: string;
readonly details?: TDetails;
}Properties
readonlycode:TCode— Machine-readable failure reason (e.g.'malformed','expired').readonlymessage:string— Human-readable diagnostic message.readonlydetails?:TDetails— Optional structured context for the failure.
Result
Discriminated ok union: either { ok: true; value } or { ok: false; error }.
Every fallible public API in micro509 returns a specialization of this type.
type Result<TValue, TError> = {
readonly ok: true;
readonly value: TValue
} | {
readonly ok: false;
readonly error: TError
}ResultError
Exception form of a Micro509Error: a branded Error carrying the structured code, message, and any details.
Thrown by unwrap for a failed result and by throwMicro509Error when a builder rejects invalid construction input. Detect with isResultError.
interface ResultError<TError extends Micro509Error<string, unknown>> extends Error {
readonly code: TError[code];
readonly error: TError;
}Properties
readonlycode:TError[code] — Machine-readable failure reason, mirrored fromerror.code.readonlyerror:TError— The structured error payload that produced this exception.
isResultError
Type guard: was value thrown by unwrap? Narrows to ResultError.
function isResultError(
value: unknown,
): value is ResultErrorParameters
value:unknown
unwrap
Explicit escape hatch: returns the success value, or throws a ResultError carrying the structured failure.
Use when you have already validated the input (or prefer exceptions) and the Result ceremony is noise. Accepts any of the library's *Result types.
function unwrap<TValue, TError extends Micro509Error<string, unknown>>(
result: UnwrappableResult<TValue, TError>,
): TValueParameters
result:UnwrappableResult<TValue,TError>
unwrapOr
Returns the success value, or fallback when the result is a failure.
function unwrapOr<TValue>(
result: UnwrappableResult<TValue, unknown>,
fallback: TValue,
): TValueParameters
result:UnwrappableResult<TValue,unknown>fallback:TValue
CertificateRevocationListMaterial
Encoded CRL in multiple serialisation formats, returned by createCertificateRevocationList.
interface CertificateRevocationListMaterial {
readonly der: Uint8Array;
readonly pem: string;
readonly base64: string;
}Properties
readonlyder:Uint8Array— Raw DER bytes of the signed CRL.readonlypem:string— PEM-encoded CRL (-----BEGIN X509 CRL-----).readonlybase64:string— Base64-encoded DER (no PEM armour).
CertificateRevocationStatus
Revocation evaluation result for a single certificate.
One entry per certificate in CheckChainRevocationValue.certificates. The trust anchor is excluded (never checked for revocation).
type CertificateRevocationStatus = {
readonly certificate: ParsedCertificate;
readonly status: good;
readonly source: RevocationSource;
readonly indeterminateReasons?: undefined;
readonly revocationInfo?: undefined
} | {
readonly certificate: ParsedCertificate;
readonly status: revoked;
readonly source: RevocationSource;
readonly revocationInfo: {
readonly revocationDate: Date;
readonly reason?: RevocationReason
};
readonly indeterminateReasons?: undefined
} | {
readonly certificate: ParsedCertificate;
readonly status: indeterminate;
readonly indeterminateReasons: readonly RevocationIndeterminateReason[];
readonly source?: undefined;
readonly revocationInfo?: undefined
}CheckCertificateRevocationAgainstCrlErrorCode
Error codes that checkCertificateRevocationAgainstCrl may return.
type CheckCertificateRevocationAgainstCrlErrorCode = signature_invalid | issuer_mismatch | stale_crl | crl_sign_not_permitted | non_applicableCheckCertificateRevocationAgainstCrlFailure
Failure detail for checkCertificateRevocationAgainstCrl.
interface CheckCertificateRevocationAgainstCrlFailure extends Micro509Error<CheckCertificateRevocationAgainstCrlErrorCode, CheckCertificateRevocationAgainstCrlFailureDetails> {
readonly ok: false;
}Properties
readonlyok:false— Alwaysfalsefor failures.
CheckCertificateRevocationAgainstCrlFailureDetails
Structured details attached to a CheckCertificateRevocationAgainstCrlFailure.
interface CheckCertificateRevocationAgainstCrlFailureDetails {
readonly reason?: CrlApplicabilityFailureReason;
}Properties
readonlyreason?:CrlApplicabilityFailureReason— Why the CRL was non-applicable, when the error code isnon_applicable.
CheckCertificateRevocationAgainstCrlGoodValue
Success value when the certificate is not found in the CRL.
interface CheckCertificateRevocationAgainstCrlGoodValue {
readonly status: good;
readonly crl: ParsedCertificateRevocationList;
}Properties
readonlystatus:good— Certificate is not revoked.readonlycrl:ParsedCertificateRevocationList— The validated CRL that was checked.
CheckCertificateRevocationAgainstCrlInput
Input for checkCertificateRevocationAgainstCrl.
interface CheckCertificateRevocationAgainstCrlInput {
readonly certificate: CrlCertificateSource;
readonly issuerCertificate: CrlCertificateSource;
readonly crl: CrlSource;
readonly deltaCrl?: CrlSource;
readonly at?: Date;
readonly clockSkewMs?: number;
}Properties
readonlycertificate:CrlCertificateSource— Certificate whose revocation status to check.readonlyissuerCertificate:CrlCertificateSource— Issuer ofcertificate— also expected signer of the CRL.readonlycrl:CrlSource— Complete (base) CRL to check against.readonlydeltaCrl?:CrlSource— Optional delta CRL for more recent revocation information.readonlyat?:Date— Evaluation time. Defaults tonew Date().readonlyclockSkewMs?:number— Clock-skew tolerance in milliseconds for freshness checks.
CheckCertificateRevocationAgainstCrlResult
Result of checkCertificateRevocationAgainstCrl.
On success value.status is 'good' or 'revoked'. On failure the CRL could not be validated or was non-applicable.
type CheckCertificateRevocationAgainstCrlResult = {
readonly ok: true;
readonly value: CheckCertificateRevocationAgainstCrlValue
} | ErrorResult<CheckCertificateRevocationAgainstCrlErrorCode, CheckCertificateRevocationAgainstCrlFailureDetails, CheckCertificateRevocationAgainstCrlFailure>CheckCertificateRevocationAgainstCrlRevokedValue
Success value when the certificate is found as revoked in the CRL.
interface CheckCertificateRevocationAgainstCrlRevokedValue {
readonly status: revoked;
readonly crl: ParsedCertificateRevocationList;
readonly revocationDate: Date;
readonly reasonCode?: RevocationReason;
}Properties
readonlystatus:revoked— Certificate is revoked.readonlycrl:ParsedCertificateRevocationList— The validated CRL that contained the revocation entry.readonlyrevocationDate:Date— When the CA declared this certificate revoked.readonlyreasonCode?:RevocationReason— CRLReason from the entry, if present.
CheckCertificateRevocationAgainstCrlValue
Discriminated union of good and revoked outcomes.
type CheckCertificateRevocationAgainstCrlValue = CheckCertificateRevocationAgainstCrlGoodValue | CheckCertificateRevocationAgainstCrlRevokedValueCheckCertificateRevocationErrorCode
Error codes that checkCertificateRevocation may surface inside an indeterminate result.
type CheckCertificateRevocationErrorCode = revocation_evidence_missing | revocation_status_indeterminateCheckCertificateRevocationFailureDetails
Diagnostic details attached to an indeterminate revocation result.
interface CheckCertificateRevocationFailureDetails {
readonly checkedSources: readonly RevocationEvidenceKind[];
readonly indeterminateEvidence: readonly RevocationIndeterminateEvidence[];
}Properties
readonlycheckedSources:readonlyRevocationEvidenceKind[]— Which evidence kinds were attempted ('crl','ocsp', or both).readonlyindeterminateEvidence:readonlyRevocationIndeterminateEvidence[]— Per-evidence explanations of why no definitive answer was reached.
CheckCertificateRevocationInput
Input for checkCertificateRevocation.
interface CheckCertificateRevocationInput {
readonly certificate: RevocationCertificateSource;
readonly issuerCertificate: RevocationCertificateSource;
readonly evidence?: readonly RevocationEvidenceInput[];
readonly at?: Date;
readonly clockSkewMs?: number;
}Properties
readonlycertificate:RevocationCertificateSource— Certificate whose revocation status to determine.readonlyissuerCertificate:RevocationCertificateSource— Issuer ofcertificate.readonlyevidence?:readonlyRevocationEvidenceInput[]— CRL and/or OCSP evidence to evaluate. Returnsindeterminateif empty.readonlyat?:Date— Evaluation time. Defaults tonew Date().readonlyclockSkewMs?:number— Clock-skew tolerance in milliseconds.
CheckCertificateRevocationResult
Result of checkCertificateRevocation. Always succeeds (ok: true) — the value.status discriminator carries the actual outcome.
type CheckCertificateRevocationResult = Result<CheckCertificateRevocationValue, never>CheckCertificateRevocationValue
Discriminated union of good, revoked, and indeterminate revocation outcomes.
type CheckCertificateRevocationValue = RevocationCheckGoodValue | RevocationCheckRevokedValue | RevocationCheckIndeterminateValueCheckChainRevocationInput
Input for checkChainRevocation.
interface CheckChainRevocationInput {
readonly chain: readonly ParsedCertificate[];
readonly crls?: readonly CrlSource[];
readonly ocspResponses?: readonly OcspResponseSource[];
readonly extraCertificates?: readonly RevocationCertificateSource[];
readonly trustedOcspResponders?: readonly RevocationCertificateSource[];
readonly at?: Date;
readonly policy?: RevocationPolicy;
}Properties
readonlychain:readonlyParsedCertificate[]— Validated certificate chain (leaf first, root last).readonlycrls?:readonlyCrlSource[]— CRLs to evaluate.readonlyocspResponses?:readonlyOcspResponseSource[]— OCSP responses to evaluate.readonlyextraCertificates?:readonlyRevocationCertificateSource[]— Extra certs for indirect CRL issuers / delegated OCSP responders.readonlytrustedOcspResponders?:readonlyRevocationCertificateSource[]— Explicitly trusted OCSP responder certificates (RFC 6960 §4.2.2.2 criterion 1). A response signed by one of these is accepted without delegated-responder issuance, EKU, and revocation checks.readonlyat?:Date— Evaluation time. Defaults tonew Date().readonlypolicy?:RevocationPolicy— Revocation policy.
CheckChainRevocationResult
Result type for checkChainRevocation.
type CheckChainRevocationResult = {
readonly ok: true;
readonly value: CheckChainRevocationValue
}CheckChainRevocationValue
Detailed revocation check results.
Returned as CheckChainRevocationResult.value from checkChainRevocation. Contains both the policy decision and detailed per-certificate findings for debugging.
interface CheckChainRevocationValue {
readonly decision: allow | deny;
readonly summary: {
readonly revokedCertificates: readonly ParsedCertificate[];
readonly indeterminateCertificates: readonly ParsedCertificate[]
};
readonly certificates: readonly CertificateRevocationStatus[];
readonly executionErrors?: readonly RevocationExecutionError[];
}Properties
readonlydecision:allow|deny— Final policy decision based onRevocationPolicy.'allow': chain passes revocation check'deny': chain fails (revoked certificate or hard-fail on indeterminate)
readonlysummary: {readonlyrevokedCertificates:readonlyParsedCertificate[];readonlyindeterminateCertificates:readonlyParsedCertificate[]} — Quick-access summary of problematic certificates.readonlycertificates:readonlyCertificateRevocationStatus[]— Per-certificate evaluation results. SeeCertificateRevocationStatus.readonlyexecutionErrors?:readonlyRevocationExecutionError[]— Evidence that could not be processed. SeeRevocationExecutionError.
ConfiguredOcspResponder
A manually-configured OCSP responder endpoint.
interface ConfiguredOcspResponder {
readonly uri: string;
readonly responderCertificate?: ConfiguredOcspResponderCertificate;
}Properties
readonlyuri:string— OCSP responder URI (typicallyhttp://...).readonlyresponderCertificate?:ConfiguredOcspResponderCertificate— Known responder certificate — skips embedded-certificate discovery.
ConfiguredOcspResponderCertificate
PEM or DER bytes of a pre-configured OCSP responder certificate.
type ConfiguredOcspResponderCertificate = string | Uint8ArrayCreateCertificateRevocationListInput
Input for createCertificateRevocationList.
interface CreateCertificateRevocationListInput {
readonly issuer: NameInput;
readonly signerPrivateKey: CryptoKey;
readonly issuerPublicKey?: CryptoKey;
readonly thisUpdate?: Date;
readonly nextUpdate?: Date;
readonly revokedCertificates?: readonly RevokedCertificateInput[];
readonly crlNumber?: number;
readonly baseCrlNumber?: number;
readonly issuingDistributionPoint?: IssuingDistributionPoint;
readonly freshestCrlDistributionPoints?: readonly DistributionPoint[];
}Properties
readonlyissuer:NameInput— Distinguished name of the CRL issuer (typically the signing CA).readonlysignerPrivateKey:CryptoKey— Private key used to sign the CRL. Algorithm is inferred from the key.readonlyissuerPublicKey?:CryptoKey— Issuer public key — used to embed an Authority Key Identifier extension.readonlythisUpdate?:Date— Issuance timestamp. Defaults tonew Date().readonlynextUpdate?:Date— Planned next issuance. Omit for an open-ended CRL.readonlyrevokedCertificates?:readonlyRevokedCertificateInput[]— Certificates to list as revoked in this CRL.readonlycrlNumber?:number— Monotonically-increasing CRL sequence number (CRLNumber extension).readonlybaseCrlNumber?:number— If set, marks this CRL as a delta CRL referencing the given base CRL number.readonlyissuingDistributionPoint?:IssuingDistributionPoint— Issuing distribution point extension — scopes this CRL to a subset of certificates.readonlyfreshestCrlDistributionPoints?:readonlyDistributionPoint[]— Freshest CRL distribution points — tells relying parties where to find delta CRLs.
CreateOcspRequestInput
Input for createOcspRequest.
interface CreateOcspRequestInput {
readonly requests: readonly CreateOcspRequestItemInput[];
readonly hashAlgorithm?: OcspHashAlgorithm;
readonly nonce?: Uint8Array;
}Properties
readonlyrequests:readonlyCreateOcspRequestItemInput[]— One or more certificates to query (batched into a single OCSP request).readonlyhashAlgorithm?:OcspHashAlgorithm— Hash algorithm for CertID computation. Defaults to'SHA-1'.readonlynonce?:Uint8Array— Random nonce for replay protection. Omit to skip the nonce extension.
CreateOcspRequestItemInput
One certificate whose status to query in an OCSP request. Used as an element of CreateOcspRequestInput.requests.
interface CreateOcspRequestItemInput {
readonly certificate: OcspCertificateSource;
readonly issuerCertificate: OcspCertificateSource;
}Properties
readonlycertificate:OcspCertificateSource— Certificate whose revocation status is being queried.readonlyissuerCertificate:OcspCertificateSource— Issuer ofcertificate— needed to compute the CertID hash.
CreateOcspResponseInput
Input for createOcspResponse.
interface CreateOcspResponseInput {
readonly signerPrivateKey: CryptoKey;
readonly signerCertificate: OcspCertificateSource;
readonly responses: readonly CreateOcspSingleResponseInput[];
readonly producedAt?: Date;
readonly nonce?: Uint8Array;
readonly hashAlgorithm?: OcspHashAlgorithm;
readonly includedCertificates?: readonly OcspCertificateSource[];
}Properties
readonlysignerPrivateKey:CryptoKey— Private key used to sign the response. Algorithm is inferred from the key.readonlysignerCertificate:OcspCertificateSource— Certificate of the OCSP responder — used to build the responder ID (by key hash).readonlyresponses:readonlyCreateOcspSingleResponseInput[]— Per-certificate status entries to include in the BasicOCSPResponse.readonlyproducedAt?:Date— Timestamp for theproducedAtfield. Defaults tonew Date().readonlynonce?:Uint8Array— Nonce to echo back for replay protection.readonlyhashAlgorithm?:OcspHashAlgorithm— Hash algorithm for CertID computation. Defaults to'SHA-1'.readonlyincludedCertificates?:readonlyOcspCertificateSource[]— Extra certificates to embed in the response (e.g. the responder's issuer chain).
CreateOcspSingleResponseInput
One certificate's status entry for CreateOcspResponseInput.responses. Extends CreateOcspRequestItemInput with status and timing fields.
interface CreateOcspSingleResponseInput extends CreateOcspRequestItemInput {
readonly certStatus: OcspCertStatus;
readonly thisUpdate?: Date;
readonly nextUpdate?: Date;
readonly revokedAt?: Date;
readonly revocationReasonCode?: number;
}Properties
readonlycertStatus:OcspCertStatus— Status to assert for this certificate.readonlythisUpdate?:Date— Start of the validity window for this status assertion. Defaults tonew Date().readonlynextUpdate?:Date— End of the validity window. Omit for open-ended assertions.readonlyrevokedAt?:Date— Revocation time (required whencertStatusis'revoked'). Defaults tothisUpdate.readonlyrevocationReasonCode?:number— CRLReason integer code (only meaningful whencertStatusis'revoked').
CrlApplicabilityFailureReason
Structured reason why a CRL was deemed non-applicable to a given certificate.
type CrlApplicabilityFailureReason = certificate_scope_mismatch | delta_crl_incompatible | unsupported_delta_crl | distribution_point_mismatch | unsupported_indirect_crl | issuer_mismatch | reasons_mismatchCrlCertificateSource
PEM string, DER bytes, or already-parsed certificate.
type CrlCertificateSource = string | Uint8Array | ParsedCertificateCrlEncoderErrorCode
Machine-readable reason a CRL encoder rejected its construction input.
type CrlEncoderErrorCode = distribution_point_name_conflict | distribution_point_full_name_empty | distribution_point_name_emptyCrlSource
PEM string, DER bytes, or already-parsed CRL.
type CrlSource = string | Uint8Array | ParsedCertificateRevocationListIssuingDistributionPoint
Input for the Issuing Distribution Point CRL extension (RFC 5280 §5.2.5).
The union enforces that at most one of the onlyContains* flags is true.
type IssuingDistributionPoint = IssuingDistributionPointBase | IssuingDistributionPointForUserCerts | IssuingDistributionPointForCaCerts | IssuingDistributionPointForAttributeCertsIssuingDistributionPointBase
Base shape for Issuing Distribution Point (RFC 5280 §5.2.5) — no scope restriction.
interface IssuingDistributionPointBase {
readonly distributionPoint?: DistributionPointName;
readonly onlySomeReasons?: readonly DistributionPointReason[];
readonly indirectCrl?: boolean;
readonly onlyContainsUserCerts?: false;
readonly onlyContainsCACerts?: false;
readonly onlyContainsAttributeCerts?: boolean;
}Properties
readonlydistributionPoint?:DistributionPointName— Where to fetch this CRL.readonlyonlySomeReasons?:readonlyDistributionPointReason[]— Limits the CRL to these revocation reasons. Absent means all reasons.readonlyindirectCrl?:boolean— When true, the CRL may contain entries from other CAs. Default false.readonlyonlyContainsUserCerts?:false— Must be absent or false in this variant (no user-cert-only restriction).readonlyonlyContainsCACerts?:false— Must be absent or false in this variant (no CA-cert-only restriction).readonlyonlyContainsAttributeCerts?:boolean— When true, the CRL only covers attribute certificates. Default false.
IssuingDistributionPointForAttributeCerts
IDP scoped to attribute certificates only. Mutually exclusive with user / CA scopes.
interface IssuingDistributionPointForAttributeCerts extends Omit<IssuingDistributionPointBase, onlyContainsAttributeCerts> {
readonly onlyContainsUserCerts?: false;
readonly onlyContainsCACerts?: false;
readonly onlyContainsAttributeCerts: true;
}Properties
readonlyonlyContainsUserCerts?:false— Must be absent or false when the CRL is not user-cert-only.readonlyonlyContainsCACerts?:false— Must be absent or false when the CRL is not CA-only.readonlyonlyContainsAttributeCerts:true— This variant only covers attribute certificates.
IssuingDistributionPointForCaCerts
IDP scoped to CA certificates only. Mutually exclusive with user / attribute scopes.
interface IssuingDistributionPointForCaCerts extends Omit<IssuingDistributionPointBase, onlyContainsCACerts> {
readonly onlyContainsUserCerts?: false;
readonly onlyContainsCACerts: true;
readonly onlyContainsAttributeCerts?: false;
}Properties
readonlyonlyContainsUserCerts?:false— Must be absent or false when the CRL is not user-cert-only.readonlyonlyContainsCACerts:true— This variant only covers CA certificates.readonlyonlyContainsAttributeCerts?:false— Must be absent or false when the CRL is not attribute-cert-only.
IssuingDistributionPointForUserCerts
IDP scoped to end-entity (user) certificates only. Mutually exclusive with CA / attribute scopes.
interface IssuingDistributionPointForUserCerts extends Omit<IssuingDistributionPointBase, onlyContainsUserCerts> {
readonly onlyContainsUserCerts: true;
readonly onlyContainsCACerts?: false;
readonly onlyContainsAttributeCerts?: false;
}Properties
readonlyonlyContainsUserCerts:true— This variant only covers end-entity certificates.readonlyonlyContainsCACerts?:false— Must be absent or false when the CRL is not CA-only.readonlyonlyContainsAttributeCerts?:false— Must be absent or false when the CRL is not attribute-cert-only.
OcspCertificateSource
PEM string, DER bytes, or already-parsed certificate.
type OcspCertificateSource = string | Uint8Array | ParsedCertificateOcspCertStatus
RFC 6960 certificate status reported by the responder for a single CertID.
type OcspCertStatus = good | revoked | unknownOcspHashAlgorithm
Hash algorithm used to compute OCSP CertID fields. SHA-1 is the RFC 6960 default.
type OcspHashAlgorithm = SHA-1 | SHA-256OcspRequestMaterial
Encoded OCSP request in multiple serialisation formats, returned by createOcspRequest.
interface OcspRequestMaterial {
readonly der: Uint8Array;
readonly pem: string;
readonly base64: string;
}Properties
readonlyder:Uint8Array— Raw DER bytes.readonlypem:string— PEM-encoded request (-----BEGIN OCSP REQUEST-----).readonlybase64:string— Base64-encoded DER (no PEM armour).
OcspRequestSource
PEM string, DER bytes, or already-parsed OCSP request.
type OcspRequestSource = string | Uint8Array | ParsedOcspRequestOcspResponderCandidate
One candidate OCSP responder resolved by resolveOcspResponderCandidates.
interface OcspResponderCandidate {
readonly source: OcspResponderSource;
readonly uri: string;
readonly responderCertificate?: ConfiguredOcspResponderCertificate;
}Properties
readonlysource:OcspResponderSource— Whether this candidate came from configuration or the certificate's AIA extension.readonlyuri:string— OCSP responder URI.readonlyresponderCertificate?:ConfiguredOcspResponderCertificate— Pre-known responder certificate, if available.
OcspResponderRevocationPolicy
Revocation policy for delegated OCSP responder certificates (RFC 6960 §4.2.2.2.1).
'honor-nocheck'(default): a responder carryingid-pkix-ocsp-nocheckis exempt from revocation checking. Otherwise, CRL evidence fromValidateOcspResponseInput.responderRevocationCrlsis consulted when provided — a revoked responder rejects the response; missing or unusable evidence is tolerated (soft).'require-evidence':nocheckis ignored; CRL evidence must positively show the responder is not revoked, otherwise the response is rejected.'skip': no responder revocation checking.
type OcspResponderRevocationPolicy = honor-nocheck | require-evidence | skipOcspResponderSource
Where the OCSP responder URI came from.
type OcspResponderSource = configured | authorityInfoAccessOcspResponseMaterial
Encoded OCSP response in multiple serialisation formats, returned by createOcspResponse.
interface OcspResponseMaterial {
readonly der: Uint8Array;
readonly pem: string;
readonly base64: string;
}Properties
readonlyder:Uint8Array— Raw DER bytes.readonlypem:string— PEM-encoded response (-----BEGIN OCSP RESPONSE-----).readonlybase64:string— Base64-encoded DER (no PEM armour).
OcspResponseSource
OCSP response in any supported format.
Accepts PEM string or DER bytes. Used for CheckChainRevocationInput.ocspResponses.
type OcspResponseSource = string | Uint8ArrayOcspResponseStatus
RFC 6960 overall response status — anything other than 'successful' means the response body is absent or unusable.
type OcspResponseStatus = successful | malformedRequest | internalError | tryLater | sigRequired | unauthorizedParseCertificateRevocationListErrorCode
Machine-readable failure reason for the CRL parsers.
type ParseCertificateRevocationListErrorCode = malformedParseCertificateRevocationListFailure
Structured failure payload for CRL parsing.
interface ParseCertificateRevocationListFailure extends Micro509Error<ParseCertificateRevocationListErrorCode> {
readonly ok: false;
}Properties
readonlyok:false— Alwaysfalsefor failures.
ParseCertificateRevocationListResult
Success-or-failure result from parseCertificateRevocationListDer / parseCertificateRevocationListPem.
type ParseCertificateRevocationListResult = {
readonly ok: true;
readonly value: ParsedCertificateRevocationList
} | ErrorResult<ParseCertificateRevocationListErrorCode, Record<never, never>, ParseCertificateRevocationListFailure>ParsedCertificateRevocationList
Decoded X.509 CRL, returned by parseCertificateRevocationListDer and parseCertificateRevocationListPem.
interface ParsedCertificateRevocationList {
readonly der?: Uint8Array;
readonly version: number;
readonly tbsCertListDer: Uint8Array;
readonly signatureValue: Uint8Array;
readonly issuer: ParsedName;
readonly thisUpdate: Date;
readonly nextUpdate?: Date;
readonly signatureAlgorithmOid: string;
readonly signatureAlgorithmName: string;
readonly signatureAlgorithmParametersDer?: Uint8Array;
readonly issuerPublicKeyAlgorithmOid?: string;
readonly issuerPublicKeyParametersOid?: string;
readonly authorityKeyIdentifier?: string;
readonly crlNumber?: number;
readonly baseCrlNumber?: number;
readonly issuingDistributionPoint?: ParsedIssuingDistributionPoint;
readonly freshestCrlDistributionPoints?: readonly ParsedDistributionPoint[];
readonly revokedCertificates: readonly ParsedRevokedCertificate[];
}Properties
readonlyder?:Uint8Array— Original DER bytes when this object came fromparseCertificateRevocationListDeror PEM parsing.readonlyversion:number— CRL version (1 = v1, 2 = v2 with extensions).readonlytbsCertListDer:Uint8Array— DER-encoded TBSCertList — the signed payload for signature verification.readonlysignatureValue:Uint8Array— Raw signature bytes from the CRL outer wrapper.readonlyissuer:ParsedName— CRL issuer distinguished name.readonlythisUpdate:Date— Start of the CRL validity window.readonlynextUpdate?:Date— End of the CRL validity window. Absent if the CA does not commit to a schedule.readonlysignatureAlgorithmOid:string— OID of the algorithm used to sign this CRL.readonlysignatureAlgorithmName:string— Human-readable signature algorithm name (e.g."ECDSA with SHA-256").readonlysignatureAlgorithmParametersDer?:Uint8Array— DER-encoded signature algorithm parameters (e.g. DER NULL for RSA PKCS#1 v1.5).readonlyissuerPublicKeyAlgorithmOid?:string— OID of the issuer's public key algorithm, when available.readonlyissuerPublicKeyParametersOid?:string— OID of the issuer's public key parameters (e.g. named curve), when available.readonlyauthorityKeyIdentifier?:string— Hex-encoded Authority Key Identifier, if the extension is present.readonlycrlNumber?:number— CRLNumber extension value — monotonically increasing sequence number.readonlybaseCrlNumber?:number— Delta CRL indicator — present only on delta CRLs, referencing the base CRL number.readonlyissuingDistributionPoint?:ParsedIssuingDistributionPoint— Issuing distribution point extension — scopes this CRL to a certificate subset.readonlyfreshestCrlDistributionPoints?:readonlyParsedDistributionPoint[]— Freshest CRL extension — points to delta CRL locations.readonlyrevokedCertificates:readonlyParsedRevokedCertificate[]— All revoked certificate entries (empty array if none).
ParsedIssuingDistributionPoint
Decoded Issuing Distribution Point CRL extension (RFC 5280 §5.2.5). Constrains which certificates a CRL covers (scope, reasons, indirection).
interface ParsedIssuingDistributionPoint {
readonly distributionPoint?: ParsedDistributionPointName;
readonly onlyContainsUserCerts?: boolean;
readonly onlyContainsCACerts?: boolean;
readonly onlySomeReasons?: ParsedBitFlags<DistributionPointReason>;
readonly indirectCrl?: boolean;
readonly onlyContainsAttributeCerts?: boolean;
}Properties
readonlydistributionPoint?:ParsedDistributionPointName— Where to fetch this CRL, if specified.readonlyonlyContainsUserCerts?:boolean— When true, this CRL only covers end-entity certificates. Default false.readonlyonlyContainsCACerts?:boolean— When true, this CRL only covers CA certificates. Default false.readonlyonlySomeReasons?:ParsedBitFlags<DistributionPointReason> — Limits the CRL to these revocation reasons. Absent means all reasons.readonlyindirectCrl?:boolean— When true, this CRL may contain entries from CAs other than the issuer. Default false.readonlyonlyContainsAttributeCerts?:boolean— When true, this CRL only covers attribute certificates. Default false.
ParsedOcspCertId
Decoded OCSP CertID — identifies a certificate by hashed issuer name, hashed issuer key, and serial number.
interface ParsedOcspCertId {
readonly hashAlgorithmOid: string;
readonly hashAlgorithmName: string;
readonly issuerNameHashHex: string;
readonly issuerKeyHashHex: string;
readonly serialNumberHex: string;
}Properties
readonlyhashAlgorithmOid:string— OID of the hash algorithm used for the name and key hashes.readonlyhashAlgorithmName:string— Human-readable hash algorithm name (e.g."SHA-256").readonlyissuerNameHashHex:string— Hex-encoded hash of the issuer's distinguished name DER.readonlyissuerKeyHashHex:string— Hex-encoded hash of the issuer's SubjectPublicKey BIT STRING content.readonlyserialNumberHex:string— Hex-encoded serial number of the certificate.
ParsedOcspRequest
Decoded OCSP request, returned by parseOcspRequestDer / parseOcspRequestPem.
interface ParsedOcspRequest {
readonly der?: Uint8Array;
readonly requests: readonly ParsedOcspCertId[];
readonly nonce?: string;
}Properties
readonlyder?:Uint8Array— Original DER bytes when this object came fromparseOcspRequestDeror PEM parsing.readonlyrequests:readonlyParsedOcspCertId[]— CertIDs of the certificates being queried.readonlynonce?:string— Hex-encoded nonce extension value, if present.
ParsedOcspResponderId
How the OCSP responder identifies itself — either by distinguished name or by SHA-1 hash of its public key.
type ParsedOcspResponderId = {
readonly type: byName;
readonly name: ParsedName
} | {
readonly type: byKeyHash;
readonly keyHashHex: string
}ParsedOcspResponse
Decoded OCSP response, returned by parseOcspResponseDer / parseOcspResponsePem.
When responseStatus is not 'successful', most fields are absent.
interface ParsedOcspResponse {
readonly der?: Uint8Array;
readonly responseStatus: OcspResponseStatus;
readonly responseTypeOid?: string;
readonly responseDataDer?: Uint8Array;
readonly responderId?: ParsedOcspResponderId;
readonly signatureAlgorithmOid?: string;
readonly signatureAlgorithmName?: string;
readonly signatureValue?: Uint8Array;
readonly producedAt?: Date;
readonly responses?: readonly ParsedOcspSingleResponse[];
readonly nonce?: string;
readonly certificates?: readonly ParsedCertificate[];
}Properties
readonlyder?:Uint8Array— Original DER bytes when this object came fromparseOcspResponseDeror PEM parsing.readonlyresponseStatus:OcspResponseStatus— Overall response status. Only'successful'carries a BasicOCSPResponse body.readonlyresponseTypeOid?:string— OID of the response type (normallyid-pkix-ocsp-basic).readonlyresponseDataDer?:Uint8Array— DER-encoded ResponseData — the signed payload for signature verification.readonlyresponderId?:ParsedOcspResponderId— How the responder identifies itself.readonlysignatureAlgorithmOid?:string— OID of the algorithm used to sign this response.readonlysignatureAlgorithmName?:string— Human-readable signature algorithm name.readonlysignatureValue?:Uint8Array— Raw signature bytes.readonlyproducedAt?:Date— Timestamp when the responder produced this response.readonlyresponses?:readonlyParsedOcspSingleResponse[]— Per-certificate status entries.readonlynonce?:string— Hex-encoded nonce, if the response echoed one.readonlycertificates?:readonlyParsedCertificate[]— Certificates embedded in the response (typically the responder's chain).
ParsedOcspSingleResponse
Status of one certificate inside an OCSP BasicResponse.
interface ParsedOcspSingleResponse {
readonly certId: ParsedOcspCertId;
readonly certStatus: OcspCertStatus;
readonly thisUpdate: Date;
readonly nextUpdate?: Date;
readonly revokedAt?: Date;
readonly revocationReasonCode?: number;
}Properties
readonlycertId:ParsedOcspCertId— Which certificate this status applies to.readonlycertStatus:OcspCertStatus— Responder's verdict:good,revoked, orunknown.readonlythisUpdate:Date— Start of the validity window for this status assertion.readonlynextUpdate?:Date— End of the validity window. Absent if the responder does not commit to a schedule.readonlyrevokedAt?:Date— When the certificate was revoked (only forcertStatus === 'revoked').readonlyrevocationReasonCode?:number— CRLReason integer (only forcertStatus === 'revoked').
ParsedRevokedCertificate
A single revoked-certificate entry decoded from a CRL.
interface ParsedRevokedCertificate {
readonly serialNumberHex: string;
readonly revocationDate: Date;
readonly reasonCode?: RevocationReason;
readonly invalidityDate?: Date;
readonly certificateIssuer?: readonly GeneralName[];
}Properties
readonlyserialNumberHex:string— Hex-encoded serial number of the revoked certificate.readonlyrevocationDate:Date— When the CA declared this certificate revoked.readonlyreasonCode?:RevocationReason— RFC 5280 CRLReason, if the entry carries one.readonlyinvalidityDate?:Date— When the key or certificate actually became suspect, if present.readonlycertificateIssuer?:readonlyGeneralName[]— Indirect-CRL certificate issuer override (RFC 5280 §5.3.3).
ParseOcspRequestErrorCode
Machine-readable failure reason for the OCSP request parsers.
type ParseOcspRequestErrorCode = malformedParseOcspRequestFailure
Structured failure payload for OCSP request parsing.
interface ParseOcspRequestFailure extends Micro509Error<ParseOcspRequestErrorCode> {
readonly ok: false;
}Properties
readonlyok:false— Alwaysfalsefor failures.
ParseOcspRequestResult
Success-or-failure result from parseOcspRequestDer / parseOcspRequestPem.
type ParseOcspRequestResult = {
readonly ok: true;
readonly value: ParsedOcspRequest
} | ErrorResult<ParseOcspRequestErrorCode, Record<never, never>, ParseOcspRequestFailure>ParseOcspResponseErrorCode
Machine-readable failure reason for the OCSP response parsers.
type ParseOcspResponseErrorCode = malformedParseOcspResponseFailure
Structured failure payload for OCSP response parsing.
interface ParseOcspResponseFailure extends Micro509Error<ParseOcspResponseErrorCode> {
readonly ok: false;
}Properties
readonlyok:false— Alwaysfalsefor failures.
ParseOcspResponseResult
Success-or-failure result from parseOcspResponseDer / parseOcspResponsePem.
type ParseOcspResponseResult = {
readonly ok: true;
readonly value: ParsedOcspResponse
} | ErrorResult<ParseOcspResponseErrorCode, Record<never, never>, ParseOcspResponseFailure>ResolveOcspResponderCandidatesInput
Input for resolveOcspResponderCandidates.
interface ResolveOcspResponderCandidatesInput {
readonly certificate: RevocationCertificateSource;
readonly configuredResponders?: readonly ConfiguredOcspResponder[];
}Properties
readonlycertificate:RevocationCertificateSource— Certificate whose AIA extension will be inspected for OCSP URIs.readonlyconfiguredResponders?:readonlyConfiguredOcspResponder[]— Manually-configured responders — checked before AIA-derived ones.
RevocationCertificateSource
PEM string, DER bytes, or already-parsed certificate.
type RevocationCertificateSource = string | Uint8Array | ParsedCertificateRevocationCheckGoodValue
Certificate is not revoked according to the checked evidence.
interface RevocationCheckGoodValue {
readonly status: Extract<RevocationStatus, good>;
readonly kind: RevocationEvidenceKind;
readonly message: string;
}Properties
readonlystatus:Extract<RevocationStatus,good> — Certificate is not revoked.readonlykind:RevocationEvidenceKind— Which evidence kind confirmed the good status.readonlymessage:string— Human-readable diagnostic message.
RevocationCheckIndeterminateValue
Revocation status could not be determined from the provided evidence.
interface RevocationCheckIndeterminateValue {
readonly status: Extract<RevocationStatus, indeterminate>;
readonly code: CheckCertificateRevocationErrorCode;
readonly message: string;
readonly details: CheckCertificateRevocationFailureDetails;
}Properties
readonlystatus:Extract<RevocationStatus,indeterminate> — Status is indeterminate.readonlycode:CheckCertificateRevocationErrorCode— Why revocation status is indeterminate.readonlymessage:string— Human-readable diagnostic message.readonlydetails:CheckCertificateRevocationFailureDetails— What evidence was attempted and why each failed.
RevocationCheckRevokedValue
Certificate is revoked according to the checked evidence.
interface RevocationCheckRevokedValue {
readonly status: Extract<RevocationStatus, revoked>;
readonly kind: RevocationEvidenceKind;
readonly message: string;
readonly revokedAt?: Date;
readonly revocationReason?: RevocationReason;
readonly revocationReasonCode?: number;
}Properties
readonlystatus:Extract<RevocationStatus,revoked> — Certificate is revoked.readonlykind:RevocationEvidenceKind— Which evidence kind reported the revocation.readonlymessage:string— Human-readable diagnostic message.readonlyrevokedAt?:Date— When the certificate was revoked (from CRL entry or OCSP response).readonlyrevocationReason?:RevocationReason— CRL reason string (from CRL evidence).readonlyrevocationReasonCode?:number— CRL reason integer code (from OCSP evidence).
RevocationCrlEvidenceInput
CRL-based revocation evidence for CheckCertificateRevocationInput.evidence.
interface RevocationCrlEvidenceInput {
readonly kind: crl;
readonly crl: CrlSource;
readonly deltaCrl?: CrlSource;
}Properties
readonlykind:crl— Discriminator for the CRL evidence variant.readonlycrl:CrlSource— Complete (base) CRL.readonlydeltaCrl?:CrlSource— Optional delta CRL for more recent revocation information.
RevocationEvidenceInput
Discriminated union of CRL and OCSP evidence inputs.
type RevocationEvidenceInput = RevocationCrlEvidenceInput | RevocationOcspEvidenceInputRevocationEvidenceKind
Which revocation mechanism produced the evidence.
type RevocationEvidenceKind = crl | ocspRevocationExecutionError
Errors encountered while processing revocation evidence.
Distinct from RevocationIndeterminateReason: execution errors are code failures (malformed CRL, unsupported extension) rather than evaluation outcomes (CRL doesn't cover this certificate).
Collected in CheckChainRevocationValue.executionErrors.
interface RevocationExecutionError {
readonly kind: parse_error | unsupported_extension | internal_error;
readonly message: string;
readonly evidenceIdentifier?: string;
}Properties
readonlykind:parse_error|unsupported_extension|internal_error— Error category.readonlymessage:string— Human-readable error description.readonlyevidenceIdentifier?:string— Which evidence caused the error (e.g., CRL issuer DN).
RevocationIndeterminateEvidence
One piece of evidence that failed to produce a definitive revocation answer.
interface RevocationIndeterminateEvidence {
readonly kind: RevocationEvidenceKind;
readonly code: RevocationIndeterminateReasonCode;
readonly message: string;
readonly reason?: CrlApplicabilityFailureReason;
}Properties
readonlykind:RevocationEvidenceKind— Whether this evidence was CRL or OCSP.readonlycode:RevocationIndeterminateReasonCode— Machine-readable reason code.readonlymessage:string— Human-readable explanation.readonlyreason?:CrlApplicabilityFailureReason— CRL-specific applicability failure reason, whenkindis'crl'.
RevocationIndeterminateReason
See the doc comment above REVOCATION_INDETERMINATE_REASONS.
type RevocationIndeterminateReason = (typeof REVOCATION_INDETERMINATE_REASONS)[number]RevocationIndeterminateReasonCode
Why a particular piece of evidence could not produce a definitive good/revoked answer.
type RevocationIndeterminateReasonCode = (typeof REVOCATION_INDETERMINATE_REASON_CODES)[number]RevocationOcspEvidenceInput
OCSP-based revocation evidence for CheckCertificateRevocationInput.evidence.
interface RevocationOcspEvidenceInput {
readonly kind: ocsp;
readonly response: string | Uint8Array | ParsedOcspResponse;
readonly request?: OcspRequestSource;
readonly responderCertificate?: OcspCertificateSource;
}Properties
readonlykind:ocsp— Discriminator for the OCSP evidence variant.readonlyresponse:string|Uint8Array|ParsedOcspResponse— OCSP response to validate.readonlyrequest?:OcspRequestSource— Original OCSP request — enables nonce and coverage checks.readonlyresponderCertificate?:OcspCertificateSource— Explicit responder certificate — overrides embedded certificate discovery.
RevocationPolicy
Revocation checking policy for checkChainRevocation.
Controls how indeterminate results (missing evidence, expired CRLs) affect the final decision.
interface RevocationPolicy {
readonly mode?: soft-fail | hard-fail;
readonly prefer?: ocsp | crl | best-available;
readonly ocspResponderRevocation?: OcspResponderRevocationPolicy;
}Properties
readonlymode?:soft-fail|hard-fail— How to handle indeterminate status.'hard-fail': indeterminate certificates cause denial (default)'soft-fail': indeterminate certificates are allowed — an explicit availability/compatibility choice
Revocation checking itself is opt-in: no check runs unless evidence is supplied. Once it is, indeterminate status denies by default.
readonlyprefer?:ocsp|crl|best-available— Evidence preference when multiple sources are available.Both evidence kinds are always evaluated, and a validated
revokedverdict from either source wins regardless of preference (fail-closed). Preference only decides which source'sgoodverdict is reported when both yield one.'best-available': the source with the fresher evidence — the laterthisUpdateon the validated OCSP entry or CRL — is reported; ties favor OCSP (default)'ocsp': prefer OCSP over CRL'crl': prefer CRL over OCSP
readonlyocspResponderRevocation?:OcspResponderRevocationPolicy— Revocation policy for delegated OCSP responder certificates (RFC 6960 §4.2.2.2.1). Supplied CRLs double as responder revocation evidence. Defaults to'honor-nocheck'.
RevocationReason
RFC 5280 §5.3.1 CRLReason code values.
removeFromCRL is used in delta CRLs to un-hold a certificate.
type RevocationReason = unspecified | keyCompromise | cACompromise | affiliationChanged | superseded | cessationOfOperation | certificateHold | removeFromCRL | privilegeWithdrawn | aACompromiseRevocationSource
Identifies the source of revocation evidence.
Included in CertificateRevocationStatus's source when status is 'good' or 'revoked' to indicate which CRL or OCSP response provided the answer.
interface RevocationSource {
readonly kind: crl | ocsp;
readonly signerCertificate?: ParsedCertificate;
readonly evidenceIdentifier?: string;
readonly thisUpdate?: Date;
}Properties
readonlykind:crl|ocsp— Whether evidence came from a CRL or OCSP response.readonlysignerCertificate?:ParsedCertificate— Certificate that signed the evidence (CRL issuer or OCSP responder).readonlyevidenceIdentifier?:string— Identifier for debugging (e.g., CRL issuer DN or OCSP responder URL).readonlythisUpdate?:Date—thisUpdateof the evidence backing the verdict — the OCSP single response entry or the freshest contributing CRL (an applied delta CRL supersedes its base). This is the timestamp'best-available'compares.
RevocationStatus
Unified revocation outcome across CRL and OCSP evidence.
type RevocationStatus = good | revoked | indeterminateRevokedCertificateInput
Single revoked certificate entry for createCertificateRevocationList.
interface RevokedCertificateInput {
readonly serialNumber: Uint8Array;
readonly revocationDate?: Date;
readonly reasonCode?: RevocationReason;
readonly invalidityDate?: Date;
}Properties
readonlyserialNumber:Uint8Array— DER-encoded certificate serial number to revoke.readonlyrevocationDate?:Date— When the certificate was revoked. Defaults tothisUpdateof the CRL.readonlyreasonCode?:RevocationReason— RFC 5280 CRLReason code. Omit forunspecified.readonlyinvalidityDate?:Date— When the key or certificate became suspect — may predaterevocationDate.
ValidateCertificateRevocationListFailure
Failure detail for validateCertificateRevocationList.
Possible codes: signature_invalid, issuer_mismatch, stale_crl, crl_sign_not_permitted.
interface ValidateCertificateRevocationListFailure extends Micro509Error<signature_invalid | issuer_mismatch | stale_crl | crl_sign_not_permitted> {
readonly ok: false;
}Properties
readonlyok:false— Alwaysfalsefor failures.
ValidateCertificateRevocationListInput
Input for validateCertificateRevocationList.
interface ValidateCertificateRevocationListInput {
readonly crl: CrlSource;
readonly issuerCertificate: CrlCertificateSource;
readonly at?: Date;
readonly clockSkewMs?: number;
}Properties
readonlycrl:CrlSource— The CRL to validate.readonlyissuerCertificate:CrlCertificateSource— Certificate of the CA that should have signed the CRL.readonlyat?:Date— Evaluation time for freshness checks. Defaults tonew Date().readonlyclockSkewMs?:number— Tolerance in milliseconds for clock skew when checkingthisUpdate/nextUpdate.
ValidateCertificateRevocationListResult
Result of validateCertificateRevocationList.
On success, the CRL has passed signature, issuer, key-usage, and freshness checks.
type ValidateCertificateRevocationListResult = {
readonly ok: true;
readonly value: ParsedCertificateRevocationList
} | ErrorResult<signature_invalid | issuer_mismatch | stale_crl | crl_sign_not_permitted, Record<never, never>, ValidateCertificateRevocationListFailure>ValidateOcspResponseErrorCode
Failure codes produced by validateOcspResponse.
type ValidateOcspResponseErrorCode = response_status_invalid | signature_invalid | responder_id_mismatch | nonce_mismatch | request_mismatch | issuer_mismatch | responder_chain_invalid | ocsp_signing_missing | responder_revoked | responder_revocation_unknown | stale_responseValidateOcspResponseFailure
Failure detail for validateOcspResponse.
Possible codes: response_status_invalid, signature_invalid, responder_id_mismatch, nonce_mismatch, request_mismatch, issuer_mismatch, responder_chain_invalid, ocsp_signing_missing, responder_revoked, responder_revocation_unknown, stale_response.
interface ValidateOcspResponseFailure extends Micro509Error<ValidateOcspResponseErrorCode> {
readonly ok: false;
}Properties
readonlyok:false— Alwaysfalsefor failures.
ValidateOcspResponseInput
Input for validateOcspResponse.
interface ValidateOcspResponseInput {
readonly response: string | Uint8Array | ParsedOcspResponse;
readonly issuerCertificate: OcspCertificateSource;
readonly request?: OcspRequestSource;
readonly responderCertificate?: OcspCertificateSource;
readonly allowChainedResponderCertificate?: boolean;
readonly trustedOcspResponders?: readonly OcspCertificateSource[];
readonly responderRevocationPolicy?: OcspResponderRevocationPolicy;
readonly responderRevocationCrls?: readonly CrlSource[];
readonly at?: Date;
readonly clockSkewMs?: number;
}Properties
readonlyresponse:string|Uint8Array|ParsedOcspResponse— The OCSP response to validate.readonlyissuerCertificate:OcspCertificateSource— Certificate of the CA that issued the target certificate.readonlyrequest?:OcspRequestSource— Original request — enables nonce and request-coverage checks.readonlyresponderCertificate?:OcspCertificateSource— Explicit responder certificate — overrides embedded certificate discovery.readonlyallowChainedResponderCertificate?:boolean— Whentrue, allows delegated responder chain validation beyond direct issuance.readonlytrustedOcspResponders?:readonlyOcspCertificateSource[]— Explicitly trusted responder certificates for this issuer's scope (RFC 6960 §4.2.2.2 criterion 1 — local responder configuration).A response signer matching one of these certificates is accepted without the delegated-responder issuance, chain, EKU, and revocation checks. Signature verification and responder-ID binding are still enforced. Also consulted during responder discovery when the response embeds no matching certificate.
readonlyresponderRevocationPolicy?:OcspResponderRevocationPolicy— Revocation policy for delegated responder certificates. Defaults to'honor-nocheck'.readonlyresponderRevocationCrls?:readonlyCrlSource[]— CRLs used as revocation evidence for delegated responder certificates.readonlyat?:Date— Evaluation time for freshness checks and delegated responder chain validation. Defaults tonew Date().readonlyclockSkewMs?:number— Clock-skew tolerance in milliseconds forthisUpdate/nextUpdate/producedAt.
ValidateOcspResponseResult
Result of validateOcspResponse.
On success, the response has passed status, signature, responder binding, authorization (including responder revocation policy), freshness, nonce, and request-coverage checks.
type ValidateOcspResponseResult = {
readonly ok: true;
readonly value: ParsedOcspResponse
} | ErrorResult<ValidateOcspResponseErrorCode, Record<never, never>, ValidateOcspResponseFailure>VerifyCertificateRevocationListSignatureFailure
Failure detail when CRL signature verification fails.
interface VerifyCertificateRevocationListSignatureFailure extends Micro509Error<signature_invalid> {
readonly ok: false;
}Properties
readonlyok:false— Alwaysfalsefor failures.
VerifyCertificateRevocationListSignatureResult
Result of verifyCertificateRevocationListSignature.
On success, value is the parsed CRL whose signature has been verified.
type VerifyCertificateRevocationListSignatureResult = {
readonly ok: true;
readonly value: ParsedCertificateRevocationList
} | ErrorResult<signature_invalid, Record<never, never>, VerifyCertificateRevocationListSignatureFailure>VerifyOcspResponseSignatureFailure
Failure detail when OCSP response signature verification fails.
interface VerifyOcspResponseSignatureFailure extends Micro509Error<signature_invalid> {
readonly ok: false;
}Properties
readonlyok:false— Alwaysfalsefor failures.
VerifyOcspResponseSignatureResult
Result of verifyOcspResponseSignature.
On success, value is the parsed response whose signature has been verified.
type VerifyOcspResponseSignatureResult = {
readonly ok: true;
readonly value: ParsedOcspResponse
} | ErrorResult<signature_invalid, Record<never, never>, VerifyOcspResponseSignatureFailure>checkCertificateRevocation
Evaluates all provided CRL and OCSP evidence to determine the certificate's revocation status. Returns the first revoked if any, else the first good, else indeterminate with diagnostic details about each indeterminate evidence.
function checkCertificateRevocation(
input: CheckCertificateRevocationInput,
): Promise<CheckCertificateRevocationResult>Parameters
Examples
import { checkCertificateRevocation } from 'micro509';
const result = await checkCertificateRevocation({
certificate: leafPem,
issuerCertificate: caPem,
evidence: [{ kind: 'crl', crl: crlPem }],
});
if (result.ok && result.value.status === 'revoked') {
console.log('revoked at', result.value.revokedAt);
}checkCertificateRevocationAgainstCrl
End-to-end revocation check: validates the CRL (and optional delta CRL), verifies applicability via distribution-point and scope matching, then resolves the certificate's revocation status.
Returns good if the serial is absent, revoked with date/reason if present, or an error if the CRL cannot be validated or is non-applicable.
function checkCertificateRevocationAgainstCrl(
input: CheckCertificateRevocationAgainstCrlInput,
): Promise<CheckCertificateRevocationAgainstCrlResult>Parameters
Examples
import { checkCertificateRevocationAgainstCrl } from 'micro509';
const result = await checkCertificateRevocationAgainstCrl({
certificate: leafPem,
issuerCertificate: caPem,
crl: crlPem,
});
if (result.ok && result.value.status === 'revoked') {
console.log('revoked on', result.value.revocationDate);
}checkChainRevocation
Checks revocation status for all certificates in a validated chain.
Evaluates CRL and OCSP evidence against each certificate (except the trust anchor), applies the revocation policy, and returns a unified decision.
function checkChainRevocation(
input: CheckChainRevocationInput,
): Promise<CheckChainRevocationResult>Parameters
input:CheckChainRevocationInput
Examples
const result = await checkChainRevocation({
chain: validatedChain,
crls: [crl1, crl2],
ocspResponses: [ocspResponseDer],
policy: { mode: 'hard-fail' },
});
if (result.value.decision === 'deny') {
console.log('Revocation check failed');
}createCertificateRevocationList
Signs and encodes an X.509 v2 CRL.
Embeds Authority Key Identifier, CRLNumber, delta CRL indicator, issuing distribution point, and freshest-CRL extensions as configured.
function createCertificateRevocationList(
input: CreateCertificateRevocationListInput,
): Promise<CertificateRevocationListMaterial>Parameters
Examples
import { createCertificateRevocationList } from 'micro509';
const crl = await createCertificateRevocationList({
issuer: { commonName: 'Example CA' },
signerPrivateKey: caPrivateKey,
issuerPublicKey: caPublicKey,
thisUpdate: new Date('2025-01-01'),
nextUpdate: new Date('2025-02-01'),
crlNumber: 42,
revokedCertificates: [
{ serialNumber: revokedSerial, reasonCode: 'keyCompromise' },
],
});
// crl.pem, crl.der, crl.base64createOcspRequest
Builds a DER-encoded OCSP request containing one or more CertID entries and an optional nonce extension.
function createOcspRequest(
input: CreateOcspRequestInput,
): Promise<OcspRequestMaterial>Parameters
input:CreateOcspRequestInput
Examples
import { createOcspRequest } from 'micro509';
const req = await createOcspRequest({
requests: [{ certificate: leafPem, issuerCertificate: caPem }],
hashAlgorithm: 'SHA-256',
nonce: crypto.getRandomValues(new Uint8Array(16)),
});
// POST req.der to the OCSP responder URIcreateOcspResponse
Signs and encodes an OCSP BasicResponse with a successful status.
The responder is identified by key hash (SHA-1 of the signer's SubjectPublicKey). Use includedCertificates to embed the responder's chain for relying parties.
function createOcspResponse(
input: CreateOcspResponseInput,
): Promise<OcspResponseMaterial>Parameters
input:CreateOcspResponseInput
Examples
import { createOcspResponse } from 'micro509';
const resp = await createOcspResponse({
signerPrivateKey: responderPrivateKey,
signerCertificate: responderCertPem,
responses: [
{
certificate: leafPem,
issuerCertificate: caPem,
certStatus: 'good',
thisUpdate: new Date('2025-01-01'),
nextUpdate: new Date('2025-01-08'),
},
],
nonce: requestNonce,
});
// resp.der, resp.pem, resp.base64getCertificateOcspResponderUris
Extracts OCSP responder URIs from the certificate's Authority Information Access extension.
function getCertificateOcspResponderUris(
certificate: RevocationCertificateSource,
): readonly string[]Parameters
certificate:RevocationCertificateSource
hasOcspNoCheckExtension
Reports whether a certificate carries the id-pkix-ocsp-nocheck extension (RFC 6960 §4.2.2.2.1) — the CA's assertion that relying parties may trust this OCSP responder certificate for its lifetime without revocation checks.
function hasOcspNoCheckExtension(
certificate: OcspCertificateSource,
): booleanParameters
certificate:OcspCertificateSource
isCertificateRevoked
Quick serial-number lookup — returns true if the serial appears in the CRL's revoked entries. Does not validate the CRL or check applicability.
function isCertificateRevoked(
certificateSerialNumber: Uint8Array | string,
crl: ParsedCertificateRevocationList,
): booleanParameters
certificateSerialNumber:Uint8Array|stringcrl:ParsedCertificateRevocationList
parseCertificateRevocationListDer
Decodes a DER-encoded X.509 CRL into a structured ParsedCertificateRevocationList.
Returns a typed failure (code: 'malformed') on malformed input. For the throwing form use parseCertificateRevocationListDerOrThrow. Does not verify the signature — call verifyCertificateRevocationListSignature or validateCertificateRevocationList for that.
function parseCertificateRevocationListDer(
der: Uint8Array,
): ParseCertificateRevocationListResultParameters
der:Uint8Array
parseCertificateRevocationListDerOrThrow
Throwing core for parseCertificateRevocationListDer.
Does not verify the signature — call verifyCertificateRevocationListSignature or validateCertificateRevocationList for that.
function parseCertificateRevocationListDerOrThrow(
der: Uint8Array,
): ParsedCertificateRevocationListParameters
der:Uint8Array
parseCertificateRevocationListPem
Decodes a PEM-encoded X.509 CRL (-----BEGIN X509 CRL-----).
Returns a typed failure (code: 'malformed') on malformed input. For the throwing form use parseCertificateRevocationListPemOrThrow.
function parseCertificateRevocationListPem(
pem: string,
): ParseCertificateRevocationListResultParameters
pem:string
parseCertificateRevocationListPemOrThrow
Decodes a PEM-encoded X.509 CRL (-----BEGIN X509 CRL-----).
function parseCertificateRevocationListPemOrThrow(
pem: string,
): ParsedCertificateRevocationListParameters
pem:string
Examples
import { parseCertificateRevocationListPemOrThrow } from 'micro509';
const crl = parseCertificateRevocationListPemOrThrow(pemString); // throws if malformed
console.log(crl.issuer.values.commonName, crl.revokedCertificates.length);parseOcspRequestDer
Decodes a DER-encoded OCSP request into a structured ParsedOcspRequest.
Returns a typed failure (code: 'malformed') on malformed input. For the throwing form use parseOcspRequestDerOrThrow.
function parseOcspRequestDer(
der: Uint8Array,
): ParseOcspRequestResultParameters
der:Uint8Array
parseOcspRequestDerOrThrow
Throwing core for parseOcspRequestDer.
function parseOcspRequestDerOrThrow(
der: Uint8Array,
): ParsedOcspRequestParameters
der:Uint8Array
parseOcspRequestPem
Decodes a PEM-encoded OCSP request (-----BEGIN OCSP REQUEST-----).
Returns a typed failure (code: 'malformed') on malformed input. For the throwing form use parseOcspRequestPemOrThrow.
function parseOcspRequestPem(
pem: string,
): ParseOcspRequestResultParameters
pem:string
parseOcspRequestPemOrThrow
Decodes a PEM-encoded OCSP request (-----BEGIN OCSP REQUEST-----).
function parseOcspRequestPemOrThrow(
pem: string,
): ParsedOcspRequestParameters
pem:string
parseOcspResponseDer
Decodes a DER-encoded OCSP response into a structured ParsedOcspResponse.
Returns a typed failure (code: 'malformed') on malformed input. For the throwing form use parseOcspResponseDerOrThrow.
function parseOcspResponseDer(
der: Uint8Array,
): ParseOcspResponseResultParameters
der:Uint8Array
parseOcspResponseDerOrThrow
Throwing core for parseOcspResponseDer.
function parseOcspResponseDerOrThrow(
der: Uint8Array,
): ParsedOcspResponseParameters
der:Uint8Array
parseOcspResponsePem
Decodes a PEM-encoded OCSP response (-----BEGIN OCSP RESPONSE-----).
Returns a typed failure (code: 'malformed') on malformed input. For the throwing form use parseOcspResponsePemOrThrow.
function parseOcspResponsePem(
pem: string,
): ParseOcspResponseResultParameters
pem:string
parseOcspResponsePemOrThrow
Decodes a PEM-encoded OCSP response (-----BEGIN OCSP RESPONSE-----).
function parseOcspResponsePemOrThrow(
pem: string,
): ParsedOcspResponseParameters
pem:string
Examples
import { parseOcspResponsePemOrThrow } from 'micro509';
const resp = parseOcspResponsePemOrThrow(pemString);
if (resp.responseStatus === 'successful') {
for (const entry of resp.responses ?? []) {
console.log(entry.certId.serialNumberHex, entry.certStatus);
}
}REVOCATION_INDETERMINATE_REASON_CODES
Every RevocationIndeterminateReasonCode, as a runtime array.
const REVOCATION_INDETERMINATE_REASON_CODES: certificate_status_missing | certificate_status_unknown | crl_sign_not_permitted | issuer_mismatch | non_applicable | nonce_mismatch | ocsp_signing_missing | request_mismatch | responder_id_mismatch | responder_chain_invalid | responder_revoked | responder_revocation_unknown | response_status_invalid | signature_invalid | stale_crl | stale_response[]REVOCATION_INDETERMINATE_REASONS
Granular reasons why revocation status could not be determined.
Returned in CertificateRevocationStatus's indeterminateReasons when status is 'indeterminate'. Grouped by category:
- Evidence not found:
no_applicable_crl,no_applicable_ocsp - Scope mismatch:
distribution_point_mismatch,issuer_name_mismatch,reason_scope_mismatch,indirect_crl_scope_mismatch,reason_coverage_incomplete - Signer trust:
crl_signer_not_found,crl_signer_not_authorized,crl_signer_revoked,crl_signer_indeterminate, and OCSP equivalents - Freshness:
crl_expired,ocsp_response_expired
const REVOCATION_INDETERMINATE_REASONS: no_applicable_crl | no_applicable_ocsp | distribution_point_mismatch | issuer_name_mismatch | reason_scope_mismatch | indirect_crl_scope_mismatch | reason_coverage_incomplete | crl_signer_not_found | crl_signer_not_authorized | crl_signer_revoked | crl_signer_indeterminate | ocsp_responder_not_found | ocsp_responder_not_authorized | ocsp_responder_revoked | ocsp_responder_indeterminate | crl_expired | ocsp_response_expired | ocsp_status_unknown[]resolveOcspResponderCandidates
Merges configured OCSP responders with those discovered from the certificate's AIA extension. Configured responders take priority; duplicates are deduplicated by URI.
function resolveOcspResponderCandidates(
input: ResolveOcspResponderCandidatesInput,
): readonly OcspResponderCandidate[]Parameters
validateCertificateRevocationList
Full CRL validation: issuer name match, authority key identifier match, cRLSign key-usage check, signature verification, and thisUpdate/nextUpdate freshness check (with optional clock-skew tolerance).
function validateCertificateRevocationList(
input: ValidateCertificateRevocationListInput,
): Promise<ValidateCertificateRevocationListResult>Parameters
validateOcspResponse
Full OCSP response validation: response status check, signature verification, responder ID binding (byName or byKeyHash), delegated-responder chain and ocspSigning EKU checks, producedAt/thisUpdate/nextUpdate freshness, nonce match, and request-coverage completeness.
function validateOcspResponse(
input: ValidateOcspResponseInput,
): Promise<ValidateOcspResponseResult>Parameters
input:ValidateOcspResponseInput
Examples
import { validateOcspResponse } from 'micro509';
const result = await validateOcspResponse({
response: ocspResponseDer,
issuerCertificate: caPem,
request: ocspRequestDer,
});
if (result.ok) {
const entry = result.value.responses?.[0];
console.log(entry?.certStatus); // 'good' | 'revoked' | 'unknown'
}verifyCertificateRevocationListSignature
Verifies the CRL signature against the issuer certificate's public key.
Does not check issuer name match, key-usage, or freshness — use validateCertificateRevocationList for full validation.
function verifyCertificateRevocationListSignature(
crl: string | Uint8Array,
issuerCertificate: string | Uint8Array,
): Promise<VerifyCertificateRevocationListSignatureResult>Parameters
crl:string|Uint8ArrayissuerCertificate:string|Uint8Array
verifyOcspResponseSignature
Verifies the OCSP response signature against the given signer certificate.
Does not check responder binding, freshness, or nonce — use validateOcspResponse for full validation.
function verifyOcspResponseSignature(
response: string | Uint8Array | ParsedOcspResponse,
signerCertificate: OcspCertificateSource,
): Promise<VerifyOcspResponseSignatureResult>Parameters
response:string|Uint8Array|ParsedOcspResponsesignerCertificate:OcspCertificateSource
BuildCandidatePathInput
Input for buildCandidatePath.
interface BuildCandidatePathInput {
readonly leaf: CertificateSource;
readonly intermediates?: readonly CertificateSource[];
readonly roots: readonly CertificateSource[];
readonly trustAnchors?: readonly TrustAnchor[];
readonly at?: Date;
}Properties
readonlyleaf:CertificateSource— End-entity certificate to verify.readonlyintermediates?:readonlyCertificateSource[]— Intermediate CA certificates available for path building. Order does not matter.readonlyroots:readonlyCertificateSource[]— Trusted root CA certificates. At least one root or trust anchor must be supplied.readonlytrustAnchors?:readonlyTrustAnchor[]— Bare trust anchors to try when no root certificate matches.readonlyat?:Date— Validation time. Defaults tonew Date().
BuildCandidatePathResult
Result of buildCandidatePath. On success, contains the CandidatePath.
type BuildCandidatePathResult = {
readonly ok: true;
readonly value: CandidatePath
} | IndexedErrorResult<VerifyErrorCode, VerifyFailureDetails, VerifyChainFailure>CandidatePath
A signature-verified certification path from leaf to root, before constraint validation.
interface CandidatePath {
readonly leaf: ParsedCertificate;
readonly chain: readonly ParsedCertificate[];
readonly root: ParsedCertificate;
readonly anchorCertificateInChain: boolean;
}Properties
readonlyleaf:ParsedCertificate— Parsed end-entity certificate.readonlychain:readonlyParsedCertificate[]— Full chain in leaf-to-root order (includes both leaf and root).readonlyroot:ParsedCertificate— Trusted root that terminates the path.readonlyanchorCertificateInChain:boolean—truewhenCandidatePath.rootis a trusted root certificate included inCandidatePath.chain;falsewhen a bare trust anchor verified the terminal certificate, which stays a path certificate.
CertificateSource
PEM string or DER bytes for a certificate. PEM may contain multiple blocks.
type CertificateSource = string | Uint8ArrayChainRevocationInput
Input for chain-level revocation checking in verifyCertificateChain.
interface ChainRevocationInput {
readonly crls?: readonly CrlSource[];
readonly ocspResponses?: readonly (string | Uint8Array)[];
readonly extraCertificates?: readonly RevocationCertificateSource[];
readonly trustedOcspResponders?: readonly RevocationCertificateSource[];
readonly policy?: RevocationPolicy;
}Properties
readonlycrls?:readonlyCrlSource[]— CRLs to evaluate.readonlyocspResponses?:readonly(string|Uint8Array)[]— OCSP responses to evaluate (PEM strings or DER bytes).readonlyextraCertificates?:readonlyRevocationCertificateSource[]— Extra certs for indirect CRL issuers / delegated OCSP responders.readonlytrustedOcspResponders?:readonlyRevocationCertificateSource[]— Explicitly trusted OCSP responder certificates (RFC 6960 §4.2.2.2 criterion 1).readonlypolicy?:RevocationPolicy— Revocation policy.
ConstrainedPolicy
One policy OID that survives RFC 5280 / RFC 9618 processing.
interface ConstrainedPolicy {
readonly policyIdentifier: string;
readonly policyQualifiers?: readonly PolicyQualifierInfo[];
}Properties
readonlypolicyIdentifier:string— Dotted-decimal OID of the surviving policy.readonlypolicyQualifiers?:readonlyPolicyQualifierInfo[]— Qualifier info (CPS URIs, user notices) attached to this policy, if any.
CsrSource
PEM string or DER bytes for a certificate signing request.
type CsrSource = string | Uint8ArrayDnsServiceIdentityInput
DNS hostname reference identifier.
interface DnsServiceIdentityInput {
readonly type: dns;
readonly value: string;
readonly allowCommonNameFallback?: boolean;
}Properties
readonlytype:dns— Discriminant for DNS hostname matching.readonlyvalue:string— The hostname to match (e.g."mail.example.com"). Wildcard labels in the certificate are handled internally.readonlyallowCommonNameFallback?:boolean— Whentrue, falls back to the subject CN if the SAN extension has no dns/uri/srv entries. Suppressed when any supported SAN type is present.
EkuCheckFailure
Failure from checkExtendedKeyUsage with the chain index of the certificate that failed.
interface EkuCheckFailure extends Micro509Error<leaf_eku_missing | intermediate_eku_constraint> {
readonly ok: false;
readonly index: number;
}Properties
readonlyok:false— Alwaysfalsefor failures.readonlyindex:number— Zero-based index into the chain of the certificate that lacks the required EKU.
EkuCheckPurpose
Extended key usage purpose checked by checkExtendedKeyUsage.
type EkuCheckPurpose = serverAuth | clientAuth | codeSigning | emailProtection | timeStamping | ocspSigningEkuCheckResult
Result of checkExtendedKeyUsage. Success carries no value; failure identifies the offending certificate.
type EkuCheckResult = {
readonly ok: true;
readonly value: undefined
} | IndexedErrorResult<leaf_eku_missing | intermediate_eku_constraint, Record<never, never>, EkuCheckFailure>InitialNameConstraintsInput
Input for createNameConstraintValidationState.
Seeds the name-constraint engine with trust-anchor-level subtree restrictions that apply before any certificate in the chain is processed.
interface InitialNameConstraintsInput {
readonly permittedSubtrees?: readonly GeneralSubtree[];
readonly excludedSubtrees?: readonly GeneralSubtree[];
}Properties
readonlypermittedSubtrees?:readonlyGeneralSubtree[]— Subtrees within which all subsequent subject names must fall. Default: unconstrained.readonlyexcludedSubtrees?:readonlyGeneralSubtree[]— Subtrees that no subsequent subject name may fall within. Default: none.
IpServiceIdentityInput
IP address reference identifier.
interface IpServiceIdentityInput {
readonly type: ip;
readonly value: string;
}Properties
readonlytype:ip— Discriminant for IP address matching.readonlyvalue:string— IPv4 or IPv6 address string. Normalized before comparison.
MatchServiceIdentityErrorCode
Discriminant codes for identity-matching failures.
type MatchServiceIdentityErrorCode = subject_alt_name_mismatch | common_name_fallback_suppressed | service_identity_mismatch | unsupported_service_identity_typeMatchServiceIdentityFailure
A failed identity-matching attempt.
interface MatchServiceIdentityFailure extends Micro509Error<MatchServiceIdentityErrorCode, MatchServiceIdentityFailureDetails> {
readonly ok: false;
}Properties
readonlyok:false— Alwaysfalsefor failures.
MatchServiceIdentityFailureDetails
Diagnostic context attached to an identity-matching failure.
interface MatchServiceIdentityFailureDetails {
readonly subjectCommonName?: string;
readonly expected?: string;
readonly actual?: string;
readonly presentedIdentifierTypes?: readonly (dns | uri | srv)[];
readonly commonNameFallbackReason?: disabled | suppressed_by_presented_identifier | common_name_missing | common_name_mismatch;
}Properties
readonlysubjectCommonName?:string— CN of the certificate that was being matched, if present.readonlyexpected?:string— The reference identifier the caller asked to verify.readonlyactual?:string— Comma-joined presented identifiers (from SAN) that were compared.readonlypresentedIdentifierTypes?:readonly(dns|uri|srv)[]— SAN types that were present, relevant to CN-fallback suppression logic.readonlycommonNameFallbackReason?:disabled|suppressed_by_presented_identifier|common_name_missing|common_name_mismatch— Explains why CN fallback was not used or failed.
MatchServiceIdentityFailureResult
Failure branch of MatchServiceIdentityResult with structured error details.
type MatchServiceIdentityFailureResult = ErrorResult<MatchServiceIdentityErrorCode, MatchServiceIdentityFailureDetails, MatchServiceIdentityFailure>MatchServiceIdentityInput
Input for matchServiceIdentity.
interface MatchServiceIdentityInput {
readonly certificate: ParsedCertificate;
readonly serviceIdentity: ServiceIdentityInput;
}Properties
readonlycertificate:ParsedCertificate— The parsed leaf certificate to check.readonlyserviceIdentity:ServiceIdentityInput— The reference identifier the client wants to verify.
MatchServiceIdentityResult
Result of matching a reference identifier against a certificate's presented identifiers.
type MatchServiceIdentityResult = MatchServiceIdentitySuccess | MatchServiceIdentityFailureResultMatchServiceIdentitySuccess
A successful identity match (the certificate covers the requested name).
interface MatchServiceIdentitySuccess {
readonly ok: true;
readonly value: undefined;
}Properties
readonlyok:true— Alwaystruefor success.readonlyvalue:undefined— No payload on success — the match itself is the signal.
PolicyValidationInput
Input for the policy-validation engine.
All fields are optional — omitted values produce the most permissive behavior (accept any policy, allow mappings, allow anyPolicy).
interface PolicyValidationInput {
readonly initialPolicySet?: readonly string[] | any;
readonly requireExplicitPolicy?: boolean;
readonly inhibitPolicyMapping?: boolean;
readonly inhibitAnyPolicy?: boolean;
}Properties
readonlyinitialPolicySet?:readonlystring``[]|any— OIDs the relying party considers acceptable, or'any'to accept whatever the chain asserts. Default:'any'.readonlyrequireExplicitPolicy?:boolean— Whentrue, the chain must assert at least one acceptable policy. Default:false.readonlyinhibitPolicyMapping?:boolean— Whentrue, policy mappings in CA certificates are ignored. Default:false.readonlyinhibitAnyPolicy?:boolean— Whentrue, the anyPolicy OID is not treated as matching all policies. Default:false.
PolicyValidationOutcome
Final policy outputs exposed by successful path-validation APIs.
interface PolicyValidationOutcome {
readonly authorityConstrainedPolicies: readonly ConstrainedPolicy[];
readonly userConstrainedPolicies: readonly ConstrainedPolicy[];
}Properties
readonlyauthorityConstrainedPolicies:readonlyConstrainedPolicy[]— Policies valid under the authority's (CA chain) constraints alone.readonlyuserConstrainedPolicies:readonlyConstrainedPolicy[]— Policies that also satisfy the caller'sPolicyValidationInput.initialPolicySet.
ServiceIdentityInput
Discriminated union of all supported reference identifier types.
type ServiceIdentityInput = DnsServiceIdentityInput | IpServiceIdentityInput | UriServiceIdentityInput | SrvServiceIdentityInputServiceIdentityType
The type discriminant values of ServiceIdentityInput.
type ServiceIdentityType = ServiceIdentityInput[type]SrvServiceIdentityInput
SRV-ID reference identifier (RFC 4985).
interface SrvServiceIdentityInput {
readonly type: srv;
readonly value: string;
}Properties
readonlytype:srv— Discriminant for SRV-ID matching.readonlyvalue:string— SRV name in_service.domainform (e.g."_imap.example.com").
TrustAnchor
Bare trust anchor — subject identity and public key material without a full certificate. Used when the root CA certificate is unavailable but its key is known. Build from a certificate with trustAnchorFromCertificate.
interface TrustAnchor {
readonly subject: ParsedName;
readonly subjectPublicKeyInfoDer: Uint8Array;
readonly publicKeyAlgorithmOid: string;
readonly publicKeyParametersOid?: string;
readonly subjectKeyIdentifier?: string;
}Properties
readonlysubject:ParsedName— Parsed subject distinguished name. Used for semantic issuer matching (RFC 5280 §7.1).readonlysubjectPublicKeyInfoDer:Uint8Array— DER-encoded SubjectPublicKeyInfo used to verify signatures from this anchor.readonlypublicKeyAlgorithmOid:string— OID of the public key algorithm (e.g.1.2.840.10045.2.1for EC).readonlypublicKeyParametersOid?:string— OID of the key parameters, when algorithm-specific (e.g. named curve OID for EC).readonlysubjectKeyIdentifier?:string— Hex-encoded subject key identifier for AKI matching.
UriServiceIdentityInput
URI-ID reference identifier (RFC 6125 §6.5). Scheme and host are matched.
interface UriServiceIdentityInput {
readonly type: uri;
readonly value: string;
}Properties
readonlytype:uri— Discriminant for URI-ID matching.readonlyvalue:string— Full URI whose scheme and reg-name will be compared.
ValidateCandidatePathInput
Input for validateCandidatePath.
interface ValidateCandidatePathInput extends PolicyValidationInput, InitialNameConstraintsInput {
readonly policy?: PolicyValidationInput;
readonly nameConstraints?: InitialNameConstraintsInput;
readonly chain: readonly ParsedCertificate[];
readonly anchorCertificateInChain?: boolean;
readonly at?: Date;
readonly purpose?: VerifyPurpose;
readonly allowSelfSignedLeaf?: boolean;
}Properties
readonlypolicy?:PolicyValidationInput— Nested policy validation overrides (takes precedence over flat fields).readonlynameConstraints?:InitialNameConstraintsInput— Nested name constraint overrides (takes precedence over flat fields).readonlychain:readonlyParsedCertificate[]— Pre-built certificate chain in leaf-to-root order.readonlyanchorCertificateInChain?:boolean— Whether the terminal certificate inchainis the trust anchor (and so is excluded from policy processing). Defaults totrue, matching a chain that ends at a root certificate. Setfalsewhen a bare trust anchor verified the terminal certificate, which then must be processed as a path certificate.readonlyat?:Date— Validation time. Defaults tonew Date().readonlypurpose?:VerifyPurpose— Leaf purpose constraint to enforce.readonlyallowSelfSignedLeaf?:boolean— Whentrue, allows a self-signed leaf that is also the root. Defaults tofalse.
ValidateCandidatePathResult
Result of validateCandidatePath.
type ValidateCandidatePathResult = {
readonly ok: true;
readonly value: ValidateCandidatePathSuccess
} | IndexedErrorResult<VerifyErrorCode, VerifyFailureDetails, VerifyChainFailure>ValidateCandidatePathSuccess
Success payload from validateCandidatePath.
interface ValidateCandidatePathSuccess {
readonly policyValidation: PolicyValidationOutcome;
}Properties
readonlypolicyValidation:PolicyValidationOutcome— Final RFC 9618-constrained policy outputs for this validated path.
ValidateForCaInput
Input for validateForCa. Enforces basicConstraints.ca on the leaf.
interface ValidateForCaInput extends BuildCandidatePathInput, PolicyValidationInput, InitialNameConstraintsInput {
readonly policy?: PolicyValidationInput;
readonly nameConstraints?: InitialNameConstraintsInput;
}Properties
readonlypolicy?:PolicyValidationInput— Nested policy validation overrides.readonlynameConstraints?:InitialNameConstraintsInput— Nested name constraint overrides.
ValidateForCodeSigningInput
Input for validateForCodeSigning. Enforces codeSigning EKU.
interface ValidateForCodeSigningInput extends BuildCandidatePathInput, PolicyValidationInput, InitialNameConstraintsInput {
readonly policy?: PolicyValidationInput;
readonly nameConstraints?: InitialNameConstraintsInput;
}Properties
readonlypolicy?:PolicyValidationInput— Nested policy validation overrides.readonlynameConstraints?:InitialNameConstraintsInput— Nested name constraint overrides.
ValidateForTlsClientInput
Input for validateForTlsClient. Enforces clientAuth EKU.
interface ValidateForTlsClientInput extends BuildCandidatePathInput, PolicyValidationInput, InitialNameConstraintsInput {
readonly policy?: PolicyValidationInput;
readonly nameConstraints?: InitialNameConstraintsInput;
}Properties
readonlypolicy?:PolicyValidationInput— Nested policy validation overrides.readonlynameConstraints?:InitialNameConstraintsInput— Nested name constraint overrides.
ValidateForTlsServerInput
Input for validateForTlsServer. Enforces serverAuth EKU and optional DNS/IP identity matching.
interface ValidateForTlsServerInput extends BuildCandidatePathInput, PolicyValidationInput, InitialNameConstraintsInput {
readonly policy?: PolicyValidationInput;
readonly nameConstraints?: InitialNameConstraintsInput;
readonly leaf: CertificateSource;
readonly intermediates?: readonly CertificateSource[];
readonly roots: readonly CertificateSource[];
readonly trustAnchors?: readonly TrustAnchor[];
readonly at?: Date;
readonly serviceIdentity?: ServiceIdentityInput;
}Properties
readonlypolicy?:PolicyValidationInput— Nested policy validation overrides.readonlynameConstraints?:InitialNameConstraintsInput— Nested name constraint overrides.readonlyleaf:CertificateSource— End-entity certificate to verify.readonlyintermediates?:readonlyCertificateSource[]— Intermediate CA certificates.readonlyroots:readonlyCertificateSource[]— Trusted root CA certificates.readonlytrustAnchors?:readonlyTrustAnchor[]— Bare trust anchors.readonlyat?:Date— Validation time. Defaults tonew Date().readonlyserviceIdentity?:ServiceIdentityInput— DNS/IP identity to match against the leaf's SAN.
VerifiedCertificateChain
Fully verified certificate chain returned on success from verifyCertificateChain.
interface VerifiedCertificateChain {
readonly leaf: ParsedCertificate;
readonly chain: readonly ParsedCertificate[];
readonly root: ParsedCertificate;
readonly policyValidation: PolicyValidationOutcome;
}Properties
readonlyleaf:ParsedCertificate— Parsed end-entity certificate.readonlychain:readonlyParsedCertificate[]— Full chain in leaf-to-root order.readonlyroot:ParsedCertificate— Trusted root that terminates the path.readonlypolicyValidation:PolicyValidationOutcome— Final RFC 5280 §6 / RFC 9618 constrained policy outputs for this validated path.
VerifyCertificateChainInput
Input for verifyCertificateChain. Combines path-building, validation, and identity options.
interface VerifyCertificateChainInput extends PolicyValidationInput, InitialNameConstraintsInput {
readonly policy?: PolicyValidationInput;
readonly nameConstraints?: InitialNameConstraintsInput;
readonly leaf: CertificateSource;
readonly intermediates?: readonly CertificateSource[];
readonly roots: readonly CertificateSource[];
readonly trustAnchors?: readonly TrustAnchor[];
readonly at?: Date;
readonly purpose?: VerifyPurpose;
readonly serviceIdentity?: ServiceIdentityInput;
readonly allowSelfSignedLeaf?: boolean;
readonly revocation?: ChainRevocationInput;
}Properties
readonlypolicy?:PolicyValidationInput— Nested policy validation overrides.readonlynameConstraints?:InitialNameConstraintsInput— Nested name constraint overrides.readonlyleaf:CertificateSource— End-entity certificate to verify.readonlyintermediates?:readonlyCertificateSource[]— Intermediate CA certificates available for path building.readonlyroots:readonlyCertificateSource[]— Trusted root CA certificates.readonlytrustAnchors?:readonlyTrustAnchor[]— Bare trust anchors to try when no root certificate matches.readonlyat?:Date— Validation time. Defaults tonew Date().readonlypurpose?:VerifyPurpose— Leaf purpose constraint to enforce during validation.readonlyserviceIdentity?:ServiceIdentityInput— DNS/IP/URI/SRV identity to match against the leaf's SAN.readonlyallowSelfSignedLeaf?:boolean— Whentrue, allows a self-signed leaf. Defaults tofalse.readonlyrevocation?:ChainRevocationInput— Optional revocation checking.
VerifyChainFailure
A chain verification failure with its error code, human message, chain index, and diagnostic details.
interface VerifyChainFailure extends IndexedMicro509Error<VerifyErrorCode, VerifyFailureDetails> {
readonly ok: false;
}Properties
readonlyok:false— Alwaysfalsefor failures.
VerifyChainResult
Result of verifyCertificateChain. On success, contains the VerifiedCertificateChain.
type VerifyChainResult = {
readonly ok: true;
readonly value: VerifiedCertificateChain
} | IndexedErrorResult<VerifyErrorCode, VerifyFailureDetails, VerifyChainFailure>VerifyErrorCode
See the doc comment above VERIFY_ERROR_CODES for the meaning of each code.
type VerifyErrorCode = (typeof VERIFY_ERROR_CODES)[number]VerifyFailureDetails
Diagnostic context attached to every VerifyChainFailure. All fields are optional; presence depends on the error code.
interface VerifyFailureDetails {
readonly subjectCommonName?: string;
readonly issuerCommonName?: string;
readonly expected?: string;
readonly actual?: string;
readonly chainCommonNames?: readonly string[];
readonly presentedIdentifierTypes?: readonly (dns | uri | srv)[];
readonly commonNameFallbackReason?: disabled | suppressed_by_presented_identifier | common_name_missing | common_name_mismatch;
}Properties
readonlysubjectCommonName?:string— CN of the certificate that triggered the failure.readonlyissuerCommonName?:string— CN of the issuer of the offending certificate.readonlyexpected?:string— The value the verifier expected (e.g. a validity window bound or SKI).readonlyactual?:string— The value actually found.readonlychainCommonNames?:readonlystring``[]— CNs of every certificate in the chain, leaf-first. Present onno_trusted_root.readonlypresentedIdentifierTypes?:readonly(dns|uri|srv)[]— SAN identifier types the leaf actually presents. Set on identity-match failures.readonlycommonNameFallbackReason?:disabled|suppressed_by_presented_identifier|common_name_missing|common_name_mismatch— Why the CN-fallback path was not taken. Set oncommon_name_fallback_suppressed.
VerifyPurpose
High-level purpose applied during path validation to enforce leaf constraints.
type VerifyPurpose = serverAuth | clientAuth | caVerifyRequestFailure
Failure from verifyCertificateSigningRequest.
interface VerifyRequestFailure extends Micro509Error<signature_invalid | unsupported_signature_algorithm_parameters, VerifyFailureDetails> {
readonly ok: false;
}Properties
readonlyok:false— Alwaysfalsefor failures.
VerifyRequestResult
Result of verifyCertificateSigningRequest. On success, contains the parsed CSR.
type VerifyRequestResult = {
readonly ok: true;
readonly value: ParsedCertificateSigningRequest
} | ErrorResult<signature_invalid | unsupported_signature_algorithm_parameters, VerifyFailureDetails, VerifyRequestFailure>buildCandidatePath
Builds a signature-verified path from a leaf certificate to a trusted root.
Parses the supplied certificates, walks the issuer chain, signature-checks each link, and returns the first valid path. Does not enforce time, constraints, or leaf purpose — call validateCandidatePath or use the all-in-one verifyCertificateChain for full validation.
function buildCandidatePath(
input: BuildCandidatePathInput,
): Promise<BuildCandidatePathResult>Parameters
input:BuildCandidatePathInput
Examples
import { buildCandidatePath } from 'micro509';
const result = await buildCandidatePath({
leaf: leafPem,
intermediates: [intermediatePem],
roots: [rootPem],
});
if (result.ok) {
console.log('path length:', result.value.chain.length);
}checkExtendedKeyUsage
Standalone EKU check against a verified certificate chain. Validates that the leaf has the requested purpose and that intermediate CA EKU constraints (if present) permit it.
function checkExtendedKeyUsage(
chain: readonly ParsedCertificate[],
purpose: EkuCheckPurpose,
): EkuCheckResultParameters
chain:readonlyParsedCertificate[]purpose:EkuCheckPurpose
Examples
import { checkExtendedKeyUsage } from 'micro509';
const result = checkExtendedKeyUsage(chain, 'serverAuth');
if (!result.ok) {
console.error(result.error.code, result.error.message);
}matchCertificateServiceIdentity
Compares a reference identifier against a certificate's SAN entries.
Supports DNS (with wildcard matching), IP, URI-ID, and SRV-ID. For DNS, optionally falls back to subject CN when no SAN of a supported type is present.
function matchCertificateServiceIdentity(
rawCertificate: ParsedCertificate,
serviceIdentity: ServiceIdentityInput,
): MatchServiceIdentityResultParameters
rawCertificate:ParsedCertificateserviceIdentity:ServiceIdentityInput
Examples
const result = matchCertificateServiceIdentity(parsed, {
type: 'ip',
value: '192.168.1.1',
});const result = matchCertificateServiceIdentity(parsed, {
type: 'dns',
value: 'mail.example.com',
allowCommonNameFallback: true,
});matchServiceIdentity
Checks whether a certificate covers the requested service identity.
Delegates to matchCertificateServiceIdentity — this overload accepts a single options object.
function matchServiceIdentity(
input: MatchServiceIdentityInput,
): MatchServiceIdentityResultParameters
input:MatchServiceIdentityInput
Examples
const result = matchServiceIdentity({
certificate: parsed,
serviceIdentity: { type: 'dns', value: 'example.com' },
});
if (!result.ok) console.error(result.error.message);trustAnchorFromCertificate
Extracts a TrustAnchor from a parsed certificate, copying the subject, SPKI, and key identifiers.
function trustAnchorFromCertificate(
certificate: ParsedCertificate,
): TrustAnchorParameters
certificate:ParsedCertificate
VERIFY_ERROR_CODES
Discriminant for every failure a verify operation can produce.
no_trusted_root— chain could not be anchored to any root orTrustAnchor.issuer_not_found— an intermediate's issuer was not in the candidate set, or its issuer DN does not match the candidate issuer's subject DN.signature_invalid— a certificate's signature failed cryptographic verification.certificate_expired— a certificate's notBefore/notAfter window excludes the validation time.ca_required— an issuer lacksbasicConstraints.ca = true.key_cert_sign_required— an issuer has keyUsage but omitskeyCertSign.path_length_exceeded— the number of CA certificates below an issuer exceeds its pathLength.authority_key_identifier_mismatch— a certificate's AKI does not match the issuer's SKI.extended_key_usage_invalid— the leaf certificate lacks the required EKU for the requested purpose.subject_alt_name_mismatch— no SAN entry matches the requested service identity.common_name_fallback_suppressed— CN fallback was attempted but suppressed (SAN present or disabled).self_signed_leaf_not_allowed— the leaf is self-signed andallowSelfSignedLeafwas not set.unrecognized_critical_extension— a certificate contains a critical extension the verifier cannot process.intermediate_eku_constraint— an intermediate CA's EKU set does not include the required purpose.explicit_policy_required—requireExplicitPolicywas set but no acceptable policy was found.initial_policy_set_not_satisfied— the chain's policies do not intersectinitialPolicySet.unsupported_initial_name_constraints— caller-supplied initial name constraints use unsupported or malformed forms.unsupported_name_constraints— a certificate's nameConstraints use an unsupported form.name_constraints_violated— a subject name violates a permitted/excluded subtree.unsupported_signature_algorithm_parameters— the signature algorithm uses unrecognized parameters.certificate_revoked— revocation evidence confirms a chain certificate is revoked.revocation_indeterminate— revocation status could not be determined under a hard-fail policy.
const VERIFY_ERROR_CODES: no_trusted_root | issuer_not_found | signature_invalid | certificate_expired | ca_required | key_cert_sign_required | path_length_exceeded | authority_key_identifier_mismatch | extended_key_usage_invalid | subject_alt_name_mismatch | common_name_fallback_suppressed | self_signed_leaf_not_allowed | unrecognized_critical_extension | intermediate_eku_constraint | explicit_policy_required | initial_policy_set_not_satisfied | unsupported_initial_name_constraints | unsupported_name_constraints | name_constraints_violated | unsupported_signature_algorithm_parameters | certificate_revoked | revocation_indeterminate[]validateCandidatePath
Validates a pre-built certificate chain for time, constraints, policy, and optionally leaf purpose. Wrap the result of buildCandidatePath.
function validateCandidatePath(
input: ValidateCandidatePathInput,
): Promise<ValidateCandidatePathResult>Parameters
input:ValidateCandidatePathInput
validateForCa
Validates a certificate chain for CA use: chain verification + basicConstraints.ca check on the leaf.
function validateForCa(
input: ValidateForCaInput,
): Promise<VerifyChainResult>Parameters
input:ValidateForCaInput
Examples
import { validateForCa } from 'micro509';
const result = await validateForCa({
leaf: intermediateCertPem,
roots: [rootCaPem],
});validateForCodeSigning
Validates a certificate chain for code signing: chain verification + codeSigning EKU (leaf + intermediate propagation).
function validateForCodeSigning(
input: ValidateForCodeSigningInput,
): Promise<VerifyChainResult>Parameters
input:ValidateForCodeSigningInput
Examples
import { validateForCodeSigning } from 'micro509';
const result = await validateForCodeSigning({
leaf: codeSigningCertPem,
roots: [rootCaPem],
});validateForTlsClient
Validates a certificate chain for TLS client use: chain verification + clientAuth EKU (leaf + intermediate propagation).
function validateForTlsClient(
input: ValidateForTlsClientInput,
): Promise<VerifyChainResult>Parameters
input:ValidateForTlsClientInput
Examples
import { validateForTlsClient } from 'micro509';
const result = await validateForTlsClient({
leaf: clientCertPem,
roots: [rootCaPem],
});validateForTlsServer
Validates a certificate chain for TLS server use: chain verification + serverAuth EKU (leaf + intermediate propagation)
- DNS/IP identity matching.
function validateForTlsServer(
input: ValidateForTlsServerInput,
): Promise<VerifyChainResult>Parameters
input:ValidateForTlsServerInput
Examples
import { validateForTlsServer } from 'micro509';
const result = await validateForTlsServer({
leaf: serverCertPem,
roots: [rootCaPem],
serviceIdentity: { type: 'dns', value: 'example.com' },
});
if (result.ok) {
console.log('valid for', result.value.leaf.subject.values.commonName);
}verifyCertificateChain
All-in-one certificate chain verification: builds a candidate path then validates time, constraints, policy, purpose, and optional service identity.
Equivalent to calling buildCandidatePath followed by validateCandidatePath (plus identity matching when configured).
function verifyCertificateChain(
input: VerifyCertificateChainInput,
): Promise<VerifyChainResult>Parameters
input:VerifyCertificateChainInput
Examples
import { verifyCertificateChain } from 'micro509';
const result = await verifyCertificateChain({
leaf: serverCertPem,
intermediates: [intermediatePem],
roots: [rootCaPem],
purpose: 'serverAuth',
serviceIdentity: { type: 'dns', value: 'example.com' },
});
if (!result.ok) {
console.error(result.error.code, result.error.message);
}verifyCertificateSigningRequest
Verifies the self-signature of a PKCS#10 certificate signing request.
Parses the CSR from PEM or DER, then checks that its signature is valid against its own embedded public key.
function verifyCertificateSigningRequest(
input: CsrSource,
): Promise<VerifyRequestResult>Parameters
input:CsrSource
Examples
import { verifyCertificateSigningRequest } from 'micro509';
const result = await verifyCertificateSigningRequest(csrPem);
if (result.ok) {
console.log('subject:', result.value.subject.values.commonName);
}AuthorityInformationAccess
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 location: GeneralName;
}Properties
readonlymethod:ocsp|caIssuers| {readonlytype:oid;readonlyvalue:string} — Access method ('ocsp','caIssuers', or custom OID).readonlylocation:GeneralName— accessLocation GeneralName where the resource is available (usually a URI).
AuthorityInformationAccessInput
Builder input for one Authority Information Access entry.
Parsed AIA locations stay broad (AuthorityInformationAccess), but an 'ocsp' entry must supply a URI location, since RFC 6960 §3.1 defines the id-ad-ocsp location as a URI; directoryName is defined for caIssuers.
type AuthorityInformationAccessInput = {
readonly method: ocsp;
readonly location: {
readonly type: uri;
readonly value: string
}
} | {
readonly method: caIssuers | CustomAuthorityInfoAccessMethod;
readonly location: GeneralName
}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 AuthorityInformationAccessInput[];
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?:readonlyAuthorityInformationAccessInput[]— Authority Information Access — OCSP responder and CA issuer locations.readonlycrlDistributionPoints?:readonlyDistributionPoint[]— CRL Distribution Points — where to check revocation status.readonlycustomExtensions?:readonlyCustomExtension[]— Arbitrary extensions not covered by the built-in fields.
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 | ParsedCertificateCertificateMaterial
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.
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
})[]
}[]CreateCertificateErrorCode
Machine-readable reason a certificate builder rejected its construction input.
type CreateCertificateErrorCode = issuer_distinguished_name_empty | validity_not_after_before_not_beforeCreateCertificateInput
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.
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.).
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.
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).
DecodedExtensionMap
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.
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.
ExtendedKeyUsage
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
}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>>ExtensionEncoderErrorCode
Machine-readable reason an extension encoder rejected its construction input.
type ExtensionEncoderErrorCode = authority_info_access_empty | authority_info_access_ocsp_not_uri | certificate_policies_empty | crl_distribution_points_empty | directory_name_not_sequence | display_text_out_of_range | distribution_point_crl_issuer_empty | distribution_point_empty | distribution_point_full_name_empty | distribution_point_name_conflict | distribution_point_name_empty | duplicate_extension_oid | duplicate_policy_oid | extended_key_usage_empty | extension_not_supported_in_context | invalid_general_name_tag | invalid_ia5_string | invalid_ip_name_constraint | invalid_oid | key_usage_empty | name_constraints_empty | policy_constraints_empty | policy_mappings_any_policy | policy_mappings_empty | reserved_policy_qualifier_oidGeneralName
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
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.
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.
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.
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.
NameEncoderErrorCode
Machine-readable reason a distinguished-name encoder rejected its construction input.
type NameEncoderErrorCode = relative_distinguished_name_empty | unsupported_name_field | name_attribute_empty | name_attribute_too_long | invalid_country_codeNameFieldKey
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.
ParseCertificateChainResult
Success-or-failure result from parseCertificateChainPem.
type ParseCertificateChainResult<TMap extends ExtensionDecoderMap> = {
readonly ok: true;
readonly value: readonly ParsedCertificate<TMap>[]
} | ErrorResult<ParseCertificateErrorCode, Record<never, never>, ParseCertificateFailure>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.1) 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 — GeneralName access locations (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
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
}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.
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
}[]PolicyQualifierInfo
Discriminated union of all supported policy qualifier types.
type PolicyQualifierInfo = CpsPolicyQualifierInfo | UserNoticePolicyQualifierInfo | CustomPolicyQualifierInfoRelativeDistinguishedNameInput
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
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.
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.
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
}SubjectAltNameTextOptions
Options for subjectAltNameToString.
interface SubjectAltNameTextOptions {
readonly prefix?: boolean;
}Properties
readonlyprefix?:boolean— Prepend[subjectAltNameLabel](/api/x509#fn-subjectaltnamelabel):to the value, asopenssl x509 -textdoes. Defaults tofalse.
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.
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.
Asynchronous: hashing uses WebCrypto's crypto.subtle.digest. Await the returned promise before reading bytes, hex, or colonHex.
function certificateFingerprint(
certificate: CertificateFingerprintSource,
algorithm: CertificateFingerprintAlgorithm,
): Promise<CertificateFingerprint>Parameters
certificate:CertificateFingerprintSource— PEM string, DER bytes, or aParsedCertificate.algorithm:CertificateFingerprintAlgorithm— Digest algorithm to use. Defaults to'SHA-256'.
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);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');
}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,
});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);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' },
});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.
distinguishedNameToString
Renders a ParsedName as an RFC 4514 distinguished name string, e.g. CN=Example CA,O=Acme,C=US.
RDNs are emitted in reverse encoding order and multi-valued RDNs are joined with +, both per RFC 4514 §2. Attribute types outside the RFC 4514 §3 keyword table use the short names openssl prints, falling back to the dotted OID.
function distinguishedNameToString(
name: ParsedName,
): stringParameters
name:ParsedName
Examples
distinguishedNameToString(parsed.subject); // 'CN=example.com,O=Acme\\, Inc.,C=US'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. Returns a typed malformed failure for invalid PEM or certificate DER.
function parseCertificateChainPem<TMap extends ExtensionDecoderMap>(
pemBundle: string,
options?: ParseOptions<TMap>,
): ParseCertificateChainResult<TMap>Parameters
pemBundle:string— PEM text that may contain multiple CERTIFICATE blocks.options?:ParseOptions<TMap> — Custom extension decoders to apply during parsing.
parseCertificateChainPemOrThrow
Decode a PEM bundle containing one or more certificates, throwing on malformed input.
Non-CERTIFICATE blocks (e.g. private keys) are silently skipped.
function parseCertificateChainPemOrThrow<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.
Synchronous: returns a ParseCertificateResult directly. Do not await this function.
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.
relativeDistinguishedNameToString
Renders one ParsedRelativeDistinguishedName, joining a multi-valued RDN's attributes with +.
function relativeDistinguishedNameToString(
rdn: ParsedRelativeDistinguishedName,
): stringParameters
subjectAltNameLabel
The openssl x509 -text label for a SubjectAltName variant — DNS, IP Address, email, URI, SRV, DirName, or [tag <n>] for an unrecognized tag.
function subjectAltNameLabel(
name: SubjectAltName,
): stringParameters
name:SubjectAltName
subjectAltNameToString
Renders one SubjectAltName as text.
| variant | rendering |
|---|---|
dns, ip, email, uri, srv | the value itself |
directoryName | distinguishedNameToString of the embedded name, or the DER hex if it does not decode |
unknown | lowercase hex of the raw content bytes |
function subjectAltNameToString(
name: SubjectAltName,
options?: SubjectAltNameTextOptions,
): stringParameters
name:SubjectAltNameoptions?:SubjectAltNameTextOptions
Examples
Render every SAN of a parsed certificate
const names = (parsed.subjectAltNames ?? []).map((name) => subjectAltNameToString(name));
// ['example.com', '192.0.2.1', 'CN=Example CA,C=US']
subjectAltNameToString({ type: 'dns', value: 'example.com' }, { prefix: true }); // 'DNS:example.com'