Skip to content

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

ts
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 === true
ts
import {
	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.

ts
type DecryptRsaOaepErrorCode = invalid_key | decryption_failed

DecryptRsaOaepFailure

Structured failure payload for decryptRsaOaep.

ts
interface DecryptRsaOaepFailure extends Micro509Error<DecryptRsaOaepErrorCode> {
	readonly ok: false;
}

Properties

  • readonly ok: false — Always false for failures.

DecryptRsaOaepResult

Success-or-failure result returned by decryptRsaOaep.

ts
type DecryptRsaOaepResult = {
  readonly ok: true;
  readonly value: Uint8Array
} | ErrorResult<DecryptRsaOaepErrorCode, Record<never, never>, DecryptRsaOaepFailure>

EcKeyAlgorithmInput

ECDSA variant of KeyAlgorithmInput.

ts
interface EcKeyAlgorithmInput {
	readonly kind: ecdsa;
	readonly curve?: EcNamedCurve;
}

Properties

  • readonly kind: ecdsa — Discriminant selecting ECDSA key generation.
  • readonly curve?: EcNamedCurve — NIST curve. Defaults to 'P-256'.

EcNamedCurve

NIST elliptic curve for ECDSA keys.

ts
type EcNamedCurve = P-256 | P-384 | P-521

Ed25519KeyAlgorithmInput

Ed25519 variant of KeyAlgorithmInput.

ts
interface Ed25519KeyAlgorithmInput {
	readonly kind: ed25519;
}

Properties

  • readonly kind: ed25519 — Discriminant selecting Ed25519 key generation.

EncryptedPkcs8Options

PBES2 encryption options for the encrypted PKCS#8 export/import functions.

ts
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

  • readonly password: string — Password fed to PBKDF2 for key derivation.
  • readonly iterations?: number — PBKDF2 iteration count. Default: 100_000.
  • readonly salt?: Uint8Array — PBKDF2 salt. Default: 16 cryptographically random bytes.
  • readonly iv?: Uint8Array — AES-CBC initialization vector. Default: 16 cryptographically random bytes.
  • readonly cipher?: AES-128-CBC | AES-192-CBC | AES-256-CBC — AES-CBC cipher. Default: 'AES-256-CBC'.
  • readonly prf?: 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).

ts
type EncryptRsaOaepErrorCode = invalid_key | message_too_long

EncryptRsaOaepFailure

Structured failure payload for encryptRsaOaep.

ts
interface EncryptRsaOaepFailure extends Micro509Error<EncryptRsaOaepErrorCode> {
	readonly ok: false;
}

Properties

  • readonly ok: false — Always false for failures.

EncryptRsaOaepResult

Success-or-failure result returned by encryptRsaOaep.

ts
type EncryptRsaOaepResult = {
  readonly ok: true;
  readonly value: Uint8Array
} | ErrorResult<EncryptRsaOaepErrorCode, Record<never, never>, EncryptRsaOaepFailure>

ImportEcKeyInput

ECDSA variant of PublicKeyImportInput / PrivateKeyImportInput.

ts
interface ImportEcKeyInput {
	readonly kind: ecdsa;
	readonly curve: EcNamedCurve;
}

Properties

  • readonly kind: ecdsa — Discriminant selecting ECDSA import.
  • readonly curve: EcNamedCurve — NIST curve the key belongs to. Required for EC import.

ImportEd25519KeyInput

Ed25519 variant of PublicKeyImportInput / PrivateKeyImportInput.

ts
interface ImportEd25519KeyInput {
	readonly kind: ed25519;
}

Properties

  • readonly kind: 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').

ts
type ImportEncryptedKeyErrorCode = malformed | invalid_password

ImportEncryptedKeyFailure

Structured failure payload for encrypted key import.

ts
interface ImportEncryptedKeyFailure extends Micro509Error<ImportEncryptedKeyErrorCode> {
	readonly ok: false;
}

Properties

  • readonly ok: false — Always false for 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.

ts
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.

ts
type ImportKeyErrorCode = malformed

ImportKeyFailure

Structured failure payload for key import.

ts
interface ImportKeyFailure extends Micro509Error<ImportKeyErrorCode> {
	readonly ok: false;
}

Properties

  • readonly ok: false — Always false for 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).

ts
type ImportKeyResult<T> = {
  readonly ok: true;
  readonly value: T
} | ErrorResult<ImportKeyErrorCode, Record<never, never>, ImportKeyFailure>

ImportRsaKeyInput

RSA variant of PublicKeyImportInput / PrivateKeyImportInput.

ts
interface ImportRsaKeyInput {
	readonly kind: rsa;
	readonly hash?: RsaHash;
	readonly scheme?: RsaScheme;
}

Properties

  • readonly kind: rsa — Discriminant selecting RSA import.
  • readonly hash?: RsaHash — Hash algorithm. Defaults to 'SHA-256'.
  • readonly scheme?: RsaScheme — Padding scheme. Defaults to 'pkcs1-v1_5'. Pass 'oaep' to import an RSA-OAEP encryption key (encrypt/decrypt usage instead of verify/sign).

KeyAlgorithmInput

Input for generateKeyPair. Selects algorithm family and parameters.

ts
type KeyAlgorithmInput = RsaKeyAlgorithmInput | EcKeyAlgorithmInput | Ed25519KeyAlgorithmInput

KeyPairMaterial

Key pair with convenience export helpers. Returned by generateKeyPair.

ts
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

  • readonly publicKey: CryptoKey — The WebCrypto public key (extractable, verify usage; encrypt for RSA-OAEP).
  • readonly privateKey: CryptoKey — The WebCrypto private key (extractable, sign usage; decrypt for RSA-OAEP).

LegacyPemEncryptionOptions

Options for OpenSSL-style Proc-Type: 4,ENCRYPTED PEM encryption (PKCS#1/SEC1).

ts
interface LegacyPemEncryptionOptions {
	readonly password: string;
	readonly iv?: Uint8Array;
	readonly cipher?: AES-128-CBC | AES-192-CBC | AES-256-CBC;
}

Properties

  • readonly password: string — Passphrase used to derive the encryption key.
  • readonly iv?: Uint8Array — 16-byte initialization vector. Random when omitted.
  • readonly cipher?: 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.

ts
type PrivateKeyImportInput = PublicKeyImportInput

PublicKeyImportInput

Algorithm descriptor for public key import functions.

ts
type PublicKeyImportInput = ImportRsaKeyInput | ImportEcKeyInput | ImportEd25519KeyInput

RsaHash

Hash algorithm paired with an RSA key.

ts
type RsaHash = SHA-256 | SHA-384 | SHA-512

RsaKeyAlgorithmInput

RSA variant of KeyAlgorithmInput.

ts
interface RsaKeyAlgorithmInput {
	readonly kind: rsa;
	readonly modulusLength?: 2048 | 3072 | 4096;
	readonly hash?: RsaHash;
	readonly scheme?: RsaScheme;
}

Properties

  • readonly kind: rsa — Discriminant selecting RSA key generation.
  • readonly modulusLength?: 2048 | 3072 | 4096 — RSA modulus size in bits. Defaults to 2048.
  • readonly hash?: RsaHash — Hash algorithm for the key. Defaults to 'SHA-256'.
  • readonly scheme?: RsaScheme — Padding scheme. Defaults to 'pkcs1-v1_5'. Pass 'oaep' to generate an RSA-OAEP encryption pair (encrypt/decrypt usages instead of sign/verify).

RsaOaepOptions

Options shared by encryptRsaOaep and decryptRsaOaep.

ts
interface RsaOaepOptions {
	readonly label?: Uint8Array;
}

Properties

  • readonly label?: 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).

ts
type RsaScheme = RsaSignatureScheme | oaep

RsaSignatureScheme

RSA signature padding scheme.

ts
type RsaSignatureScheme = pkcs1-v1_5 | pss

decryptRsaOaep

Decrypt an RSA-OAEP ciphertext with the matching private key.

ts
function decryptRsaOaep(
	privateKey: CryptoKey,
	ciphertext: Uint8Array,
	options: RsaOaepOptions,
): Promise<DecryptRsaOaepResult>

Parameters

See also

  • decryptRsaOaepOrThrow for the throwing variant

Examples

ts
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).

ts
function decryptRsaOaepOrThrow(
	privateKey: CryptoKey,
	ciphertext: Uint8Array,
	options: RsaOaepOptions,
): Promise<Uint8Array>

Parameters

  • privateKey: CryptoKey — RSA-OAEP private CryptoKey with decrypt usage
  • ciphertext: Uint8Array — Ciphertext produced by encryptRsaOaep (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

Examples

ts
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).

ts
function derivePublicKey(
	privateKey: CryptoKey,
): Promise<CryptoKey>

Parameters

  • privateKey: CryptoKey — An extractable private CryptoKey

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

Examples

ts
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.

ts
function encryptRsaOaep(
	publicKey: CryptoKey,
	plaintext: Uint8Array,
	options: RsaOaepOptions,
): Promise<EncryptRsaOaepResult>

Parameters

See also

  • encryptRsaOaepOrThrow for the throwing variant

Examples

ts
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.

ts
function encryptRsaOaepOrThrow(
	publicKey: CryptoKey,
	plaintext: Uint8Array,
	options: RsaOaepOptions,
): Promise<Uint8Array>

Parameters

  • publicKey: CryptoKey — RSA-OAEP public CryptoKey with encrypt usage
  • plaintext: Uint8Array — Message bytes, at most the OAEP capacity of the key
  • options: 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

Examples

ts
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.

ts
function exportBinaryBase64(
	key: CryptoKey,
): Promise<string>

Parameters

  • key: CryptoKey

Throws

  • Error — If the key is a symmetric/secret key

See also

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.

ts
function exportEncryptedPkcs1Pem(
	privateKey: CryptoKey,
	options: LegacyPemEncryptionOptions,
): Promise<string>

Parameters

Throws

  • Error — If the key is not an RSA key

See also

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.

ts
function exportEncryptedPkcs8Der(
	privateKey: CryptoKey,
	options: EncryptedPkcs8Options,
): Promise<Uint8Array>

Parameters

  • privateKey: CryptoKey — The private key to export
  • options: EncryptedPkcs8Options — Encryption options including password and optional algorithm settings

See also

exportEncryptedPkcs8Pem

Export a private key as PEM-encoded PBES2-encrypted PKCS#8 EncryptedPrivateKeyInfo.

ts
function exportEncryptedPkcs8Pem(
	privateKey: CryptoKey,
	options: EncryptedPkcs8Options,
): Promise<string>

Parameters

See also

Examples

ts
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.

ts
function exportEncryptedSec1Pem(
	privateKey: CryptoKey,
	options: LegacyPemEncryptionOptions,
): Promise<string>

Parameters

Throws

  • Error — If the key is not an EC key

See also

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.

ts
function exportPkcs1Der(
	privateKey: CryptoKey,
): Promise<Uint8Array>

Parameters

  • privateKey: CryptoKey

Throws

  • Error — If the key is not an RSA key

See also

exportPkcs1Pem

Export an RSA private key as PEM-encoded PKCS#1 RSAPrivateKey.

ts
function exportPkcs1Pem(
	privateKey: CryptoKey,
): Promise<string>

Parameters

  • privateKey: CryptoKey

Throws

  • Error — If the key is not an RSA key

See also

exportPkcs8Der

Export a private key as DER-encoded PKCS#8 PrivateKeyInfo.

ts
function exportPkcs8Der(
	privateKey: CryptoKey,
): Promise<Uint8Array>

Parameters

  • privateKey: CryptoKey

See also

exportPkcs8Pem

Export a private key as PEM-encoded PKCS#8 PrivateKeyInfo.

ts
function exportPkcs8Pem(
	privateKey: CryptoKey,
): Promise<string>

Parameters

  • privateKey: CryptoKey

See also

Examples

ts
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.

ts
function exportPrivateJwk(
	privateKey: CryptoKey,
): Promise<JsonWebKey>

Parameters

  • privateKey: CryptoKey

See also

exportPublicJwk

Export a public key as a JSON Web Key.

ts
function exportPublicJwk(
	publicKey: CryptoKey,
): Promise<JsonWebKey>

Parameters

  • publicKey: CryptoKey

Examples

ts
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.

ts
function exportSec1Der(
	privateKey: CryptoKey,
): Promise<Uint8Array>

Parameters

  • privateKey: CryptoKey

Throws

  • Error — If the key is not an EC key

See also

exportSec1Pem

Export an EC private key as PEM-encoded SEC 1 ECPrivateKey.

ts
function exportSec1Pem(
	privateKey: CryptoKey,
): Promise<string>

Parameters

  • privateKey: CryptoKey

Throws

  • Error — If the key is not an EC key

See also

exportSpkiDer

Export a public key as DER-encoded SubjectPublicKeyInfo.

ts
function exportSpkiDer(
	publicKey: CryptoKey,
): Promise<Uint8Array>

Parameters

  • publicKey: CryptoKey

See also

exportSpkiPem

Export a public key as PEM-encoded SubjectPublicKeyInfo.

ts
function exportSpkiPem(
	publicKey: CryptoKey,
): Promise<string>

Parameters

  • publicKey: CryptoKey

Examples

ts
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.

ts
function generateKeyPair(
	algorithm: KeyAlgorithmInput,
): Promise<KeyPairMaterial>

Parameters

Examples

ts
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).

ts
function importEncryptedPkcs1Pem(
	pem: string,
	password: string,
	algorithm: ImportRsaKeyInput,
): Promise<ImportEncryptedKeyResult<CryptoKey>>

Parameters

See also

  • importEncryptedPkcs1PemOrThrow for 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.

ts
function importEncryptedPkcs1PemOrThrow(
	pem: string,
	password: string,
	algorithm: ImportRsaKeyInput,
): Promise<CryptoKey>

Parameters

See also

importEncryptedPkcs8Der

Import a private key from DER-encoded PBES2-encrypted PKCS#8 EncryptedPrivateKeyInfo.

ts
function importEncryptedPkcs8Der(
	der: Uint8Array,
	password: string,
	algorithm?: PrivateKeyImportInput,
): Promise<ImportEncryptedKeyResult<CryptoKey>>

Parameters

See also

  • importEncryptedPkcs8DerOrThrow for 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).

ts
function importEncryptedPkcs8DerOrThrow(
	der: Uint8Array,
	password: string,
	algorithm?: PrivateKeyImportInput,
): Promise<CryptoKey>

Parameters

  • der: Uint8Array — DER-encoded EncryptedPrivateKeyInfo bytes
  • password: string — Decryption password
  • algorithm?: 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

importEncryptedPkcs8Pem

Import a private key from PEM-encoded PBES2-encrypted PKCS#8 EncryptedPrivateKeyInfo.

ts
function importEncryptedPkcs8Pem(
	pem: string,
	password: string,
	algorithm?: PrivateKeyImportInput,
): Promise<ImportEncryptedKeyResult<CryptoKey>>

Parameters

See also

  • importEncryptedPkcs8PemOrThrow for 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).

ts
function importEncryptedPkcs8PemOrThrow(
	pem: string,
	password: string,
	algorithm?: PrivateKeyImportInput,
): Promise<CryptoKey>

Parameters

Examples

ts
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).

ts
function importEncryptedSec1Pem(
	pem: string,
	password: string,
	algorithm?: ImportEcKeyInput,
): Promise<ImportEncryptedKeyResult<CryptoKey>>

Parameters

See also

  • importEncryptedSec1PemOrThrow for 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.

ts
function importEncryptedSec1PemOrThrow(
	pem: string,
	password: string,
	algorithm?: ImportEcKeyInput,
): Promise<CryptoKey>

Parameters

See also

importPkcs1Der

Import an RSA private key from DER-encoded PKCS#1 RSAPrivateKey.

ts
function importPkcs1Der(
	der: Uint8Array,
	algorithm: ImportRsaKeyInput,
): Promise<ImportKeyResult<CryptoKey>>

Parameters

See also

  • importPkcs1DerOrThrow for 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.

ts
function importPkcs1DerOrThrow(
	der: Uint8Array,
	algorithm: ImportRsaKeyInput,
): Promise<CryptoKey>

Parameters

See also

importPkcs1Pem

Import an RSA private key from PEM-encoded PKCS#1 RSAPrivateKey.

ts
function importPkcs1Pem(
	pem: string,
	algorithm: ImportRsaKeyInput,
): Promise<ImportKeyResult<CryptoKey>>

Parameters

See also

  • importPkcs1PemOrThrow for the throwing variant

importPkcs1PemOrThrow

Import an RSA private key from PEM-encoded PKCS#1 RSAPrivateKey.

Expects the -----BEGIN RSA PRIVATE KEY----- PEM label.

ts
function importPkcs1PemOrThrow(
	pem: string,
	algorithm: ImportRsaKeyInput,
): Promise<CryptoKey>

Parameters

See also

importPkcs8Base64

Import a private key from base64-encoded PKCS#8 PrivateKeyInfo (no PEM headers).

ts
function importPkcs8Base64(
	base64: string,
	algorithm?: PrivateKeyImportInput,
): Promise<ImportKeyResult<CryptoKey>>

Parameters

See also

  • importPkcs8Base64OrThrow for the throwing variant

importPkcs8Base64OrThrow

Import a private key from base64-encoded PKCS#8 PrivateKeyInfo (no PEM headers).

ts
function importPkcs8Base64OrThrow(
	base64: string,
	algorithm?: PrivateKeyImportInput,
): Promise<CryptoKey>

Parameters

See also

importPkcs8Der

Import a private key from DER-encoded PKCS#8 PrivateKeyInfo.

ts
function importPkcs8Der(
	der: Uint8Array,
	algorithm?: PrivateKeyImportInput,
): Promise<ImportKeyResult<CryptoKey>>

Parameters

See also

  • importPkcs8DerOrThrow for 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.

ts
function importPkcs8DerOrThrow(
	der: Uint8Array,
	algorithm?: PrivateKeyImportInput,
): Promise<CryptoKey>

Parameters

  • der: Uint8Array — DER-encoded PKCS#8 PrivateKeyInfo bytes
  • algorithm?: 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 match algorithm

See also

importPkcs8Pem

Import a private key from PEM-encoded PKCS#8 PrivateKeyInfo.

ts
function importPkcs8Pem(
	pem: string,
	algorithm?: PrivateKeyImportInput,
): Promise<ImportKeyResult<CryptoKey>>

Parameters

See also

  • importPkcs8PemOrThrow for 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).

ts
function importPkcs8PemOrThrow(
	pem: string,
	algorithm?: PrivateKeyImportInput,
): Promise<CryptoKey>

Parameters

Examples

ts
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.

ts
function importPrivateJwk(
	jwk: JsonWebKey,
	algorithm?: PrivateKeyImportInput,
): Promise<ImportKeyResult<CryptoKey>>

Parameters

See also

  • importPrivateJwkOrThrow for 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).

ts
function importPrivateJwkOrThrow(
	jwk: JsonWebKey,
	algorithm?: PrivateKeyImportInput,
): Promise<CryptoKey>

Parameters

  • jwk: JsonWebKey — JSON Web Key object with private key components
  • algorithm?: PrivateKeyImportInput — Optional expected algorithm; must match JWK's kty and crv when given

Returns — Extractable CryptoKey with sign usage

Throws

  • Error — If JWK is malformed, lacks private key material, encodes an unsupported algorithm, or doesn't match algorithm

See also

Examples

ts
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.

ts
function importPublicJwk(
	jwk: JsonWebKey,
	algorithm?: PublicKeyImportInput,
): Promise<ImportKeyResult<CryptoKey>>

Parameters

See also

  • importPublicJwkOrThrow for 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.

ts
function importPublicJwkOrThrow(
	jwk: JsonWebKey,
	algorithm?: PublicKeyImportInput,
): Promise<CryptoKey>

Parameters

  • jwk: JsonWebKey — JSON Web Key object with public key components
  • algorithm?: PublicKeyImportInput — Optional expected algorithm; must match JWK's kty and crv when given

Returns — Extractable CryptoKey with verify usage

Throws

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

See also

importSec1Der

Import an EC private key from DER-encoded SEC 1 ECPrivateKey.

ts
function importSec1Der(
	der: Uint8Array,
	algorithm?: ImportEcKeyInput,
): Promise<ImportKeyResult<CryptoKey>>

Parameters

See also

  • importSec1DerOrThrow for 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.

ts
function importSec1DerOrThrow(
	der: Uint8Array,
	algorithm?: ImportEcKeyInput,
): Promise<CryptoKey>

Parameters

Throws

  • Error — If DER is not an ECPrivateKey, its embedded curve doesn't match algorithm, or no curve is available (neither embedded nor supplied)

See also

importSec1Pem

Import an EC private key from PEM-encoded SEC 1 ECPrivateKey.

ts
function importSec1Pem(
	pem: string,
	algorithm?: ImportEcKeyInput,
): Promise<ImportKeyResult<CryptoKey>>

Parameters

See also

  • importSec1PemOrThrow for 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).

ts
function importSec1PemOrThrow(
	pem: string,
	algorithm?: ImportEcKeyInput,
): Promise<CryptoKey>

Parameters

See also

importSpkiBase64

Import a public key from base64-encoded SubjectPublicKeyInfo (no PEM headers).

ts
function importSpkiBase64(
	base64: string,
	algorithm?: PublicKeyImportInput,
): Promise<ImportKeyResult<CryptoKey>>

Parameters

See also

  • importSpkiBase64OrThrow for the throwing variant

importSpkiBase64OrThrow

Import a public key from base64-encoded SubjectPublicKeyInfo (no PEM headers).

ts
function importSpkiBase64OrThrow(
	base64: string,
	algorithm?: PublicKeyImportInput,
): Promise<CryptoKey>

Parameters

See also

importSpkiDer

Import a public key from DER-encoded SubjectPublicKeyInfo.

ts
function importSpkiDer(
	der: Uint8Array,
	algorithm?: PublicKeyImportInput,
): Promise<ImportKeyResult<CryptoKey>>

Parameters

See also

  • importSpkiDerOrThrow for 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.

ts
function importSpkiDerOrThrow(
	der: Uint8Array,
	algorithm?: PublicKeyImportInput,
): Promise<CryptoKey>

Parameters

  • der: Uint8Array — DER-encoded SubjectPublicKeyInfo bytes
  • algorithm?: 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 match algorithm

See also

importSpkiPem

Import a public key from PEM-encoded SubjectPublicKeyInfo.

ts
function importSpkiPem(
	pem: string,
	algorithm?: PublicKeyImportInput,
): Promise<ImportKeyResult<CryptoKey>>

Parameters

See also

  • importSpkiPemOrThrow for the throwing variant

importSpkiPemOrThrow

Import a public key from PEM-encoded SubjectPublicKeyInfo.

ts
function importSpkiPemOrThrow(
	pem: string,
	algorithm?: PublicKeyImportInput,
): Promise<CryptoKey>

Parameters

See also

Examples

ts
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.

ts
interface CategorizedPemBlocks {
	readonly certificates: readonly PemBlock[];
	readonly certificateRequests: readonly PemBlock[];
	readonly privateKeys: readonly PemBlock[];
	readonly publicKeys: readonly PemBlock[];
	readonly others: readonly PemBlock[];
}

Properties

  • readonly certificates: readonly PemBlock[] — Blocks with label CERTIFICATE.
  • readonly certificateRequests: readonly PemBlock[] — Blocks with label CERTIFICATE REQUEST.
  • readonly privateKeys: readonly PemBlock[] — Blocks with label PRIVATE KEY, RSA PRIVATE KEY, or EC PRIVATE KEY.
  • readonly publicKeys: readonly PemBlock[] — Blocks with label PUBLIC KEY.
  • readonly others: readonly PemBlock[] — Blocks whose label doesn't match any of the above categories.

CategorizePemBlocksResult

Success-or-failure result from categorizePemBlocks.

ts
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.

ts
interface PemBlock {
	readonly label: string;
	readonly bytes: Uint8Array;
	readonly pem: string;
}

Properties

  • readonly label: string — RFC 7468 label between the BEGIN / END markers (e.g. "CERTIFICATE").
  • readonly bytes: Uint8Array — Decoded DER content of this block.
  • readonly pem: string — The original PEM text including BEGIN/END lines.

PemDecodeResult

Success-or-failure result from pemDecode.

ts
type PemDecodeResult = {
  readonly ok: true;
  readonly value: Uint8Array
} | ErrorResult<PemErrorCode, Record<never, never>, PemFailure>

PemErrorCode

Machine-readable failure reason for the PEM decoders.

ts
type PemErrorCode = malformed

PemFailure

Structured failure payload for PEM decoding.

ts
interface PemFailure extends Micro509Error<PemErrorCode> {
	readonly ok: false;
}

Properties

  • readonly ok: false — Always false for failures.

SplitPemBlocksResult

Success-or-failure result from splitPemBlocks.

ts
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.

ts
function categorizePemBlocks(
	input: string | readonly PemBlock[],
): CategorizePemBlocksResult

Parameters

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.

ts
function categorizePemBlocksOrThrow(
	input: string | readonly PemBlock[],
): CategorizedPemBlocks

Parameters

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.

ts
function pemDecode(
	label: string,
	pem: string,
): PemDecodeResult

Parameters

  • label: string
  • pem: 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.

ts
function pemDecodeOrThrow(
	label: string,
	pem: string,
): Uint8Array

Parameters

  • 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.

ts
function pemEncode(
	label: string,
	der: Uint8Array,
): string

Parameters

  • 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.

ts
function splitPemBlocks(
	input: string,
): SplitPemBlocksResult

Parameters

  • 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.

ts
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.

ts
type CreatePfxErrorCode = invalid_certificate

CreatePfxFailure

Error payload for a failed PFX creation.

ts
interface CreatePfxFailure extends Micro509Error<CreatePfxErrorCode> {
	readonly ok: false;
}

Properties

  • readonly ok: false — Always false for failures.

CreatePfxInput

Input for createPfx.

ts
interface CreatePfxInput {
	readonly certificates?: readonly PfxCertificateBagInput[];
	readonly privateKeys?: readonly PfxPrivateKeyBagInput[];
	readonly encryption?: PfxEncryptionOptions;
	readonly mac?: Pkcs12MacOptions;
}

Properties

  • readonly certificates?: readonly PfxCertificateBagInput[] — Certificates to include as certBag entries.
  • readonly privateKeys?: readonly PfxPrivateKeyBagInput[] — Private keys to include as keyBag entries.
  • readonly encryption?: PfxEncryptionOptions — PBES2 encryption settings for the key-bag ContentInfo. Omit for unencrypted.
  • readonly mac?: Pkcs12MacOptions — PKCS#12 MAC integrity settings. Omit to skip MAC generation.

CreatePfxResult

Success-or-failure result from createPfx.

ts
type CreatePfxResult = {
  readonly ok: true;
  readonly value: PfxMaterial
} | ErrorResult<CreatePfxErrorCode, Record<never, never>, CreatePfxFailure>

CreatePkcs7CertBagErrorCode

Caller-correctable failure code from createPkcs7CertBag.

ts
type CreatePkcs7CertBagErrorCode = invalid_certificate

CreatePkcs7CertBagFailure

Error payload for a failed PKCS#7 certificate bag creation.

ts
interface CreatePkcs7CertBagFailure extends Micro509Error<CreatePkcs7CertBagErrorCode> {
	readonly ok: false;
}

Properties

  • readonly ok: false — Always false for failures.

CreatePkcs7CertBagResult

Success-or-failure result from createPkcs7CertBag.

ts
type CreatePkcs7CertBagResult = {
  readonly ok: true;
  readonly value: Pkcs7CertBagMaterial
} | ErrorResult<CreatePkcs7CertBagErrorCode, Record<never, never>, CreatePkcs7CertBagFailure>

CreatePkcs7SignedDataErrorCode

Caller-correctable failure codes from createPkcs7SignedData.

ts
type CreatePkcs7SignedDataErrorCode = no_signers | invalid_signer_certificate | invalid_certificate | unsupported_signer_key

CreatePkcs7SignedDataFailure

Error payload for a failed PKCS#7 SignedData creation.

ts
interface CreatePkcs7SignedDataFailure extends Micro509Error<CreatePkcs7SignedDataErrorCode> {
	readonly ok: false;
}

Properties

  • readonly ok: false — Always false for failures.

CreatePkcs7SignedDataInput

Input for createPkcs7SignedData.

ts
interface CreatePkcs7SignedDataInput {
	readonly content: Uint8Array;
	readonly signers: readonly Pkcs7Signer[];
	readonly additionalCertificates?: readonly Pkcs7CertificateSource[];
	readonly encapsulatedContentTypeOid?: string;
	readonly detached?: boolean;
}

Properties

  • readonly content: Uint8Array — Content to encapsulate and sign (the eContent).
  • readonly signers: readonly Pkcs7Signer[] — One or more signers. Each produces a SignerInfo with signed attributes.
  • readonly additionalCertificates?: readonly Pkcs7CertificateSource[] — Additional certificates to embed (e.g. intermediates). Signer certificates are always embedded; duplicate DER is removed.
  • readonly encapsulatedContentTypeOid?: string — Encapsulated content type OID.
  • readonly detached?: boolean — Omit eContent from encapContentInfo (RFC 5652 Section 5.2 detached form). The signature still covers content via 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.

ts
type CreatePkcs7SignedDataResult = {
  readonly ok: true;
  readonly value: Pkcs7SignedDataMaterial
} | ErrorResult<CreatePkcs7SignedDataErrorCode, Record<never, never>, CreatePkcs7SignedDataFailure>

ParsedPfx

Fully decoded PFX container returned by parsePfxDer / parsePfxPem.

ts
interface ParsedPfx {
	readonly bags: readonly ParsedPfxBag[];
	readonly certificates: readonly ParsedCertificate[];
	readonly privateKeys: readonly Uint8Array[];
	readonly macData?: ParsedPkcs12MacData;
}

Properties

  • readonly bags: readonly ParsedPfxBag[] — All SafeBags in the PFX, including unknown types.
  • readonly certificates: readonly ParsedCertificate[] — Convenience: only the parsed certificates extracted from certBag entries.
  • readonly privateKeys: readonly Uint8Array``[] — Convenience: raw PKCS#8 DER of each private key extracted from keyBag entries.
  • readonly macData?: ParsedPkcs12MacData — MAC verification metadata, present when the PFX includes a MacData block.

ParsedPfxAttribute

A single PKCS#12 bag attribute as decoded by parsePfxDer.

ts
interface ParsedPfxAttribute {
	readonly oid: string;
	readonly valuesHex: readonly string[];
}

Properties

  • readonly oid: string — Dotted-decimal OID identifying this attribute type.
  • readonly valuesHex: readonly string``[] — 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'.

ts
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.

ts
interface ParsedPfxBagAttributes {
	readonly entries: readonly ParsedPfxAttribute[];
	readonly friendlyName?: string;
	readonly localKeyId?: string;
}

Properties

  • readonly entries: readonly ParsedPfxAttribute[] — All raw attributes as OID + hex-encoded values.
  • readonly friendlyName?: string — Decoded BMPString friendly-name attribute, if present.
  • readonly localKeyId?: string — Hex-encoded localKeyId attribute, if present.

ParsedPkcs7SignedData

Decoded PKCS#7 SignedData content, including certificates and signer info.

ts
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

  • readonly der?: Uint8Array — Original DER bytes when this object came from parsePkcs7SignedDataDer or PEM parsing.
  • readonly contentTypeOid: string — Outer ContentInfo type OID (always pkcs7-signedData).
  • readonly version: number — SignedData version number.
  • readonly digestAlgorithmOids: readonly string``[] — OIDs of digest algorithms declared in digestAlgorithms.
  • readonly digestAlgorithmNames: readonly string``[] — Human-readable digest algorithm names declared in digestAlgorithms.
  • readonly encapsulatedContentTypeOid: string — OID of the encapsulated content type (e.g. pkcs7-data).
  • readonly encapsulatedContent?: Uint8Array — Raw encapsulated content bytes. Absent in degenerate (certs-only) bags.
  • readonly certificates: readonly ParsedCertificate[] — Certificates included in the SignedData certificate set.
  • readonly signerInfos: readonly ParsedPkcs7SignerInfo[] — 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.

ts
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.

ts
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

  • readonly version: number — CMS SignerInfo version (typically 1 for issuerAndSerialNumber).
  • readonly issuer?: ParsedName — Parsed issuer distinguished name, if present (issuerAndSerialNumber signer identifier).
  • readonly serialNumberHex?: string — Hex-encoded serial number used to locate the signer certificate, if present.
  • readonly subjectKeyIdentifier?: string — Hex-encoded SubjectKeyIdentifier used to locate the signer certificate, if present.
  • readonly digestAlgorithmOid: string — OID of the digest algorithm used to hash the content.
  • readonly digestAlgorithmName: string — Human-readable digest algorithm name (e.g. "SHA-256").
  • readonly signatureAlgorithmOid: string — OID of the algorithm used to produce the signature.
  • readonly signatureAlgorithmName: string — Human-readable signature algorithm name.
  • readonly signatureAlgorithmParametersDer?: Uint8Array — Raw DER of the signature AlgorithmIdentifier parameters, if present.
  • readonly signatureHex: string — Hex-encoded raw signature bytes.
  • readonly signature: Uint8Array — Raw signature bytes.

ParsedPkcs12MacData

Decoded PKCS#12 MacData block returned by parsePkcs12MacData.

ts
interface ParsedPkcs12MacData {
	readonly digestAlgorithmOid: string;
	readonly digestAlgorithmName: string;
	readonly digestHex: string;
	readonly saltHex: string;
	readonly iterations: number;
	readonly verification: valid | invalid | unchecked;
}

Properties

  • readonly digestAlgorithmOid: string — OID of the digest algorithm (currently always SHA-256).
  • readonly digestAlgorithmName: string — Human-readable digest algorithm name (currently "SHA-256").
  • readonly digestHex: string — Hex-encoded MAC digest value.
  • readonly saltHex: string — Hex-encoded salt bytes used during key derivation.
  • readonly iterations: number — Number of PKCS#12 KDF iterations.
  • readonly verification: 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.

ts
type ParsePfxErrorCode = malformed | invalid_password | password_required

ParsePfxFailure

Error payload for a failed PFX parse.

ts
interface ParsePfxFailure extends Micro509Error<ParsePfxErrorCode> {
	readonly ok: false;
}

Properties

  • readonly ok: false — Always false for failures.

ParsePfxOptions

Options for parsePfxDer and parsePfxPem.

ts
interface ParsePfxOptions {
	readonly password?: string;
	readonly macPassword?: string;
}

Properties

  • readonly password?: string — Password used to decrypt PBES2-encrypted ContentInfo entries. Also used for MAC verification when macPassword is omitted.
  • readonly macPassword?: string — Separate password for MAC verification. Falls back to password when omitted.

ParsePfxResult

Success-or-failure result from parsePfxDer / parsePfxPem.

ts
type ParsePfxResult = {
  readonly ok: true;
  readonly value: ParsedPfx
} | ErrorResult<ParsePfxErrorCode, Record<never, never>, ParsePfxFailure>

ParsePkcs7CertBagResult

Success-or-failure result from parsePkcs7CertBagDer / parsePkcs7CertBagPem.

ts
type ParsePkcs7CertBagResult = {
  readonly ok: true;
  readonly value: readonly ParsedCertificate[]
} | ErrorResult<ParsePkcs7ErrorCode, Record<never, never>, ParsePkcs7Failure>

ParsePkcs7ErrorCode

Error codes for PKCS#7 parse failures.

ts
type ParsePkcs7ErrorCode = malformed | not_signed_data

ParsePkcs7Failure

Error payload for a failed PKCS#7 parse.

ts
interface ParsePkcs7Failure extends Micro509Error<ParsePkcs7ErrorCode> {
	readonly ok: false;
}

Properties

  • readonly ok: false — Always false for failures.

ParsePkcs7SignedDataResult

Success-or-failure result from parsePkcs7SignedDataDer / parsePkcs7SignedDataPem.

ts
type ParsePkcs7SignedDataResult = {
  readonly ok: true;
  readonly value: ParsedPkcs7SignedData
} | ErrorResult<ParsePkcs7ErrorCode, Record<never, never>, ParsePkcs7Failure>

ParsePkcs12MacDataErrorCode

Machine-readable failure reason for parsePkcs12MacData.

ts
type ParsePkcs12MacDataErrorCode = malformed

ParsePkcs12MacDataFailure

Structured failure payload for MacData parsing.

ts
interface ParsePkcs12MacDataFailure extends Micro509Error<ParsePkcs12MacDataErrorCode> {
	readonly ok: false;
}

Properties

  • readonly ok: false — Always false for failures.

ParsePkcs12MacDataResult

Success-or-failure result from parsePkcs12MacData.

ts
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.

ts
interface PfxBagAttributesInput {
	readonly friendlyName?: string;
	readonly localKeyId?: Uint8Array;
}

Properties

  • readonly friendlyName?: string — Human-readable label stored as a BMPString attribute.
  • readonly localKeyId?: Uint8Array — Opaque identifier linking a certificate bag to its corresponding key bag.

PfxCertificateBagInput

A certificate to embed in a PFX container. Input for createPfx.

ts
interface PfxCertificateBagInput {
	readonly certificate: PfxCertificateSource;
	readonly attributes?: PfxBagAttributesInput;
}

Properties

PfxCertificateSource

PEM string or DER bytes for a certificate to include in a PFX bag.

ts
type PfxCertificateSource = string | Uint8Array | ParsedCertificate

PfxEncryptionOptions

PBES2 encryption settings for PFX key-bag protection. Alias of EncryptedPkcs8Options.

ts
type PfxEncryptionOptions = EncryptedPkcs8Options

PfxMaterial

DER, PEM, and base64 encodings of a PFX container produced by createPfx.

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

Properties

  • readonly der: Uint8Array — Raw DER-encoded PFX bytes.
  • readonly pem: string — PEM-armored PFX (-----BEGIN PKCS12-----).
  • readonly base64: string — Base64-encoded DER (no PEM armor).

PfxPrivateKeyBagInput

A private key to embed in a PFX container. Input for createPfx.

ts
interface PfxPrivateKeyBagInput {
	readonly privateKey: PfxPrivateKeySource;
	readonly attributes?: PfxBagAttributesInput;
}

Properties

  • readonly privateKey: PfxPrivateKeySource — Private key as a WebCrypto CryptoKey or raw PKCS#8 DER bytes.
  • readonly attributes?: 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.

ts
type PfxPrivateKeySource = CryptoKey | Uint8Array

Pkcs7CertBagMaterial

DER, PEM, and base64 encodings of a PKCS#7 certificate bag.

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

Properties

  • readonly der: Uint8Array — Raw DER-encoded PKCS#7 structure.
  • readonly pem: string — PEM-armored PKCS#7 (-----BEGIN PKCS7-----).
  • readonly base64: string — Base64-encoded DER (no PEM armor).

Pkcs7CertificateSource

PEM text (may contain multiple CERTIFICATE blocks), raw DER bytes, or an already-parsed certificate.

ts
type Pkcs7CertificateSource = string | Uint8Array | ParsedCertificate

Pkcs7SignedDataMaterial

DER, PEM, and base64 encodings of a PKCS#7 SignedData structure.

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

Properties

  • readonly der: Uint8Array — Raw DER-encoded PKCS#7 SignedData.
  • readonly pem: string — PEM-armored PKCS#7 (-----BEGIN PKCS7-----).
  • readonly base64: string — Base64-encoded DER (no PEM armor).

Pkcs7Signer

A single signer for createPkcs7SignedData.

ts
interface Pkcs7Signer {
	readonly certificate: Pkcs7CertificateSource;
	readonly privateKey: CryptoKey;
	readonly signature?: SignatureProfileInput;
}

Properties

  • readonly certificate: 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.
  • readonly privateKey: CryptoKey — Private key matching the certificate's public key, used to sign.
  • readonly signature?: 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.

ts
interface Pkcs12MacOptions {
	readonly password: string;
	readonly iterations?: number;
	readonly salt?: Uint8Array;
}

Properties

  • readonly password: string — Password used to derive the HMAC key via the PKCS#12 KDF.
  • readonly iterations?: number — PKCS#12 KDF iteration count. Default: 2048.
  • readonly salt?: 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.

ts
type VerifyPkcs7SignedDataErrorCode = signer_not_found | signature_invalid | message_digest_mismatch | detached_content_required | ParsePkcs7ErrorCode

VerifyPkcs7SignedDataFailure

Error payload for a failed verifyPkcs7SignedData call.

ts
interface VerifyPkcs7SignedDataFailure extends Micro509Error<VerifyPkcs7SignedDataErrorCode> {
	readonly ok: false;
}

Properties

  • readonly ok: false — Always false for failures.

VerifyPkcs7SignedDataOptions

Options for verifyPkcs7SignedData.

ts
interface VerifyPkcs7SignedDataOptions {
	readonly content?: Uint8Array;
}

Properties

  • readonly content?: Uint8Array — External content for a detached SignedData (RFC 5652 Section 5.2, absent eContent). Required to verify a detached signature; ignored when the SignedData embeds its own content.

VerifyPkcs7SignedDataResult

Success-or-failure result from verifyPkcs7SignedData.

ts
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.

ts
function createPfx(
	input: CreatePfxInput,
): Promise<CreatePfxResult>

Parameters

Examples

ts
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.

ts
function createPkcs7CertBag(
	certificates: readonly Pkcs7CertificateSource[],
): CreatePkcs7CertBagResult

Parameters

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).

ts
function createPkcs7SignedData(
	input: CreatePkcs7SignedDataInput,
): Promise<CreatePkcs7SignedDataResult>

Parameters

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).

ts
function parsePfxDer(
	der: Uint8Array,
	options?: ParsePfxOptions,
): Promise<ParsePfxResult>

Parameters

Examples

ts
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.

ts
function parsePfxPem(
	pem: string,
	options?: ParsePfxOptions,
): Promise<ParsePfxResult>

Parameters

Examples

ts
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.

ts
function parsePkcs7CertBagDer(
	der: Uint8Array,
): ParsePkcs7CertBagResult

Parameters

  • der: Uint8Array

parsePkcs7CertBagPem

Parses a PEM-armored PKCS#7 cert bag. Expects exactly one PKCS7 PEM block.

ts
function parsePkcs7CertBagPem(
	pem: string,
): ParsePkcs7CertBagResult

Parameters

  • pem: string

parsePkcs7SignedDataDer

Decodes a DER-encoded PKCS#7 ContentInfo expecting signedData content type.

ts
function parsePkcs7SignedDataDer(
	der: Uint8Array,
): ParsePkcs7SignedDataResult

Parameters

  • der: Uint8Array

parsePkcs7SignedDataPem

Decodes a PEM-armored PKCS#7 SignedData. Expects exactly one PKCS7 PEM block.

ts
function parsePkcs7SignedDataPem(
	pem: string,
): ParsePkcs7SignedDataResult

Parameters

  • 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.

ts
function verifyPkcs7SignedData(
	input: string | Uint8Array | ParsedPkcs7SignedData,
	options: VerifyPkcs7SignedDataOptions,
): Promise<VerifyPkcs7SignedDataResult>

Parameters

Examples

ts
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.

ts
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

  • readonly ok: false — Always false for failures.
  • readonly error: TError — Structured error payload.
  • readonly code: TCode — Machine-readable failure reason, mirrored from error.code.
  • readonly message: string — Human-readable diagnostic, mirrored from error.message.
  • readonly details?: TDetails — Optional structured context for the failure.

IndexedErrorResult

Like ErrorResult but also carries an index into the collection that was being processed.

ts
interface IndexedErrorResult<TCode extends string, TDetails, TError extends IndexedMicro509Error<TCode, TDetails>> extends ErrorResult<TCode, TDetails, TError> {
	readonly index?: number;
}

Properties

  • readonly index?: number — Zero-based position of the failing item in the input collection.

IndexedMicro509Error

Like Micro509Error but includes a positional index for collection-processing APIs.

ts
interface IndexedMicro509Error<TCode extends string, TDetails> extends Micro509Error<TCode, TDetails> {
	readonly index?: number;
}

Properties

  • readonly index?: number — Zero-based position of the failing item in the input collection.

Micro509Error

Base error shape carried by all failure results in the library.

ts
interface Micro509Error<TCode extends string, TDetails> {
	readonly code: TCode;
	readonly message: string;
	readonly details?: TDetails;
}

Properties

  • readonly code: TCode — Machine-readable failure reason (e.g. 'malformed', 'expired').
  • readonly message: string — Human-readable diagnostic message.
  • readonly details?: 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.

ts
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.

ts
interface ResultError<TError extends Micro509Error<string, unknown>> extends Error {
	readonly code: TError[code];
	readonly error: TError;
}

Properties

  • readonly code: TError[code] — Machine-readable failure reason, mirrored from error.code.
  • readonly error: TError — The structured error payload that produced this exception.

isResultError

Type guard: was value thrown by unwrap? Narrows to ResultError.

ts
function isResultError(
	value: unknown,
): value is ResultError

Parameters

  • 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.

ts
function unwrap<TValue, TError extends Micro509Error<string, unknown>>(
	result: UnwrappableResult<TValue, TError>,
): TValue

Parameters

unwrapOr

Returns the success value, or fallback when the result is a failure.

ts
function unwrapOr<TValue>(
	result: UnwrappableResult<TValue, unknown>,
	fallback: TValue,
): TValue

Parameters

CertificateRevocationListMaterial

Encoded CRL in multiple serialisation formats, returned by createCertificateRevocationList.

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

Properties

  • readonly der: Uint8Array — Raw DER bytes of the signed CRL.
  • readonly pem: string — PEM-encoded CRL (-----BEGIN X509 CRL-----).
  • readonly base64: 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).

ts
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.

ts
type CheckCertificateRevocationAgainstCrlErrorCode = signature_invalid | issuer_mismatch | stale_crl | crl_sign_not_permitted | non_applicable

CheckCertificateRevocationAgainstCrlFailure

Failure detail for checkCertificateRevocationAgainstCrl.

ts
interface CheckCertificateRevocationAgainstCrlFailure extends Micro509Error<CheckCertificateRevocationAgainstCrlErrorCode, CheckCertificateRevocationAgainstCrlFailureDetails> {
	readonly ok: false;
}

Properties

  • readonly ok: false — Always false for failures.

CheckCertificateRevocationAgainstCrlFailureDetails

Structured details attached to a CheckCertificateRevocationAgainstCrlFailure.

ts
interface CheckCertificateRevocationAgainstCrlFailureDetails {
	readonly reason?: CrlApplicabilityFailureReason;
}

Properties

CheckCertificateRevocationAgainstCrlGoodValue

Success value when the certificate is not found in the CRL.

ts
interface CheckCertificateRevocationAgainstCrlGoodValue {
	readonly status: good;
	readonly crl: ParsedCertificateRevocationList;
}

Properties

CheckCertificateRevocationAgainstCrlInput

Input for checkCertificateRevocationAgainstCrl.

ts
interface CheckCertificateRevocationAgainstCrlInput {
	readonly certificate: CrlCertificateSource;
	readonly issuerCertificate: CrlCertificateSource;
	readonly crl: CrlSource;
	readonly deltaCrl?: CrlSource;
	readonly at?: Date;
	readonly clockSkewMs?: number;
}

Properties

  • readonly certificate: CrlCertificateSource — Certificate whose revocation status to check.
  • readonly issuerCertificate: CrlCertificateSource — Issuer of certificate — also expected signer of the CRL.
  • readonly crl: CrlSource — Complete (base) CRL to check against.
  • readonly deltaCrl?: CrlSource — Optional delta CRL for more recent revocation information.
  • readonly at?: Date — Evaluation time. Defaults to new Date().
  • readonly clockSkewMs?: 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.

ts
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.

ts
interface CheckCertificateRevocationAgainstCrlRevokedValue {
	readonly status: revoked;
	readonly crl: ParsedCertificateRevocationList;
	readonly revocationDate: Date;
	readonly reasonCode?: RevocationReason;
}

Properties

  • readonly status: revoked — Certificate is revoked.
  • readonly crl: ParsedCertificateRevocationList — The validated CRL that contained the revocation entry.
  • readonly revocationDate: Date — When the CA declared this certificate revoked.
  • readonly reasonCode?: RevocationReason — CRLReason from the entry, if present.

CheckCertificateRevocationAgainstCrlValue

Discriminated union of good and revoked outcomes.

ts
type CheckCertificateRevocationAgainstCrlValue = CheckCertificateRevocationAgainstCrlGoodValue | CheckCertificateRevocationAgainstCrlRevokedValue

CheckCertificateRevocationErrorCode

Error codes that checkCertificateRevocation may surface inside an indeterminate result.

ts
type CheckCertificateRevocationErrorCode = revocation_evidence_missing | revocation_status_indeterminate

CheckCertificateRevocationFailureDetails

Diagnostic details attached to an indeterminate revocation result.

ts
interface CheckCertificateRevocationFailureDetails {
	readonly checkedSources: readonly RevocationEvidenceKind[];
	readonly indeterminateEvidence: readonly RevocationIndeterminateEvidence[];
}

Properties

  • readonly checkedSources: readonly RevocationEvidenceKind[] — Which evidence kinds were attempted ('crl', 'ocsp', or both).
  • readonly indeterminateEvidence: readonly RevocationIndeterminateEvidence[] — Per-evidence explanations of why no definitive answer was reached.

CheckCertificateRevocationInput

Input for checkCertificateRevocation.

ts
interface CheckCertificateRevocationInput {
	readonly certificate: RevocationCertificateSource;
	readonly issuerCertificate: RevocationCertificateSource;
	readonly evidence?: readonly RevocationEvidenceInput[];
	readonly at?: Date;
	readonly clockSkewMs?: number;
}

Properties

  • readonly certificate: RevocationCertificateSource — Certificate whose revocation status to determine.
  • readonly issuerCertificate: RevocationCertificateSource — Issuer of certificate.
  • readonly evidence?: readonly RevocationEvidenceInput[] — CRL and/or OCSP evidence to evaluate. Returns indeterminate if empty.
  • readonly at?: Date — Evaluation time. Defaults to new Date().
  • readonly clockSkewMs?: number — Clock-skew tolerance in milliseconds.

CheckCertificateRevocationResult

Result of checkCertificateRevocation. Always succeeds (ok: true) — the value.status discriminator carries the actual outcome.

ts
type CheckCertificateRevocationResult = Result<CheckCertificateRevocationValue, never>

CheckCertificateRevocationValue

Discriminated union of good, revoked, and indeterminate revocation outcomes.

ts
type CheckCertificateRevocationValue = RevocationCheckGoodValue | RevocationCheckRevokedValue | RevocationCheckIndeterminateValue

CheckChainRevocationInput

Input for checkChainRevocation.

ts
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

  • readonly chain: readonly ParsedCertificate[] — Validated certificate chain (leaf first, root last).
  • readonly crls?: readonly CrlSource[] — CRLs to evaluate.
  • readonly ocspResponses?: readonly OcspResponseSource[] — OCSP responses to evaluate.
  • readonly extraCertificates?: readonly RevocationCertificateSource[] — Extra certs for indirect CRL issuers / delegated OCSP responders.
  • readonly trustedOcspResponders?: readonly RevocationCertificateSource[] — 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.
  • readonly at?: Date — Evaluation time. Defaults to new Date().
  • readonly policy?: RevocationPolicy — Revocation policy.

CheckChainRevocationResult

Result type for checkChainRevocation.

ts
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.

ts
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

ConfiguredOcspResponder

A manually-configured OCSP responder endpoint.

ts
interface ConfiguredOcspResponder {
	readonly uri: string;
	readonly responderCertificate?: ConfiguredOcspResponderCertificate;
}

Properties

  • readonly uri: string — OCSP responder URI (typically http://...).
  • readonly responderCertificate?: ConfiguredOcspResponderCertificate — Known responder certificate — skips embedded-certificate discovery.

ConfiguredOcspResponderCertificate

PEM or DER bytes of a pre-configured OCSP responder certificate.

ts
type ConfiguredOcspResponderCertificate = string | Uint8Array

CreateCertificateRevocationListInput

Input for createCertificateRevocationList.

ts
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

  • readonly issuer: NameInput — Distinguished name of the CRL issuer (typically the signing CA).
  • readonly signerPrivateKey: CryptoKey — Private key used to sign the CRL. Algorithm is inferred from the key.
  • readonly issuerPublicKey?: CryptoKey — Issuer public key — used to embed an Authority Key Identifier extension.
  • readonly thisUpdate?: Date — Issuance timestamp. Defaults to new Date().
  • readonly nextUpdate?: Date — Planned next issuance. Omit for an open-ended CRL.
  • readonly revokedCertificates?: readonly RevokedCertificateInput[] — Certificates to list as revoked in this CRL.
  • readonly crlNumber?: number — Monotonically-increasing CRL sequence number (CRLNumber extension).
  • readonly baseCrlNumber?: number — If set, marks this CRL as a delta CRL referencing the given base CRL number.
  • readonly issuingDistributionPoint?: IssuingDistributionPoint — Issuing distribution point extension — scopes this CRL to a subset of certificates.
  • readonly freshestCrlDistributionPoints?: readonly DistributionPoint[] — Freshest CRL distribution points — tells relying parties where to find delta CRLs.

CreateOcspRequestInput

Input for createOcspRequest.

ts
interface CreateOcspRequestInput {
	readonly requests: readonly CreateOcspRequestItemInput[];
	readonly hashAlgorithm?: OcspHashAlgorithm;
	readonly nonce?: Uint8Array;
}

Properties

  • readonly requests: readonly CreateOcspRequestItemInput[] — One or more certificates to query (batched into a single OCSP request).
  • readonly hashAlgorithm?: OcspHashAlgorithm — Hash algorithm for CertID computation. Defaults to 'SHA-1'.
  • readonly nonce?: 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.

ts
interface CreateOcspRequestItemInput {
	readonly certificate: OcspCertificateSource;
	readonly issuerCertificate: OcspCertificateSource;
}

Properties

  • readonly certificate: OcspCertificateSource — Certificate whose revocation status is being queried.
  • readonly issuerCertificate: OcspCertificateSource — Issuer of certificate — needed to compute the CertID hash.

CreateOcspResponseInput

Input for createOcspResponse.

ts
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

  • readonly signerPrivateKey: CryptoKey — Private key used to sign the response. Algorithm is inferred from the key.
  • readonly signerCertificate: OcspCertificateSource — Certificate of the OCSP responder — used to build the responder ID (by key hash).
  • readonly responses: readonly CreateOcspSingleResponseInput[] — Per-certificate status entries to include in the BasicOCSPResponse.
  • readonly producedAt?: Date — Timestamp for the producedAt field. Defaults to new Date().
  • readonly nonce?: Uint8Array — Nonce to echo back for replay protection.
  • readonly hashAlgorithm?: OcspHashAlgorithm — Hash algorithm for CertID computation. Defaults to 'SHA-1'.
  • readonly includedCertificates?: readonly OcspCertificateSource[] — 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.

ts
interface CreateOcspSingleResponseInput extends CreateOcspRequestItemInput {
	readonly certStatus: OcspCertStatus;
	readonly thisUpdate?: Date;
	readonly nextUpdate?: Date;
	readonly revokedAt?: Date;
	readonly revocationReasonCode?: number;
}

Properties

  • readonly certStatus: OcspCertStatus — Status to assert for this certificate.
  • readonly thisUpdate?: Date — Start of the validity window for this status assertion. Defaults to new Date().
  • readonly nextUpdate?: Date — End of the validity window. Omit for open-ended assertions.
  • readonly revokedAt?: Date — Revocation time (required when certStatus is 'revoked'). Defaults to thisUpdate.
  • readonly revocationReasonCode?: number — CRLReason integer code (only meaningful when certStatus is 'revoked').

CrlApplicabilityFailureReason

Structured reason why a CRL was deemed non-applicable to a given certificate.

ts
type CrlApplicabilityFailureReason = certificate_scope_mismatch | delta_crl_incompatible | unsupported_delta_crl | distribution_point_mismatch | unsupported_indirect_crl | issuer_mismatch | reasons_mismatch

CrlCertificateSource

PEM string, DER bytes, or already-parsed certificate.

ts
type CrlCertificateSource = string | Uint8Array | ParsedCertificate

CrlEncoderErrorCode

Machine-readable reason a CRL encoder rejected its construction input.

ts
type CrlEncoderErrorCode = distribution_point_name_conflict | distribution_point_full_name_empty | distribution_point_name_empty

CrlSource

PEM string, DER bytes, or already-parsed CRL.

ts
type CrlSource = string | Uint8Array | ParsedCertificateRevocationList

IssuingDistributionPoint

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.

ts
type IssuingDistributionPoint = IssuingDistributionPointBase | IssuingDistributionPointForUserCerts | IssuingDistributionPointForCaCerts | IssuingDistributionPointForAttributeCerts

IssuingDistributionPointBase

Base shape for Issuing Distribution Point (RFC 5280 §5.2.5) — no scope restriction.

ts
interface IssuingDistributionPointBase {
	readonly distributionPoint?: DistributionPointName;
	readonly onlySomeReasons?: readonly DistributionPointReason[];
	readonly indirectCrl?: boolean;
	readonly onlyContainsUserCerts?: false;
	readonly onlyContainsCACerts?: false;
	readonly onlyContainsAttributeCerts?: boolean;
}

Properties

  • readonly distributionPoint?: DistributionPointName — Where to fetch this CRL.
  • readonly onlySomeReasons?: readonly DistributionPointReason[] — Limits the CRL to these revocation reasons. Absent means all reasons.
  • readonly indirectCrl?: boolean — When true, the CRL may contain entries from other CAs. Default false.
  • readonly onlyContainsUserCerts?: false — Must be absent or false in this variant (no user-cert-only restriction).
  • readonly onlyContainsCACerts?: false — Must be absent or false in this variant (no CA-cert-only restriction).
  • readonly onlyContainsAttributeCerts?: boolean — When true, the CRL only covers attribute certificates. Default false.

IssuingDistributionPointForAttributeCerts

IDP scoped to attribute certificates only. Mutually exclusive with user / CA scopes.

ts
interface IssuingDistributionPointForAttributeCerts extends Omit<IssuingDistributionPointBase, onlyContainsAttributeCerts> {
	readonly onlyContainsUserCerts?: false;
	readonly onlyContainsCACerts?: false;
	readonly onlyContainsAttributeCerts: true;
}

Properties

  • readonly onlyContainsUserCerts?: false — Must be absent or false when the CRL is not user-cert-only.
  • readonly onlyContainsCACerts?: false — Must be absent or false when the CRL is not CA-only.
  • readonly onlyContainsAttributeCerts: true — This variant only covers attribute certificates.

IssuingDistributionPointForCaCerts

IDP scoped to CA certificates only. Mutually exclusive with user / attribute scopes.

ts
interface IssuingDistributionPointForCaCerts extends Omit<IssuingDistributionPointBase, onlyContainsCACerts> {
	readonly onlyContainsUserCerts?: false;
	readonly onlyContainsCACerts: true;
	readonly onlyContainsAttributeCerts?: false;
}

Properties

  • readonly onlyContainsUserCerts?: false — Must be absent or false when the CRL is not user-cert-only.
  • readonly onlyContainsCACerts: true — This variant only covers CA certificates.
  • readonly onlyContainsAttributeCerts?: 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.

ts
interface IssuingDistributionPointForUserCerts extends Omit<IssuingDistributionPointBase, onlyContainsUserCerts> {
	readonly onlyContainsUserCerts: true;
	readonly onlyContainsCACerts?: false;
	readonly onlyContainsAttributeCerts?: false;
}

Properties

  • readonly onlyContainsUserCerts: true — This variant only covers end-entity certificates.
  • readonly onlyContainsCACerts?: false — Must be absent or false when the CRL is not CA-only.
  • readonly onlyContainsAttributeCerts?: false — Must be absent or false when the CRL is not attribute-cert-only.

OcspCertificateSource

PEM string, DER bytes, or already-parsed certificate.

ts
type OcspCertificateSource = string | Uint8Array | ParsedCertificate

OcspCertStatus

RFC 6960 certificate status reported by the responder for a single CertID.

ts
type OcspCertStatus = good | revoked | unknown

OcspHashAlgorithm

Hash algorithm used to compute OCSP CertID fields. SHA-1 is the RFC 6960 default.

ts
type OcspHashAlgorithm = SHA-1 | SHA-256

OcspRequestMaterial

Encoded OCSP request in multiple serialisation formats, returned by createOcspRequest.

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

Properties

  • readonly der: Uint8Array — Raw DER bytes.
  • readonly pem: string — PEM-encoded request (-----BEGIN OCSP REQUEST-----).
  • readonly base64: string — Base64-encoded DER (no PEM armour).

OcspRequestSource

PEM string, DER bytes, or already-parsed OCSP request.

ts
type OcspRequestSource = string | Uint8Array | ParsedOcspRequest

OcspResponderCandidate

One candidate OCSP responder resolved by resolveOcspResponderCandidates.

ts
interface OcspResponderCandidate {
	readonly source: OcspResponderSource;
	readonly uri: string;
	readonly responderCertificate?: ConfiguredOcspResponderCertificate;
}

Properties

  • readonly source: OcspResponderSource — Whether this candidate came from configuration or the certificate's AIA extension.
  • readonly uri: string — OCSP responder URI.
  • readonly responderCertificate?: 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 carrying id-pkix-ocsp-nocheck is exempt from revocation checking. Otherwise, CRL evidence from ValidateOcspResponseInput.responderRevocationCrls is consulted when provided — a revoked responder rejects the response; missing or unusable evidence is tolerated (soft).
  • 'require-evidence': nocheck is ignored; CRL evidence must positively show the responder is not revoked, otherwise the response is rejected.
  • 'skip': no responder revocation checking.
ts
type OcspResponderRevocationPolicy = honor-nocheck | require-evidence | skip

OcspResponderSource

Where the OCSP responder URI came from.

ts
type OcspResponderSource = configured | authorityInfoAccess

OcspResponseMaterial

Encoded OCSP response in multiple serialisation formats, returned by createOcspResponse.

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

Properties

  • readonly der: Uint8Array — Raw DER bytes.
  • readonly pem: string — PEM-encoded response (-----BEGIN OCSP RESPONSE-----).
  • readonly base64: string — Base64-encoded DER (no PEM armour).

OcspResponseSource

OCSP response in any supported format.

Accepts PEM string or DER bytes. Used for CheckChainRevocationInput.ocspResponses.

ts
type OcspResponseSource = string | Uint8Array

OcspResponseStatus

RFC 6960 overall response status — anything other than 'successful' means the response body is absent or unusable.

ts
type OcspResponseStatus = successful | malformedRequest | internalError | tryLater | sigRequired | unauthorized

ParseCertificateRevocationListErrorCode

Machine-readable failure reason for the CRL parsers.

ts
type ParseCertificateRevocationListErrorCode = malformed

ParseCertificateRevocationListFailure

Structured failure payload for CRL parsing.

ts
interface ParseCertificateRevocationListFailure extends Micro509Error<ParseCertificateRevocationListErrorCode> {
	readonly ok: false;
}

Properties

  • readonly ok: false — Always false for failures.

ParseCertificateRevocationListResult

Success-or-failure result from parseCertificateRevocationListDer / parseCertificateRevocationListPem.

ts
type ParseCertificateRevocationListResult = {
  readonly ok: true;
  readonly value: ParsedCertificateRevocationList
} | ErrorResult<ParseCertificateRevocationListErrorCode, Record<never, never>, ParseCertificateRevocationListFailure>

ParsedCertificateRevocationList

Decoded X.509 CRL, returned by parseCertificateRevocationListDer and parseCertificateRevocationListPem.

ts
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

  • readonly der?: Uint8Array — Original DER bytes when this object came from parseCertificateRevocationListDer or PEM parsing.
  • readonly version: number — CRL version (1 = v1, 2 = v2 with extensions).
  • readonly tbsCertListDer: Uint8Array — DER-encoded TBSCertList — the signed payload for signature verification.
  • readonly signatureValue: Uint8Array — Raw signature bytes from the CRL outer wrapper.
  • readonly issuer: ParsedName — CRL issuer distinguished name.
  • readonly thisUpdate: Date — Start of the CRL validity window.
  • readonly nextUpdate?: Date — End of the CRL validity window. Absent if the CA does not commit to a schedule.
  • readonly signatureAlgorithmOid: string — OID of the algorithm used to sign this CRL.
  • readonly signatureAlgorithmName: string — Human-readable signature algorithm name (e.g. "ECDSA with SHA-256").
  • readonly signatureAlgorithmParametersDer?: Uint8Array — DER-encoded signature algorithm parameters (e.g. DER NULL for RSA PKCS#1 v1.5).
  • readonly issuerPublicKeyAlgorithmOid?: string — OID of the issuer's public key algorithm, when available.
  • readonly issuerPublicKeyParametersOid?: string — OID of the issuer's public key parameters (e.g. named curve), when available.
  • readonly authorityKeyIdentifier?: string — Hex-encoded Authority Key Identifier, if the extension is present.
  • readonly crlNumber?: number — CRLNumber extension value — monotonically increasing sequence number.
  • readonly baseCrlNumber?: number — Delta CRL indicator — present only on delta CRLs, referencing the base CRL number.
  • readonly issuingDistributionPoint?: ParsedIssuingDistributionPoint — Issuing distribution point extension — scopes this CRL to a certificate subset.
  • readonly freshestCrlDistributionPoints?: readonly ParsedDistributionPoint[] — Freshest CRL extension — points to delta CRL locations.
  • readonly revokedCertificates: readonly ParsedRevokedCertificate[] — 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).

ts
interface ParsedIssuingDistributionPoint {
	readonly distributionPoint?: ParsedDistributionPointName;
	readonly onlyContainsUserCerts?: boolean;
	readonly onlyContainsCACerts?: boolean;
	readonly onlySomeReasons?: ParsedBitFlags<DistributionPointReason>;
	readonly indirectCrl?: boolean;
	readonly onlyContainsAttributeCerts?: boolean;
}

Properties

  • readonly distributionPoint?: ParsedDistributionPointName — Where to fetch this CRL, if specified.
  • readonly onlyContainsUserCerts?: boolean — When true, this CRL only covers end-entity certificates. Default false.
  • readonly onlyContainsCACerts?: boolean — When true, this CRL only covers CA certificates. Default false.
  • readonly onlySomeReasons?: ParsedBitFlags<DistributionPointReason> — Limits the CRL to these revocation reasons. Absent means all reasons.
  • readonly indirectCrl?: boolean — When true, this CRL may contain entries from CAs other than the issuer. Default false.
  • readonly onlyContainsAttributeCerts?: 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.

ts
interface ParsedOcspCertId {
	readonly hashAlgorithmOid: string;
	readonly hashAlgorithmName: string;
	readonly issuerNameHashHex: string;
	readonly issuerKeyHashHex: string;
	readonly serialNumberHex: string;
}

Properties

  • readonly hashAlgorithmOid: string — OID of the hash algorithm used for the name and key hashes.
  • readonly hashAlgorithmName: string — Human-readable hash algorithm name (e.g. "SHA-256").
  • readonly issuerNameHashHex: string — Hex-encoded hash of the issuer's distinguished name DER.
  • readonly issuerKeyHashHex: string — Hex-encoded hash of the issuer's SubjectPublicKey BIT STRING content.
  • readonly serialNumberHex: string — Hex-encoded serial number of the certificate.

ParsedOcspRequest

Decoded OCSP request, returned by parseOcspRequestDer / parseOcspRequestPem.

ts
interface ParsedOcspRequest {
	readonly der?: Uint8Array;
	readonly requests: readonly ParsedOcspCertId[];
	readonly nonce?: string;
}

Properties

  • readonly der?: Uint8Array — Original DER bytes when this object came from parseOcspRequestDer or PEM parsing.
  • readonly requests: readonly ParsedOcspCertId[] — CertIDs of the certificates being queried.
  • readonly nonce?: 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.

ts
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.

ts
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

  • readonly der?: Uint8Array — Original DER bytes when this object came from parseOcspResponseDer or PEM parsing.
  • readonly responseStatus: OcspResponseStatus — Overall response status. Only 'successful' carries a BasicOCSPResponse body.
  • readonly responseTypeOid?: string — OID of the response type (normally id-pkix-ocsp-basic).
  • readonly responseDataDer?: Uint8Array — DER-encoded ResponseData — the signed payload for signature verification.
  • readonly responderId?: ParsedOcspResponderId — How the responder identifies itself.
  • readonly signatureAlgorithmOid?: string — OID of the algorithm used to sign this response.
  • readonly signatureAlgorithmName?: string — Human-readable signature algorithm name.
  • readonly signatureValue?: Uint8Array — Raw signature bytes.
  • readonly producedAt?: Date — Timestamp when the responder produced this response.
  • readonly responses?: readonly ParsedOcspSingleResponse[] — Per-certificate status entries.
  • readonly nonce?: string — Hex-encoded nonce, if the response echoed one.
  • readonly certificates?: readonly ParsedCertificate[] — Certificates embedded in the response (typically the responder's chain).

ParsedOcspSingleResponse

Status of one certificate inside an OCSP BasicResponse.

ts
interface ParsedOcspSingleResponse {
	readonly certId: ParsedOcspCertId;
	readonly certStatus: OcspCertStatus;
	readonly thisUpdate: Date;
	readonly nextUpdate?: Date;
	readonly revokedAt?: Date;
	readonly revocationReasonCode?: number;
}

Properties

  • readonly certId: ParsedOcspCertId — Which certificate this status applies to.
  • readonly certStatus: OcspCertStatus — Responder's verdict: good, revoked, or unknown.
  • readonly thisUpdate: Date — Start of the validity window for this status assertion.
  • readonly nextUpdate?: Date — End of the validity window. Absent if the responder does not commit to a schedule.
  • readonly revokedAt?: Date — When the certificate was revoked (only for certStatus === 'revoked').
  • readonly revocationReasonCode?: number — CRLReason integer (only for certStatus === 'revoked').

ParsedRevokedCertificate

A single revoked-certificate entry decoded from a CRL.

ts
interface ParsedRevokedCertificate {
	readonly serialNumberHex: string;
	readonly revocationDate: Date;
	readonly reasonCode?: RevocationReason;
	readonly invalidityDate?: Date;
	readonly certificateIssuer?: readonly GeneralName[];
}

Properties

  • readonly serialNumberHex: string — Hex-encoded serial number of the revoked certificate.
  • readonly revocationDate: Date — When the CA declared this certificate revoked.
  • readonly reasonCode?: RevocationReason — RFC 5280 CRLReason, if the entry carries one.
  • readonly invalidityDate?: Date — When the key or certificate actually became suspect, if present.
  • readonly certificateIssuer?: readonly GeneralName[] — Indirect-CRL certificate issuer override (RFC 5280 §5.3.3).

ParseOcspRequestErrorCode

Machine-readable failure reason for the OCSP request parsers.

ts
type ParseOcspRequestErrorCode = malformed

ParseOcspRequestFailure

Structured failure payload for OCSP request parsing.

ts
interface ParseOcspRequestFailure extends Micro509Error<ParseOcspRequestErrorCode> {
	readonly ok: false;
}

Properties

  • readonly ok: false — Always false for failures.

ParseOcspRequestResult

Success-or-failure result from parseOcspRequestDer / parseOcspRequestPem.

ts
type ParseOcspRequestResult = {
  readonly ok: true;
  readonly value: ParsedOcspRequest
} | ErrorResult<ParseOcspRequestErrorCode, Record<never, never>, ParseOcspRequestFailure>

ParseOcspResponseErrorCode

Machine-readable failure reason for the OCSP response parsers.

ts
type ParseOcspResponseErrorCode = malformed

ParseOcspResponseFailure

Structured failure payload for OCSP response parsing.

ts
interface ParseOcspResponseFailure extends Micro509Error<ParseOcspResponseErrorCode> {
	readonly ok: false;
}

Properties

  • readonly ok: false — Always false for failures.

ParseOcspResponseResult

Success-or-failure result from parseOcspResponseDer / parseOcspResponsePem.

ts
type ParseOcspResponseResult = {
  readonly ok: true;
  readonly value: ParsedOcspResponse
} | ErrorResult<ParseOcspResponseErrorCode, Record<never, never>, ParseOcspResponseFailure>

ResolveOcspResponderCandidatesInput

Input for resolveOcspResponderCandidates.

ts
interface ResolveOcspResponderCandidatesInput {
	readonly certificate: RevocationCertificateSource;
	readonly configuredResponders?: readonly ConfiguredOcspResponder[];
}

Properties

  • readonly certificate: RevocationCertificateSource — Certificate whose AIA extension will be inspected for OCSP URIs.
  • readonly configuredResponders?: readonly ConfiguredOcspResponder[] — Manually-configured responders — checked before AIA-derived ones.

RevocationCertificateSource

PEM string, DER bytes, or already-parsed certificate.

ts
type RevocationCertificateSource = string | Uint8Array | ParsedCertificate

RevocationCheckGoodValue

Certificate is not revoked according to the checked evidence.

ts
interface RevocationCheckGoodValue {
	readonly status: Extract<RevocationStatus, good>;
	readonly kind: RevocationEvidenceKind;
	readonly message: string;
}

Properties

  • readonly status: Extract<RevocationStatus, good> — Certificate is not revoked.
  • readonly kind: RevocationEvidenceKind — Which evidence kind confirmed the good status.
  • readonly message: string — Human-readable diagnostic message.

RevocationCheckIndeterminateValue

Revocation status could not be determined from the provided evidence.

ts
interface RevocationCheckIndeterminateValue {
	readonly status: Extract<RevocationStatus, indeterminate>;
	readonly code: CheckCertificateRevocationErrorCode;
	readonly message: string;
	readonly details: CheckCertificateRevocationFailureDetails;
}

Properties

RevocationCheckRevokedValue

Certificate is revoked according to the checked evidence.

ts
interface RevocationCheckRevokedValue {
	readonly status: Extract<RevocationStatus, revoked>;
	readonly kind: RevocationEvidenceKind;
	readonly message: string;
	readonly revokedAt?: Date;
	readonly revocationReason?: RevocationReason;
	readonly revocationReasonCode?: number;
}

Properties

  • readonly status: Extract<RevocationStatus, revoked> — Certificate is revoked.
  • readonly kind: RevocationEvidenceKind — Which evidence kind reported the revocation.
  • readonly message: string — Human-readable diagnostic message.
  • readonly revokedAt?: Date — When the certificate was revoked (from CRL entry or OCSP response).
  • readonly revocationReason?: RevocationReason — CRL reason string (from CRL evidence).
  • readonly revocationReasonCode?: number — CRL reason integer code (from OCSP evidence).

RevocationCrlEvidenceInput

CRL-based revocation evidence for CheckCertificateRevocationInput.evidence.

ts
interface RevocationCrlEvidenceInput {
	readonly kind: crl;
	readonly crl: CrlSource;
	readonly deltaCrl?: CrlSource;
}

Properties

  • readonly kind: crl — Discriminator for the CRL evidence variant.
  • readonly crl: CrlSource — Complete (base) CRL.
  • readonly deltaCrl?: CrlSource — Optional delta CRL for more recent revocation information.

RevocationEvidenceInput

Discriminated union of CRL and OCSP evidence inputs.

ts
type RevocationEvidenceInput = RevocationCrlEvidenceInput | RevocationOcspEvidenceInput

RevocationEvidenceKind

Which revocation mechanism produced the evidence.

ts
type RevocationEvidenceKind = crl | ocsp

RevocationExecutionError

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.

ts
interface RevocationExecutionError {
	readonly kind: parse_error | unsupported_extension | internal_error;
	readonly message: string;
	readonly evidenceIdentifier?: string;
}

Properties

  • readonly kind: parse_error | unsupported_extension | internal_error — Error category.
  • readonly message: string — Human-readable error description.
  • readonly evidenceIdentifier?: string — Which evidence caused the error (e.g., CRL issuer DN).

RevocationIndeterminateEvidence

One piece of evidence that failed to produce a definitive revocation answer.

ts
interface RevocationIndeterminateEvidence {
	readonly kind: RevocationEvidenceKind;
	readonly code: RevocationIndeterminateReasonCode;
	readonly message: string;
	readonly reason?: CrlApplicabilityFailureReason;
}

Properties

RevocationIndeterminateReason

See the doc comment above REVOCATION_INDETERMINATE_REASONS.

ts
type RevocationIndeterminateReason = (typeof REVOCATION_INDETERMINATE_REASONS)[number]

RevocationIndeterminateReasonCode

Why a particular piece of evidence could not produce a definitive good/revoked answer.

ts
type RevocationIndeterminateReasonCode = (typeof REVOCATION_INDETERMINATE_REASON_CODES)[number]

RevocationOcspEvidenceInput

OCSP-based revocation evidence for CheckCertificateRevocationInput.evidence.

ts
interface RevocationOcspEvidenceInput {
	readonly kind: ocsp;
	readonly response: string | Uint8Array | ParsedOcspResponse;
	readonly request?: OcspRequestSource;
	readonly responderCertificate?: OcspCertificateSource;
}

Properties

  • readonly kind: ocsp — Discriminator for the OCSP evidence variant.
  • readonly response: string | Uint8Array | ParsedOcspResponse — OCSP response to validate.
  • readonly request?: OcspRequestSource — Original OCSP request — enables nonce and coverage checks.
  • readonly responderCertificate?: 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.

ts
interface RevocationPolicy {
	readonly mode?: soft-fail | hard-fail;
	readonly prefer?: ocsp | crl | best-available;
	readonly ocspResponderRevocation?: OcspResponderRevocationPolicy;
}

Properties

  • readonly mode?: 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.

  • readonly prefer?: ocsp | crl | best-available — Evidence preference when multiple sources are available.

    Both evidence kinds are always evaluated, and a validated revoked verdict from either source wins regardless of preference (fail-closed). Preference only decides which source's good verdict is reported when both yield one.

    • 'best-available': the source with the fresher evidence — the later thisUpdate on the validated OCSP entry or CRL — is reported; ties favor OCSP (default)
    • 'ocsp': prefer OCSP over CRL
    • 'crl': prefer CRL over OCSP
  • readonly ocspResponderRevocation?: 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.

ts
type RevocationReason = unspecified | keyCompromise | cACompromise | affiliationChanged | superseded | cessationOfOperation | certificateHold | removeFromCRL | privilegeWithdrawn | aACompromise

RevocationSource

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.

ts
interface RevocationSource {
	readonly kind: crl | ocsp;
	readonly signerCertificate?: ParsedCertificate;
	readonly evidenceIdentifier?: string;
	readonly thisUpdate?: Date;
}

Properties

  • readonly kind: crl | ocsp — Whether evidence came from a CRL or OCSP response.
  • readonly signerCertificate?: ParsedCertificate — Certificate that signed the evidence (CRL issuer or OCSP responder).
  • readonly evidenceIdentifier?: string — Identifier for debugging (e.g., CRL issuer DN or OCSP responder URL).
  • readonly thisUpdate?: DatethisUpdate of 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.

ts
type RevocationStatus = good | revoked | indeterminate

RevokedCertificateInput

Single revoked certificate entry for createCertificateRevocationList.

ts
interface RevokedCertificateInput {
	readonly serialNumber: Uint8Array;
	readonly revocationDate?: Date;
	readonly reasonCode?: RevocationReason;
	readonly invalidityDate?: Date;
}

Properties

  • readonly serialNumber: Uint8Array — DER-encoded certificate serial number to revoke.
  • readonly revocationDate?: Date — When the certificate was revoked. Defaults to thisUpdate of the CRL.
  • readonly reasonCode?: RevocationReason — RFC 5280 CRLReason code. Omit for unspecified.
  • readonly invalidityDate?: Date — When the key or certificate became suspect — may predate revocationDate.

ValidateCertificateRevocationListFailure

Failure detail for validateCertificateRevocationList.

Possible codes: signature_invalid, issuer_mismatch, stale_crl, crl_sign_not_permitted.

ts
interface ValidateCertificateRevocationListFailure extends Micro509Error<signature_invalid | issuer_mismatch | stale_crl | crl_sign_not_permitted> {
	readonly ok: false;
}

Properties

  • readonly ok: false — Always false for failures.

ValidateCertificateRevocationListInput

Input for validateCertificateRevocationList.

ts
interface ValidateCertificateRevocationListInput {
	readonly crl: CrlSource;
	readonly issuerCertificate: CrlCertificateSource;
	readonly at?: Date;
	readonly clockSkewMs?: number;
}

Properties

  • readonly crl: CrlSource — The CRL to validate.
  • readonly issuerCertificate: CrlCertificateSource — Certificate of the CA that should have signed the CRL.
  • readonly at?: Date — Evaluation time for freshness checks. Defaults to new Date().
  • readonly clockSkewMs?: number — Tolerance in milliseconds for clock skew when checking thisUpdate/nextUpdate.

ValidateCertificateRevocationListResult

Result of validateCertificateRevocationList.

On success, the CRL has passed signature, issuer, key-usage, and freshness checks.

ts
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.

ts
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_response

ValidateOcspResponseFailure

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.

ts
interface ValidateOcspResponseFailure extends Micro509Error<ValidateOcspResponseErrorCode> {
	readonly ok: false;
}

Properties

  • readonly ok: false — Always false for failures.

ValidateOcspResponseInput

Input for validateOcspResponse.

ts
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

  • readonly response: string | Uint8Array | ParsedOcspResponse — The OCSP response to validate.

  • readonly issuerCertificate: OcspCertificateSource — Certificate of the CA that issued the target certificate.

  • readonly request?: OcspRequestSource — Original request — enables nonce and request-coverage checks.

  • readonly responderCertificate?: OcspCertificateSource — Explicit responder certificate — overrides embedded certificate discovery.

  • readonly allowChainedResponderCertificate?: boolean — When true, allows delegated responder chain validation beyond direct issuance.

  • readonly trustedOcspResponders?: readonly OcspCertificateSource[] — 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.

  • readonly responderRevocationPolicy?: OcspResponderRevocationPolicy — Revocation policy for delegated responder certificates. Defaults to 'honor-nocheck'.

  • readonly responderRevocationCrls?: readonly CrlSource[] — CRLs used as revocation evidence for delegated responder certificates.

  • readonly at?: Date — Evaluation time for freshness checks and delegated responder chain validation. Defaults to new Date().

  • readonly clockSkewMs?: number — Clock-skew tolerance in milliseconds for thisUpdate/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.

ts
type ValidateOcspResponseResult = {
  readonly ok: true;
  readonly value: ParsedOcspResponse
} | ErrorResult<ValidateOcspResponseErrorCode, Record<never, never>, ValidateOcspResponseFailure>

VerifyCertificateRevocationListSignatureFailure

Failure detail when CRL signature verification fails.

ts
interface VerifyCertificateRevocationListSignatureFailure extends Micro509Error<signature_invalid> {
	readonly ok: false;
}

Properties

  • readonly ok: false — Always false for failures.

VerifyCertificateRevocationListSignatureResult

Result of verifyCertificateRevocationListSignature.

On success, value is the parsed CRL whose signature has been verified.

ts
type VerifyCertificateRevocationListSignatureResult = {
  readonly ok: true;
  readonly value: ParsedCertificateRevocationList
} | ErrorResult<signature_invalid, Record<never, never>, VerifyCertificateRevocationListSignatureFailure>

VerifyOcspResponseSignatureFailure

Failure detail when OCSP response signature verification fails.

ts
interface VerifyOcspResponseSignatureFailure extends Micro509Error<signature_invalid> {
	readonly ok: false;
}

Properties

  • readonly ok: false — Always false for failures.

VerifyOcspResponseSignatureResult

Result of verifyOcspResponseSignature.

On success, value is the parsed response whose signature has been verified.

ts
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.

ts
function checkCertificateRevocation(
	input: CheckCertificateRevocationInput,
): Promise<CheckCertificateRevocationResult>

Parameters

Examples

ts
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.

ts
function checkCertificateRevocationAgainstCrl(
	input: CheckCertificateRevocationAgainstCrlInput,
): Promise<CheckCertificateRevocationAgainstCrlResult>

Parameters

Examples

ts
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.

ts
function checkChainRevocation(
	input: CheckChainRevocationInput,
): Promise<CheckChainRevocationResult>

Parameters

Examples

ts
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.

ts
function createCertificateRevocationList(
	input: CreateCertificateRevocationListInput,
): Promise<CertificateRevocationListMaterial>

Parameters

Examples

ts
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.base64

createOcspRequest

Builds a DER-encoded OCSP request containing one or more CertID entries and an optional nonce extension.

ts
function createOcspRequest(
	input: CreateOcspRequestInput,
): Promise<OcspRequestMaterial>

Parameters

Examples

ts
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 URI

createOcspResponse

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.

ts
function createOcspResponse(
	input: CreateOcspResponseInput,
): Promise<OcspResponseMaterial>

Parameters

Examples

ts
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.base64

getCertificateOcspResponderUris

Extracts OCSP responder URIs from the certificate's Authority Information Access extension.

ts
function getCertificateOcspResponderUris(
	certificate: RevocationCertificateSource,
): readonly string[]

Parameters

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.

ts
function hasOcspNoCheckExtension(
	certificate: OcspCertificateSource,
): boolean

Parameters

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.

ts
function isCertificateRevoked(
	certificateSerialNumber: Uint8Array | string,
	crl: ParsedCertificateRevocationList,
): boolean

Parameters

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.

ts
function parseCertificateRevocationListDer(
	der: Uint8Array,
): ParseCertificateRevocationListResult

Parameters

  • der: Uint8Array

parseCertificateRevocationListDerOrThrow

Throwing core for parseCertificateRevocationListDer.

Does not verify the signature — call verifyCertificateRevocationListSignature or validateCertificateRevocationList for that.

ts
function parseCertificateRevocationListDerOrThrow(
	der: Uint8Array,
): ParsedCertificateRevocationList

Parameters

  • 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.

ts
function parseCertificateRevocationListPem(
	pem: string,
): ParseCertificateRevocationListResult

Parameters

  • pem: string

parseCertificateRevocationListPemOrThrow

Decodes a PEM-encoded X.509 CRL (-----BEGIN X509 CRL-----).

ts
function parseCertificateRevocationListPemOrThrow(
	pem: string,
): ParsedCertificateRevocationList

Parameters

  • pem: string

Examples

ts
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.

ts
function parseOcspRequestDer(
	der: Uint8Array,
): ParseOcspRequestResult

Parameters

  • der: Uint8Array

parseOcspRequestDerOrThrow

Throwing core for parseOcspRequestDer.

ts
function parseOcspRequestDerOrThrow(
	der: Uint8Array,
): ParsedOcspRequest

Parameters

  • 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.

ts
function parseOcspRequestPem(
	pem: string,
): ParseOcspRequestResult

Parameters

  • pem: string

parseOcspRequestPemOrThrow

Decodes a PEM-encoded OCSP request (-----BEGIN OCSP REQUEST-----).

ts
function parseOcspRequestPemOrThrow(
	pem: string,
): ParsedOcspRequest

Parameters

  • 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.

ts
function parseOcspResponseDer(
	der: Uint8Array,
): ParseOcspResponseResult

Parameters

  • der: Uint8Array

parseOcspResponseDerOrThrow

Throwing core for parseOcspResponseDer.

ts
function parseOcspResponseDerOrThrow(
	der: Uint8Array,
): ParsedOcspResponse

Parameters

  • 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.

ts
function parseOcspResponsePem(
	pem: string,
): ParseOcspResponseResult

Parameters

  • pem: string

parseOcspResponsePemOrThrow

Decodes a PEM-encoded OCSP response (-----BEGIN OCSP RESPONSE-----).

ts
function parseOcspResponsePemOrThrow(
	pem: string,
): ParsedOcspResponse

Parameters

  • pem: string

Examples

ts
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.

ts
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
ts
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.

ts
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).

ts
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.

ts
function validateOcspResponse(
	input: ValidateOcspResponseInput,
): Promise<ValidateOcspResponseResult>

Parameters

Examples

ts
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.

ts
function verifyCertificateRevocationListSignature(
	crl: string | Uint8Array,
	issuerCertificate: string | Uint8Array,
): Promise<VerifyCertificateRevocationListSignatureResult>

Parameters

  • crl: string | Uint8Array
  • issuerCertificate: 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.

ts
function verifyOcspResponseSignature(
	response: string | Uint8Array | ParsedOcspResponse,
	signerCertificate: OcspCertificateSource,
): Promise<VerifyOcspResponseSignatureResult>

Parameters

BuildCandidatePathInput

Input for buildCandidatePath.

ts
interface BuildCandidatePathInput {
	readonly leaf: CertificateSource;
	readonly intermediates?: readonly CertificateSource[];
	readonly roots: readonly CertificateSource[];
	readonly trustAnchors?: readonly TrustAnchor[];
	readonly at?: Date;
}

Properties

  • readonly leaf: CertificateSource — End-entity certificate to verify.
  • readonly intermediates?: readonly CertificateSource[] — Intermediate CA certificates available for path building. Order does not matter.
  • readonly roots: readonly CertificateSource[] — Trusted root CA certificates. At least one root or trust anchor must be supplied.
  • readonly trustAnchors?: readonly TrustAnchor[] — Bare trust anchors to try when no root certificate matches.
  • readonly at?: Date — Validation time. Defaults to new Date().

BuildCandidatePathResult

Result of buildCandidatePath. On success, contains the CandidatePath.

ts
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.

ts
interface CandidatePath {
	readonly leaf: ParsedCertificate;
	readonly chain: readonly ParsedCertificate[];
	readonly root: ParsedCertificate;
	readonly anchorCertificateInChain: boolean;
}

Properties

  • readonly leaf: ParsedCertificate — Parsed end-entity certificate.
  • readonly chain: readonly ParsedCertificate[] — Full chain in leaf-to-root order (includes both leaf and root).
  • readonly root: ParsedCertificate — Trusted root that terminates the path.
  • readonly anchorCertificateInChain: booleantrue when CandidatePath.root is a trusted root certificate included in CandidatePath.chain; false when 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.

ts
type CertificateSource = string | Uint8Array

ChainRevocationInput

Input for chain-level revocation checking in verifyCertificateChain.

ts
interface ChainRevocationInput {
	readonly crls?: readonly CrlSource[];
	readonly ocspResponses?: readonly (string | Uint8Array)[];
	readonly extraCertificates?: readonly RevocationCertificateSource[];
	readonly trustedOcspResponders?: readonly RevocationCertificateSource[];
	readonly policy?: RevocationPolicy;
}

Properties

  • readonly crls?: readonly CrlSource[] — CRLs to evaluate.
  • readonly ocspResponses?: readonly (string | Uint8Array)[] — OCSP responses to evaluate (PEM strings or DER bytes).
  • readonly extraCertificates?: readonly RevocationCertificateSource[] — Extra certs for indirect CRL issuers / delegated OCSP responders.
  • readonly trustedOcspResponders?: readonly RevocationCertificateSource[] — Explicitly trusted OCSP responder certificates (RFC 6960 §4.2.2.2 criterion 1).
  • readonly policy?: RevocationPolicy — Revocation policy.

ConstrainedPolicy

One policy OID that survives RFC 5280 / RFC 9618 processing.

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

Properties

  • readonly policyIdentifier: string — Dotted-decimal OID of the surviving policy.
  • readonly policyQualifiers?: readonly PolicyQualifierInfo[] — Qualifier info (CPS URIs, user notices) attached to this policy, if any.

CsrSource

PEM string or DER bytes for a certificate signing request.

ts
type CsrSource = string | Uint8Array

DnsServiceIdentityInput

DNS hostname reference identifier.

ts
interface DnsServiceIdentityInput {
	readonly type: dns;
	readonly value: string;
	readonly allowCommonNameFallback?: boolean;
}

Properties

  • readonly type: dns — Discriminant for DNS hostname matching.
  • readonly value: string — The hostname to match (e.g. "mail.example.com"). Wildcard labels in the certificate are handled internally.
  • readonly allowCommonNameFallback?: boolean — When true, 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.

ts
interface EkuCheckFailure extends Micro509Error<leaf_eku_missing | intermediate_eku_constraint> {
	readonly ok: false;
	readonly index: number;
}

Properties

  • readonly ok: false — Always false for failures.
  • readonly index: number — Zero-based index into the chain of the certificate that lacks the required EKU.

EkuCheckPurpose

Extended key usage purpose checked by checkExtendedKeyUsage.

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

EkuCheckResult

Result of checkExtendedKeyUsage. Success carries no value; failure identifies the offending certificate.

ts
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.

ts
interface InitialNameConstraintsInput {
	readonly permittedSubtrees?: readonly GeneralSubtree[];
	readonly excludedSubtrees?: readonly GeneralSubtree[];
}

Properties

  • readonly permittedSubtrees?: readonly GeneralSubtree[] — Subtrees within which all subsequent subject names must fall. Default: unconstrained.
  • readonly excludedSubtrees?: readonly GeneralSubtree[] — Subtrees that no subsequent subject name may fall within. Default: none.

IpServiceIdentityInput

IP address reference identifier.

ts
interface IpServiceIdentityInput {
	readonly type: ip;
	readonly value: string;
}

Properties

  • readonly type: ip — Discriminant for IP address matching.
  • readonly value: string — IPv4 or IPv6 address string. Normalized before comparison.

MatchServiceIdentityErrorCode

Discriminant codes for identity-matching failures.

ts
type MatchServiceIdentityErrorCode = subject_alt_name_mismatch | common_name_fallback_suppressed | service_identity_mismatch | unsupported_service_identity_type

MatchServiceIdentityFailure

A failed identity-matching attempt.

ts
interface MatchServiceIdentityFailure extends Micro509Error<MatchServiceIdentityErrorCode, MatchServiceIdentityFailureDetails> {
	readonly ok: false;
}

Properties

  • readonly ok: false — Always false for failures.

MatchServiceIdentityFailureDetails

Diagnostic context attached to an identity-matching failure.

ts
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

  • readonly subjectCommonName?: string — CN of the certificate that was being matched, if present.
  • readonly expected?: string — The reference identifier the caller asked to verify.
  • readonly actual?: string — Comma-joined presented identifiers (from SAN) that were compared.
  • readonly presentedIdentifierTypes?: readonly (dns | uri | srv)[] — SAN types that were present, relevant to CN-fallback suppression logic.
  • readonly commonNameFallbackReason?: 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.

ts
type MatchServiceIdentityFailureResult = ErrorResult<MatchServiceIdentityErrorCode, MatchServiceIdentityFailureDetails, MatchServiceIdentityFailure>

MatchServiceIdentityInput

Input for matchServiceIdentity.

ts
interface MatchServiceIdentityInput {
	readonly certificate: ParsedCertificate;
	readonly serviceIdentity: ServiceIdentityInput;
}

Properties

MatchServiceIdentityResult

Result of matching a reference identifier against a certificate's presented identifiers.

ts
type MatchServiceIdentityResult = MatchServiceIdentitySuccess | MatchServiceIdentityFailureResult

MatchServiceIdentitySuccess

A successful identity match (the certificate covers the requested name).

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

Properties

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

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).

ts
interface PolicyValidationInput {
	readonly initialPolicySet?: readonly string[] | any;
	readonly requireExplicitPolicy?: boolean;
	readonly inhibitPolicyMapping?: boolean;
	readonly inhibitAnyPolicy?: boolean;
}

Properties

  • readonly initialPolicySet?: readonly string``[] | any — OIDs the relying party considers acceptable, or 'any' to accept whatever the chain asserts. Default: 'any'.
  • readonly requireExplicitPolicy?: boolean — When true, the chain must assert at least one acceptable policy. Default: false.
  • readonly inhibitPolicyMapping?: boolean — When true, policy mappings in CA certificates are ignored. Default: false.
  • readonly inhibitAnyPolicy?: boolean — When true, the anyPolicy OID is not treated as matching all policies. Default: false.

PolicyValidationOutcome

Final policy outputs exposed by successful path-validation APIs.

ts
interface PolicyValidationOutcome {
	readonly authorityConstrainedPolicies: readonly ConstrainedPolicy[];
	readonly userConstrainedPolicies: readonly ConstrainedPolicy[];
}

Properties

ServiceIdentityInput

Discriminated union of all supported reference identifier types.

ts
type ServiceIdentityInput = DnsServiceIdentityInput | IpServiceIdentityInput | UriServiceIdentityInput | SrvServiceIdentityInput

ServiceIdentityType

The type discriminant values of ServiceIdentityInput.

ts
type ServiceIdentityType = ServiceIdentityInput[type]

SrvServiceIdentityInput

SRV-ID reference identifier (RFC 4985).

ts
interface SrvServiceIdentityInput {
	readonly type: srv;
	readonly value: string;
}

Properties

  • readonly type: srv — Discriminant for SRV-ID matching.
  • readonly value: string — SRV name in _service.domain form (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.

ts
interface TrustAnchor {
	readonly subject: ParsedName;
	readonly subjectPublicKeyInfoDer: Uint8Array;
	readonly publicKeyAlgorithmOid: string;
	readonly publicKeyParametersOid?: string;
	readonly subjectKeyIdentifier?: string;
}

Properties

  • readonly subject: ParsedName — Parsed subject distinguished name. Used for semantic issuer matching (RFC 5280 §7.1).
  • readonly subjectPublicKeyInfoDer: Uint8Array — DER-encoded SubjectPublicKeyInfo used to verify signatures from this anchor.
  • readonly publicKeyAlgorithmOid: string — OID of the public key algorithm (e.g. 1.2.840.10045.2.1 for EC).
  • readonly publicKeyParametersOid?: string — OID of the key parameters, when algorithm-specific (e.g. named curve OID for EC).
  • readonly subjectKeyIdentifier?: string — Hex-encoded subject key identifier for AKI matching.

UriServiceIdentityInput

URI-ID reference identifier (RFC 6125 §6.5). Scheme and host are matched.

ts
interface UriServiceIdentityInput {
	readonly type: uri;
	readonly value: string;
}

Properties

  • readonly type: uri — Discriminant for URI-ID matching.
  • readonly value: string — Full URI whose scheme and reg-name will be compared.

ValidateCandidatePathInput

Input for validateCandidatePath.

ts
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

  • readonly policy?: PolicyValidationInput — Nested policy validation overrides (takes precedence over flat fields).
  • readonly nameConstraints?: InitialNameConstraintsInput — Nested name constraint overrides (takes precedence over flat fields).
  • readonly chain: readonly ParsedCertificate[] — Pre-built certificate chain in leaf-to-root order.
  • readonly anchorCertificateInChain?: boolean — Whether the terminal certificate in chain is the trust anchor (and so is excluded from policy processing). Defaults to true, matching a chain that ends at a root certificate. Set false when a bare trust anchor verified the terminal certificate, which then must be processed as a path certificate.
  • readonly at?: Date — Validation time. Defaults to new Date().
  • readonly purpose?: VerifyPurpose — Leaf purpose constraint to enforce.
  • readonly allowSelfSignedLeaf?: boolean — When true, allows a self-signed leaf that is also the root. Defaults to false.

ValidateCandidatePathResult

Result of validateCandidatePath.

ts
type ValidateCandidatePathResult = {
  readonly ok: true;
  readonly value: ValidateCandidatePathSuccess
} | IndexedErrorResult<VerifyErrorCode, VerifyFailureDetails, VerifyChainFailure>

ValidateCandidatePathSuccess

Success payload from validateCandidatePath.

ts
interface ValidateCandidatePathSuccess {
	readonly policyValidation: PolicyValidationOutcome;
}

Properties

  • readonly policyValidation: PolicyValidationOutcome — Final RFC 9618-constrained policy outputs for this validated path.

ValidateForCaInput

Input for validateForCa. Enforces basicConstraints.ca on the leaf.

ts
interface ValidateForCaInput extends BuildCandidatePathInput, PolicyValidationInput, InitialNameConstraintsInput {
	readonly policy?: PolicyValidationInput;
	readonly nameConstraints?: InitialNameConstraintsInput;
}

Properties

ValidateForCodeSigningInput

Input for validateForCodeSigning. Enforces codeSigning EKU.

ts
interface ValidateForCodeSigningInput extends BuildCandidatePathInput, PolicyValidationInput, InitialNameConstraintsInput {
	readonly policy?: PolicyValidationInput;
	readonly nameConstraints?: InitialNameConstraintsInput;
}

Properties

ValidateForTlsClientInput

Input for validateForTlsClient. Enforces clientAuth EKU.

ts
interface ValidateForTlsClientInput extends BuildCandidatePathInput, PolicyValidationInput, InitialNameConstraintsInput {
	readonly policy?: PolicyValidationInput;
	readonly nameConstraints?: InitialNameConstraintsInput;
}

Properties

ValidateForTlsServerInput

Input for validateForTlsServer. Enforces serverAuth EKU and optional DNS/IP identity matching.

ts
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

VerifiedCertificateChain

Fully verified certificate chain returned on success from verifyCertificateChain.

ts
interface VerifiedCertificateChain {
	readonly leaf: ParsedCertificate;
	readonly chain: readonly ParsedCertificate[];
	readonly root: ParsedCertificate;
	readonly policyValidation: PolicyValidationOutcome;
}

Properties

VerifyCertificateChainInput

Input for verifyCertificateChain. Combines path-building, validation, and identity options.

ts
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

  • readonly policy?: PolicyValidationInput — Nested policy validation overrides.
  • readonly nameConstraints?: InitialNameConstraintsInput — Nested name constraint overrides.
  • readonly leaf: CertificateSource — End-entity certificate to verify.
  • readonly intermediates?: readonly CertificateSource[] — Intermediate CA certificates available for path building.
  • readonly roots: readonly CertificateSource[] — Trusted root CA certificates.
  • readonly trustAnchors?: readonly TrustAnchor[] — Bare trust anchors to try when no root certificate matches.
  • readonly at?: Date — Validation time. Defaults to new Date().
  • readonly purpose?: VerifyPurpose — Leaf purpose constraint to enforce during validation.
  • readonly serviceIdentity?: ServiceIdentityInput — DNS/IP/URI/SRV identity to match against the leaf's SAN.
  • readonly allowSelfSignedLeaf?: boolean — When true, allows a self-signed leaf. Defaults to false.
  • readonly revocation?: ChainRevocationInput — Optional revocation checking.

VerifyChainFailure

A chain verification failure with its error code, human message, chain index, and diagnostic details.

ts
interface VerifyChainFailure extends IndexedMicro509Error<VerifyErrorCode, VerifyFailureDetails> {
	readonly ok: false;
}

Properties

  • readonly ok: false — Always false for failures.

VerifyChainResult

Result of verifyCertificateChain. On success, contains the VerifiedCertificateChain.

ts
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.

ts
type VerifyErrorCode = (typeof VERIFY_ERROR_CODES)[number]

VerifyFailureDetails

Diagnostic context attached to every VerifyChainFailure. All fields are optional; presence depends on the error code.

ts
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

  • readonly subjectCommonName?: string — CN of the certificate that triggered the failure.
  • readonly issuerCommonName?: string — CN of the issuer of the offending certificate.
  • readonly expected?: string — The value the verifier expected (e.g. a validity window bound or SKI).
  • readonly actual?: string — The value actually found.
  • readonly chainCommonNames?: readonly string``[] — CNs of every certificate in the chain, leaf-first. Present on no_trusted_root.
  • readonly presentedIdentifierTypes?: readonly (dns | uri | srv)[] — SAN identifier types the leaf actually presents. Set on identity-match failures.
  • readonly commonNameFallbackReason?: disabled | suppressed_by_presented_identifier | common_name_missing | common_name_mismatch — Why the CN-fallback path was not taken. Set on common_name_fallback_suppressed.

VerifyPurpose

High-level purpose applied during path validation to enforce leaf constraints.

ts
type VerifyPurpose = serverAuth | clientAuth | ca

VerifyRequestFailure

Failure from verifyCertificateSigningRequest.

ts
interface VerifyRequestFailure extends Micro509Error<signature_invalid | unsupported_signature_algorithm_parameters, VerifyFailureDetails> {
	readonly ok: false;
}

Properties

  • readonly ok: false — Always false for failures.

VerifyRequestResult

Result of verifyCertificateSigningRequest. On success, contains the parsed CSR.

ts
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.

ts
function buildCandidatePath(
	input: BuildCandidatePathInput,
): Promise<BuildCandidatePathResult>

Parameters

Examples

ts
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.

ts
function checkExtendedKeyUsage(
	chain: readonly ParsedCertificate[],
	purpose: EkuCheckPurpose,
): EkuCheckResult

Parameters

Examples

ts
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.

ts
function matchCertificateServiceIdentity(
	rawCertificate: ParsedCertificate,
	serviceIdentity: ServiceIdentityInput,
): MatchServiceIdentityResult

Parameters

Examples

ts
const result = matchCertificateServiceIdentity(parsed, {
  type: 'ip',
  value: '192.168.1.1',
});
ts
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.

ts
function matchServiceIdentity(
	input: MatchServiceIdentityInput,
): MatchServiceIdentityResult

Parameters

Examples

ts
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.

ts
function trustAnchorFromCertificate(
	certificate: ParsedCertificate,
): TrustAnchor

Parameters

VERIFY_ERROR_CODES

Discriminant for every failure a verify operation can produce.

  • no_trusted_root — chain could not be anchored to any root or TrustAnchor.
  • 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 lacks basicConstraints.ca = true.
  • key_cert_sign_required — an issuer has keyUsage but omits keyCertSign.
  • 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 and allowSelfSignedLeaf was 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_requiredrequireExplicitPolicy was set but no acceptable policy was found.
  • initial_policy_set_not_satisfied — the chain's policies do not intersect initialPolicySet.
  • 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.
ts
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.

ts
function validateCandidatePath(
	input: ValidateCandidatePathInput,
): Promise<ValidateCandidatePathResult>

Parameters

validateForCa

Validates a certificate chain for CA use: chain verification + basicConstraints.ca check on the leaf.

ts
function validateForCa(
	input: ValidateForCaInput,
): Promise<VerifyChainResult>

Parameters

Examples

ts
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).

ts
function validateForCodeSigning(
	input: ValidateForCodeSigningInput,
): Promise<VerifyChainResult>

Parameters

Examples

ts
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).

ts
function validateForTlsClient(
	input: ValidateForTlsClientInput,
): Promise<VerifyChainResult>

Parameters

Examples

ts
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.
ts
function validateForTlsServer(
	input: ValidateForTlsServerInput,
): Promise<VerifyChainResult>

Parameters

Examples

ts
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).

ts
function verifyCertificateChain(
	input: VerifyCertificateChainInput,
): Promise<VerifyChainResult>

Parameters

Examples

ts
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.

ts
function verifyCertificateSigningRequest(
	input: CsrSource,
): Promise<VerifyRequestResult>

Parameters

Examples

ts
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).

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

Properties

  • readonly method: ocsp | caIssuers | { readonly type: oid; readonly value: string } — Access method ('ocsp', 'caIssuers', or custom OID).
  • readonly location: 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.

ts
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.

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

CertificateExtensionsInput

Input for createCertificate, createSelfSignedCertificate, and createCertificateSigningRequest.

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

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

Properties

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

CertificateFingerprint

The three rendered forms of a certificate fingerprint.

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

Properties

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

CertificateFingerprintAlgorithm

Digest algorithms supported by certificateFingerprint.

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

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

CertificateFingerprintSource

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

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

ts
type CertificateFingerprintSource = string | Uint8Array | ParsedCertificate

CertificateMaterial

Encoded certificate material in common interchange formats.

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

Properties

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

CertificatePolicies

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

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

CreateCertificateErrorCode

Machine-readable reason a certificate builder rejected its construction input.

ts
type CreateCertificateErrorCode = issuer_distinguished_name_empty | validity_not_after_before_not_before

CreateCertificateInput

Input for createCertificate.

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

Properties

  • readonly issuer: NameInput — Issuer distinguished name.

  • readonly subject: NameInput — Subject distinguished name.

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

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

  • readonly issuerPublicKey?: CryptoKey — Issuer public key.

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

  • readonly validity?: ValidityInput — Validity window configuration.

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

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

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

  • readonly signature?: SignatureProfileInput — Signature algorithm override.

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

CreateCsrInput

Input for createCertificateSigningRequest.

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

Properties

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

CreateSelfSignedCertificateInput

Input for createSelfSignedCertificate.

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

Properties

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

  • readonly algorithm?: KeyAlgorithmInput — Key generation parameters.

    Ignored when keyPair is provided.

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

    When omitted, a new key pair is generated.

  • readonly validity?: ValidityInput — Validity window configuration.

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

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

  • readonly signature?: SignatureProfileInput — Signature algorithm override.

CsrMaterial

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

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

Properties

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

DecodedExtensionMap

Inferred result type when decoding extensions via an ExtensionDecoderMap.

ts
type DecodedExtensionMap<TMap extends ExtensionDecoderMap> = undefined

DecodedExtensionValue

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

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

Properties

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

DistributionPoint

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

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

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

DistributionPointName

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

Supply exactly one of fullName or relativeName.

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

Properties

ExtendedKeyUsage

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

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

ExtensionDecoder

User-supplied decoder for a single extension OID.

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

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

Properties

  • readonly oid: string — OID this decoder handles.

ExtensionDecoderMap

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

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

ExtensionEncoderErrorCode

Machine-readable reason an extension encoder rejected its construction input.

ts
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_oid

GeneralName

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

ts
type GeneralName = SubjectAltName

GeneralSubtree

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

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

Properties

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

InhibitAnyPolicy

RFC 5280 §4.2.1.14 Inhibit anyPolicy.

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

ts
interface InhibitAnyPolicy {
	readonly skipCerts: number;
}

Properties

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

KeyUsage

RFC 5280 §4.2.1.3 Key Usage bit flag.

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

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

See also

MatchCertificatePrivateKeyErrorCode

Machine-readable failure reason for matchCertificatePrivateKey.

ts
type MatchCertificatePrivateKeyErrorCode = malformed_certificate | unsupported_private_key | key_type_mismatch | key_mismatch

MatchCertificatePrivateKeyFailure

Structured failure payload for matchCertificatePrivateKey.

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

Properties

  • readonly ok: false — Always false for failures.

MatchCertificatePrivateKeyFailureResult

Failure branch of MatchCertificatePrivateKeyResult with structured error details.

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

MatchCertificatePrivateKeyResult

Result of matchCertificatePrivateKey.

ts
type MatchCertificatePrivateKeyResult = MatchCertificatePrivateKeySuccess | MatchCertificatePrivateKeyFailureResult

MatchCertificatePrivateKeySuccess

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

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

Properties

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

NameAttribute

Single name attribute within a distinguished name.

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

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

Properties

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

See also

NameConstraintForm

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

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

NameConstraints

RFC 5280 §4.2.1.10 Name Constraints.

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

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

Properties

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

NameEncoderErrorCode

Machine-readable reason a distinguished-name encoder rejected its construction input.

ts
type NameEncoderErrorCode = relative_distinguished_name_empty | unsupported_name_field | name_attribute_empty | name_attribute_too_long | invalid_country_code

NameFieldKey

Union of recognized X.501 attribute type shorthand names.

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

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

NameInput

Input for encodeName.

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

ts
type NameInput = NameObject | readonly NameAttribute[]

NameObject

Convenience object form of an X.501 distinguished name.

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

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

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

Properties

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

ParseCertificateChainResult

Success-or-failure result from parseCertificateChainPem.

ts
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.

ts
type ParseCertificateErrorCode = malformed

ParseCertificateFailure

Structured failure payload for certificate parsing.

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

Properties

  • readonly ok: false — Always false for failures.

ParseCertificateResult

Success-or-failure result from parseCertificateDer / parseCertificatePem.

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

ParseCertificateSigningRequestErrorCode

Machine-readable failure reason for the CSR parsers.

ts
type ParseCertificateSigningRequestErrorCode = malformed

ParseCertificateSigningRequestFailure

Structured failure payload for CSR parsing.

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

Properties

  • readonly ok: false — Always false for failures.

ParseCertificateSigningRequestResult

Success-or-failure result from parseCertificateSigningRequestDer / parseCertificateSigningRequestPem.

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

ParsedBitFlags

A decoded BIT STRING flag set.

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

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

Properties

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

ParsedCertificate

A fully decoded X.509 certificate.

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

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

Properties

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

ParsedCertificateSigningRequest

A fully decoded PKCS#10 Certificate Signing Request.

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

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

Properties

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

ParsedDistributionPoint

A decoded DistributionPoint from the CRL Distribution Points extension.

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

Properties

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

ParsedDistributionPointName

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

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

Properties

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

ParsedExtension

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

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

Properties

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

ParsedName

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

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

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

Properties

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

ParsedNameAttribute

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

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

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

Properties

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

See also

ParsedNameConstraintForm

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

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

ParsedRelativeDistinguishedName

A single RelativeDistinguishedName SET from an X.501 Name.

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

Properties

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

ParseOptions

Options for parseCertificateDer, parseCertificatePem, and CSR parse functions.

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

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

Properties

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

PolicyConstraints

RFC 5280 §4.2.1.11 Policy Constraints.

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

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

Properties

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

PolicyInformation

A single certificate policy: an OID plus optional qualifiers.

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

Properties

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

PolicyMapping

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

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

Properties

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

PolicyMappings

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

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

PolicyQualifierInfo

Discriminated union of all supported policy qualifier types.

ts
type PolicyQualifierInfo = CpsPolicyQualifierInfo | UserNoticePolicyQualifierInfo | CustomPolicyQualifierInfo

RelativeDistinguishedNameInput

Input for encodeRelativeDistinguishedName.

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

ts
type RelativeDistinguishedNameInput = readonly NameAttribute[]

See also

SelfSignedCertificateResult

Result returned by createSelfSignedCertificate.

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

Properties

SubjectAltName

RFC 5280 §4.2.1.6 Subject Alternative Name / GeneralName.

Discriminated union keyed on type.

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

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

SubjectAltNameTextOptions

Options for subjectAltNameToString.

ts
interface SubjectAltNameTextOptions {
	readonly prefix?: boolean;
}

Properties

  • readonly prefix?: boolean — Prepend [subjectAltNameLabel](/api/x509#fn-subjectaltnamelabel): to the value, as openssl x509 -text does. Defaults to false.

ValidityInput

Configures the certificate validity window.

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

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

Properties

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

    Defaults to the current time.

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

    Must be later than notBefore.

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

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.

ts
function certificateFingerprint(
	certificate: CertificateFingerprintSource,
	algorithm: CertificateFingerprintAlgorithm,
): Promise<CertificateFingerprint>

Parameters

Examples

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

certificateMatchesPrivateKey

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

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

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

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

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

Parameters

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

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

Throws

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

See also

Examples

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

createCertificate

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

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

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

Parameters

Returns — The encoded certificate material.

Examples

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

createCertificateSigningRequest

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

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

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

Parameters

Examples

ts
import { createCertificateSigningRequest } from 'micro509';

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

createSelfSignedCertificate

Create a self-signed certificate.

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

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

Parameters

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

Examples

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

decodeExtension

Decode a single extension using a custom ExtensionDecoder.

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

Parameters

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

decodeExtensionMap

Decode all matching extensions using a named ExtensionDecoderMap.

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

Parameters

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

decodeExtensions

Decode all matching extensions using an array of ExtensionDecoders.

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

Parameters

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

defineExtensionDecoder

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

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

Parameters

Returns — The same decoder, properly typed.

defineExtensionDecoderMap

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

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

Parameters

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

Returns — The same map, properly typed.

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.

ts
function distinguishedNameToString(
	name: ParsedName,
): string

Parameters

Examples

ts
distinguishedNameToString(parsed.subject); // 'CN=example.com,O=Acme\\, Inc.,C=US'

findExtension

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

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

Parameters

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

getSubjectPublicKey

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

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

Parameters

See also

  • getSubjectPublicKeyOrThrow for the throwing variant

getSubjectPublicKeyOrThrow

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

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

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

Parameters

Returns — Extractable CryptoKey with verify usage.

Throws

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

See also

Examples

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

matchCertificatePrivateKey

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

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

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

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

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

Parameters

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

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

See also

Examples

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

parseCertificateChainPem

Decode a PEM bundle containing one or more certificates.

Non-CERTIFICATE blocks (e.g. private keys) are silently skipped. Returns a typed malformed failure for invalid PEM or certificate DER.

ts
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.

ts
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.

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

Parameters

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

Examples

ts
import { parseCertificateDer } from 'micro509';

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

parseCertificateDerOrThrow

Throwing core for parseCertificateDer.

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

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

Parameters

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

parseCertificatePem

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

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

Synchronous: returns a ParseCertificateResult directly. Do not await this function.

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

Parameters

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

parseCertificatePemOrThrow

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

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

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

Parameters

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

Examples

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

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

parseCertificateSigningRequestDer

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

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

Parameters

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

parseCertificateSigningRequestDerOrThrow

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

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

Parameters

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

parseCertificateSigningRequestPem

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

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

Parameters

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

parseCertificateSigningRequestPemOrThrow

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

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

Parameters

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

relativeDistinguishedNameToString

Renders one ParsedRelativeDistinguishedName, joining a multi-valued RDN's attributes with +.

ts
function relativeDistinguishedNameToString(
	rdn: ParsedRelativeDistinguishedName,
): string

Parameters

subjectAltNameLabel

The openssl x509 -text label for a SubjectAltName variant — DNS, IP Address, email, URI, SRV, DirName, or [tag <n>] for an unrecognized tag.

ts
function subjectAltNameLabel(
	name: SubjectAltName,
): string

Parameters

subjectAltNameToString

Renders one SubjectAltName as text.

variantrendering
dns, ip, email, uri, srvthe value itself
directoryNamedistinguishedNameToString of the embedded name, or the DER hex if it does not decode
unknownlowercase hex of the raw content bytes
ts
function subjectAltNameToString(
	name: SubjectAltName,
	options?: SubjectAltNameTextOptions,
): string

Parameters

Examples

Render every SAN of a parsed certificate

ts
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'

Released under the MIT License.