@blamejs/pki 0.6.4 → 0.6.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -4,6 +4,23 @@ All notable changes to `@blamejs/pki` are documented here. The format
4
4
  follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/); this
5
5
  project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
6
6
 
7
+ ## v0.6.6 — 2026-08-31
8
+
9
+ pki.kem establishes a shared secret with composite ML-KEM (draft-ietf-lamps-pq-composite-kem): a post-quantum ML-KEM hybridized with a traditional RSA-OAEP, ECDH, X25519, or X448, so the secret holds if either component is later broken.
10
+
11
+ ### Added
12
+
13
+ - pki.kem.encapsulate(publicKey) establishes a 256-bit shared secret for a recipient's composite ML-KEM SubjectPublicKeyInfo, returning the secret and a ciphertext to send to the recipient (draft-ietf-lamps-pq-composite-kem).
14
+ - pki.kem.decapsulate(privateKey, ciphertext) recovers the shared secret from a composite ML-KEM ciphertext and the composite PKCS#8 private key. The twelve algorithms pair ML-KEM-768 and ML-KEM-1024 with RSA-OAEP 2048/3072/4096, ECDH over P-256/P-384/P-521 and brainpoolP256r1/P384r1, X25519, and X448.
15
+
16
+ ## v0.6.5 — 2026-08-30
17
+
18
+ pki.cmp.build assembles a CMP key-recovery request (krr) body: a CertReqMessages under PKIBody tag [9], the key-recovery counterpart of an initialization request (RFC 9810 sec. 5.3.7).
19
+
20
+ ### Added
21
+
22
+ - pki.cmp.build accepts a { krr } body arm (RFC 9810 sec. 5.3.7): a key-recovery request, a CertReqMessages built through pki.crmf.build under PKIBody tag [9], identical in syntax to an initialization request. The proof-of-possession key is a key field on the arm spec, and any proof-of-possession arm the CRMF builder produces is permitted, including a private-key-transport encryptedKey proof.
23
+
7
24
  ## v0.6.4 — 2026-08-30
8
25
 
9
26
  The ACME client gains account update and order listing: pki.acme.client updates an account's contacts (RFC 8555 sec. 7.3.2) and fetches the account's orders list, following the paginated Link: rel="next" chain (sec. 7.1.2.1).
package/README.md CHANGED
@@ -235,7 +235,7 @@ comment blocks, is at [pkijs.com](https://pkijs.com).
235
235
  | `pki.csr` | PKCS#10 certification-request issuance (RFC 2986 / RFC 2985). `sign(spec, key, opts)` builds and signs a `CertificationRequest` from a `spec` of subject (which may be empty), the public key being certified, an optional `extensionRequest` carrying the requested v3 extensions a CA copies into the issued certificate (subject alternative names, key usage, extended key usage, basic constraints, certificate policies, subject key identifier, or an array of pre-encoded Extension DER), and an optional `challengePassword`. `key` (or `{ key }`) is the subject's own private key: the request is self-signed to prove possession of the private half of `subjectPublicKey`, and that proof is verified before the request is returned, which is what `openssl req -verify` checks. The signature algorithm is resolved from the subject key, so RSA (PKCS#1 v1.5 or PSS via `opts.pss`), ECDSA, EdDSA, ML-DSA, SLH-DSA, and the composite arms all sign without a per-algorithm branch. Returns DER, or a PEM `CERTIFICATE REQUEST` with `opts.pem`; malformed input throws a typed `CsrError`. `verify(request)` asks the same question of a request someone else produced, over its exact signed `certificationRequestInfo` bytes under the `subjectPKInfo` inside them, through the one path-validation signature engine. It answers `{ verified, subject, subjectPublicKeyInfo, attributes, certificationRequestInfoBytes }`, all re-derived from the signed bytes, so a CA issues from the fields the signature covers rather than from the object it passed in. A `verified: true` says the producer held that private key and that the subject and requested extensions are the ones they signed; who they are is the enrollment protocol's question, not this one. Parsing stays at `pki.schema.csr.parse` — `sign`, `verify` |
236
236
  | `pki.attrcert` | Attribute-certificate issuance (RFC 5755). `sign(spec, issuer, opts)` builds and signs an `AttributeCertificate` as an Attribute Authority: a `spec` of `holder` (exactly one of an entity name, a `baseCertificateID` reference, a `fromCertificate` binding, or an object digest), the validity window as GeneralizedTime, an optional serial (positive, at most 20 octets, randomly generated when omitted), the `attributes` (role, clearance, group, chargingIdentity, accessIdentity, authenticationInfo, or pre-encoded Attribute DER), and optional `extensions` (auditIdentity, targetInformation, noRevAvail, aaControls, acProxying, authorityKeyIdentifier, or pre-encoded Extension DER) each with its RFC 5755 criticality. An attribute certificate is never self-signed, so the `issuer` is the signing AA, supplied as `{ cert, key }` or `{ name, publicKey, key }`. The signature algorithm is resolved from the AA key, so RSA (PKCS#1 v1.5 or PSS via `opts.pss`), ECDSA, EdDSA, ML-DSA, SLH-DSA, and the composite arms all sign without a per-algorithm branch, and the signature is verified under the AA public key before the certificate is returned. Returns DER, or a PEM `ATTRIBUTE CERTIFICATE` with `opts.pem`; malformed input throws a typed `AttrCertError`. `verify(ac, issuer, opts)` is the receiving side, performing the RFC 5755 sec. 5 checks an attribute certificate and a named issuer can settle between them: the signature over the exact `AttributeCertificateInfo` bytes through the one path-validation signature engine, the AC naming the issuer this verifier trusts (compared as a distinguished name), the evaluation instant lying within the validity with equality at either bound succeeding as the section states, the sec. 4.3.2 targeting rule, and rejection of any critical extension this verb does not process (section 5 defines support as parsing the value AND rejecting where the value would reject, so `aaControls` and `acProxying`, whose constraints it does not evaluate, are refused when critical). It answers `{ verified, signatureValid, validityChecked, targetingChecked, holderBindingChecked, issuerPathChecked, holder, issuer, attributes, extensions, notBefore, notAfter, serialNumberHex, reason }` with the fields re-derived from the signed bytes; the holder's own certificate chain and the AC issuer's chain need certificates the verb is not given, so those slots report `false` rather than letting their absence read as a pass. Parsing stays at `pki.schema.attrcert.parse` — `sign`, `verify` |
237
237
  | `pki.crmf` | Certificate-request-message issuance (RFC 4211). `build(spec, key, opts)` assembles a `CertReqMessages` from a `spec` of `certReqId` (default 0, with the RFC 9483 `-1` sentinel allowed), a `certTemplate` of the requested fields (`subject`, `publicKey` as the SPKI DER of the key being certified, `validity`, requested `extensions`, an optional `version` 2), optional `controls` and `regInfo` (regToken, authenticator, utf8Pairs, oldCertID, protocolEncrKey, or pre-encoded `AttributeTypeAndValue` DER), and an optional `pop` selector. `key` (or `{ key }`) is the requester's private key: the message carries a `POPOSigningKey` proof of possession signed with the private half of `certTemplate.publicKey` and verified before the message is returned, exactly as a PKCS#10 CSR proves possession. A complete template signs the `CertRequest`; an incomplete one signs a `POPOSigningKeyInput`. The signature algorithm is resolved from the requested public key, so RSA (PKCS#1 v1.5 or PSS via `opts.pss`), ECDSA, EdDSA, ML-DSA, SLH-DSA, and the composite arms all sign without a per-algorithm branch. `key` is optional for a `raVerified` proof. A key that cannot sign, which is where an ML-KEM enrollment sits, takes a `POPOPrivKey` proof instead (RFC 4211 sec. 4.2, sec. 4.3): `pop.type` of `keyEncipherment` or `keyAgreement` with `pop.method: 'subsequentMessage'` declares whether an encrypted certificate (`encrCert`) or a challenge (`challengeResp`) completes the proof over the enrolling protocol's next exchange, and `pop.method: 'encryptedKey'` encloses the requester's private key for the CA in a CMS `EnvelopedData` under `id-ct-encKeyWithID`, requiring `pop.privateKey`, `pop.recipients`, the `pop.identifier` sec. 4.2.1 makes mandatory, and `pop.archive: true` because RFC 9810 sec. 5.2.8.3.1 permits the method only where archival is intended. The enclosed key must be the private half of `certTemplate.publicKey`, or the proof demonstrates possession of a key the request never asked to have certified. The `thisMessage` and `dhMAC` alternatives the specification deprecates are refused with their successors named, and `agreeMAC` is not built, since it needs the RFC 2875 static Diffie-Hellman secret against a CA certificate the requester already holds. Pass an array of specs for a batch; the CA-assigned template fields are never emitted. Returns DER, or a PEM block with `opts.pem`; malformed input throws a typed `CrmfError`. `verifyPop(messages)` is the receiving side: for each `CertReqMsg` it verifies the `POPOSigningKey` signature over the bytes RFC 4211 sec. 4.1 names — the DER of `poposkInput` when present, of `certReq` when not — through the one path-validation signature engine, and answers `{ verified, messages: [{ verified, method, cryptographicallyVerified, certReqId, subject, subjectBound, publicKey, reason }] }` with the fields re-derived from the message's own bytes. Each verdict reports only what its preimage covers: `publicKey` is the key possession was proven for, and `subject` is the requested name when the `certReq` was signed. A `poposkInput` preimage covers the key and the sender alone, so any subject beside it is unsigned and is withheld with `subjectBound: false`. A `raVerified` proof is an RA's out-of-band assertion and a `keyEncipherment` or `keyAgreement` proof completes over a later exchange, so each is reported unverified with its `method` named instead of guessed. Parsing stays at `pki.schema.crmf.parse` — `build`, `verifyPop` |
238
- | `pki.cmp` | CMP message building, transfer, and verification (RFC 9810). `build(message, opts)` assembles a protected `PKIMessage`. `message.header` carries the `sender` and `recipient` GeneralNames (including the anonymous NULL-DN) plus optional transaction metadata; `message.body` is a single-key object naming the arm — request-side `ir`, `cr`, `kur`, `p10cr`, `certConf`, `pollReq`, `genm`, `rr`, responder-side `ip`, `cp`, `kup`, `ccp`, `rp`, `genp`, `error`, `pollRep`, `krp`, `pkiconf`, and the registration-authority `nested` wrapper of complete PKIMessages (RFC 9810 §5.1.3.5). Protection is exactly one of `opts.{ key, cert }`, a signature under the sender key with the algorithm resolved from the signer certificate so RSA (PKCS#1 v1.5 / PSS), ECDSA, EdDSA, ML-DSA, SLH-DSA, and the composite arms all sign without a per-algorithm branch, or `opts.mac`, a PBMAC1 shared-secret HMAC (RFC 9481 / 9579, PBKDF2-derived). Protection covers the exact DER of the virtual `ProtectedPart` and is self-verified before the message is returned, and `protectionAlg` is derived rather than caller-set, so the message the parser accepts is coherent by construction. A `p10cr` request's PKCS#10 proof-of-possession is verified before the message is protected, so one whose self-signature does not verify under its subject public key is refused rather than sent. `transfer(url, message, opts)` carries a built message to a CMP endpoint over `pki.transport` (RFC 9811): one POST of the DER PKIMessage, with the response classified fail-closed — 200 only for success, a non-200 2xx or an un-followed 3xx refused, a 4xx or 5xx carrying a CMP error PKIMessage forwarded as the integrity-protected verdict — and protection surfaced rather than verified. `wellKnownUrl(base, opts)` builds the §3.4 `/.well-known/cmp` request-URIs. `verify(message, opts)` checks the protection on an incoming message, either a signature through the same certification-path engine `pki.crl.verify` and `pki.ocsp.verify` use, with the EdDSA low-order-point and algorithm-confusion gates, or a PBMAC1 MAC recomputed from `opts.sharedSecret` and the message's own PBKDF2 parameters and constant-time compared, over the exact `ProtectedPart` reconstructed from the parser's raw slices. It is fail-closed on an unprotected message, a legacy or KEM MAC algorithm, an omitted keyLength, or a SHA-1 PRF, and returns a `{ valid, trusted, protectionType, signer, ... }` verdict. With `opts.trustAnchors` the signer certificate is fully path-validated (RFC 5280 §6.1 plus the RFC 9483 §3.2 `keyUsage.digitalSignature` gate) at a trusted current time, or an explicit `opts.time` for historical verification and never the message's self-asserted `messageTime`, before it is reported trusted; without one the verdict is crypto-only and the signer certificate is surfaced to anchor. `session(opts)` returns a stateful enrollment session whose `enroll(request)` drives a full `ir` / `cr` / `kur` / `p10cr` transaction over the shared transport, composing `build`, `transfer`, and `verify`. Every response is protection-verified, signer-trusted, and bound to the exchange (a stable `transactionID`, a fresh-`senderNonce` and echoed-`recipNonce` chain) before its body is read, with a bounded `pollReq` / `pollRep` loop for a `waiting` status and a `certConf` / `pkiConf` (or implicit) confirmation carrying an explicit `hashAlg` for a signature algorithm that does not convey its hash. It returns a terminal `{ outcome, certificate, chain, status, trusted, confirmed, implicitConfirm, transactionID, polls, transcript }`. The same session also drives the other two RFC 9483 operations under that shell: `revoke(request)` sends an `rr` naming a certificate as `{ certificate }` or `{ certDetails }` with an optional CRLReason `reason`, and returns `revoked` / `rejected` / `poll-timeout`; `info(request)` sends a `genm` for one of the four support messages — `{ caCerts }`, `{ rootCaCert }`, `{ certReqTemplate }`, `{ crlUpdate }` — and returns `answered` with the decoded `value` and a `present` flag, since an absent response value is how each says nothing is available. A session revokes its own certificate: the signature over the request is the proof of authorization (§4.2), so the named certificate must be `opts.cert` and a PBMAC1 session is refused. The signature flavor requires `opts.trustAnchors` to authenticate the CA; a verified rejection or error and an exhausted poll budget are terminal verdicts, while a tampered, untrusted, or desynchronized response is a typed throw. Returns DER, or a PEM `CMP` block with `opts.pem`; malformed input throws a typed `CmpError`. Parsing stays at `pki.schema.cmp.parse` — `build`, `transfer`, `wellKnownUrl`, `verify`, `session` |
238
+ | `pki.cmp` | CMP message building, transfer, and verification (RFC 9810). `build(message, opts)` assembles a protected `PKIMessage`. `message.header` carries the `sender` and `recipient` GeneralNames (including the anonymous NULL-DN) plus optional transaction metadata; `message.body` is a single-key object naming the arm — request-side `ir`, `cr`, `kur`, `krr` (key recovery, §5.3.7), `p10cr`, `certConf`, `pollReq`, `genm`, `rr`, responder-side `ip`, `cp`, `kup`, `ccp`, `rp`, `genp`, `error`, `pollRep`, `krp`, `pkiconf`, and the registration-authority `nested` wrapper of complete PKIMessages (RFC 9810 §5.1.3.5). Protection is exactly one of `opts.{ key, cert }`, a signature under the sender key with the algorithm resolved from the signer certificate so RSA (PKCS#1 v1.5 / PSS), ECDSA, EdDSA, ML-DSA, SLH-DSA, and the composite arms all sign without a per-algorithm branch, or `opts.mac`, a PBMAC1 shared-secret HMAC (RFC 9481 / 9579, PBKDF2-derived). Protection covers the exact DER of the virtual `ProtectedPart` and is self-verified before the message is returned, and `protectionAlg` is derived rather than caller-set, so the message the parser accepts is coherent by construction. A `p10cr` request's PKCS#10 proof-of-possession is verified before the message is protected, so one whose self-signature does not verify under its subject public key is refused rather than sent. `transfer(url, message, opts)` carries a built message to a CMP endpoint over `pki.transport` (RFC 9811): one POST of the DER PKIMessage, with the response classified fail-closed — 200 only for success, a non-200 2xx or an un-followed 3xx refused, a 4xx or 5xx carrying a CMP error PKIMessage forwarded as the integrity-protected verdict — and protection surfaced rather than verified. `wellKnownUrl(base, opts)` builds the §3.4 `/.well-known/cmp` request-URIs. `verify(message, opts)` checks the protection on an incoming message, either a signature through the same certification-path engine `pki.crl.verify` and `pki.ocsp.verify` use, with the EdDSA low-order-point and algorithm-confusion gates, or a PBMAC1 MAC recomputed from `opts.sharedSecret` and the message's own PBKDF2 parameters and constant-time compared, over the exact `ProtectedPart` reconstructed from the parser's raw slices. It is fail-closed on an unprotected message, a legacy or KEM MAC algorithm, an omitted keyLength, or a SHA-1 PRF, and returns a `{ valid, trusted, protectionType, signer, ... }` verdict. With `opts.trustAnchors` the signer certificate is fully path-validated (RFC 5280 §6.1 plus the RFC 9483 §3.2 `keyUsage.digitalSignature` gate) at a trusted current time, or an explicit `opts.time` for historical verification and never the message's self-asserted `messageTime`, before it is reported trusted; without one the verdict is crypto-only and the signer certificate is surfaced to anchor. `session(opts)` returns a stateful enrollment session whose `enroll(request)` drives a full `ir` / `cr` / `kur` / `p10cr` transaction over the shared transport, composing `build`, `transfer`, and `verify`. Every response is protection-verified, signer-trusted, and bound to the exchange (a stable `transactionID`, a fresh-`senderNonce` and echoed-`recipNonce` chain) before its body is read, with a bounded `pollReq` / `pollRep` loop for a `waiting` status and a `certConf` / `pkiConf` (or implicit) confirmation carrying an explicit `hashAlg` for a signature algorithm that does not convey its hash. It returns a terminal `{ outcome, certificate, chain, status, trusted, confirmed, implicitConfirm, transactionID, polls, transcript }`. The same session also drives the other two RFC 9483 operations under that shell: `revoke(request)` sends an `rr` naming a certificate as `{ certificate }` or `{ certDetails }` with an optional CRLReason `reason`, and returns `revoked` / `rejected` / `poll-timeout`; `info(request)` sends a `genm` for one of the four support messages — `{ caCerts }`, `{ rootCaCert }`, `{ certReqTemplate }`, `{ crlUpdate }` — and returns `answered` with the decoded `value` and a `present` flag, since an absent response value is how each says nothing is available. A session revokes its own certificate: the signature over the request is the proof of authorization (§4.2), so the named certificate must be `opts.cert` and a PBMAC1 session is refused. The signature flavor requires `opts.trustAnchors` to authenticate the CA; a verified rejection or error and an exhausted poll budget are terminal verdicts, while a tampered, untrusted, or desynchronized response is a typed throw. Returns DER, or a PEM `CMP` block with `opts.pem`; malformed input throws a typed `CmpError`. Parsing stays at `pki.schema.cmp.parse` — `build`, `transfer`, `wellKnownUrl`, `verify`, `session` |
239
239
  | `pki.crl` | CRL issuance and verification (RFC 5280 §5). `sign(spec, issuer, opts)` builds and signs a `CertificateList` from a `spec` of `thisUpdate` and `nextUpdate`, an optional `crlNumber`, a `revoked` array (each entry a `serialNumber` and `revocationDate` with an optional `reason` or `invalidityDate`), and an optional `extensions` object (authority key identifier, issuing distribution point, delta-CRL indicator, freshest CRL, authority information access) or an array of pre-encoded Extension DER, with an `issuer` of `{ cert, key }` or `{ name, publicKey, key }`. The signature algorithm is resolved from the issuer key, so RSA (PKCS#1 v1.5 or PSS via `opts.pss`), ECDSA, EdDSA, ML-DSA, SLH-DSA, and the composite arms all sign without a per-algorithm branch. The version is derived from the extension set (v2 when any CRL or entry extension is present, else v1), the outer `signatureAlgorithm` matches `tbsCertList.signature`, an empty revocation list omits the field rather than emitting an empty SEQUENCE, `reasonCode` is an ENUMERATED and `invalidityDate` is always GeneralizedTime, the RFC fixes per-extension criticality, and the produced signature is verified under the issuer key before return. `verify(crl, issuer)` checks a CRL signature through the one path-validation signature engine, algorithm-confusion and EdDSA low-order gates included; handed a certificate rather than a bare key it also asks what only a certificate can answer — that the certificate is the issuer the CRL names, and that its `keyUsage`, when present, asserts `cRLSign` — so a CRL minted under an end-entity certificate of the same CA does not verify as that CA's. `isRevoked(crl, serialNumber, opts)` looks a serial up, and first checks that the CRL is one a serial can be looked up in at all — it is handed a serial and nothing else, so a CRL that speaks for part of its issuer's certificates is refused rather than answered from. A delta CRL lists changes since a base, so an entry recording a release reads as a revocation when read alone; an indirect CRL carries other issuers' entries, whose serials are unrelated to yours; and any other `issuingDistributionPoint` narrows the CRL to one distribution point, one kind of certificate, or a subset of revocation reasons, none of which a serial can be matched against. A CRL speaks for a span as well as a set, so `opts.time` states the instant the question is asked at and a list that has stopped speaking for it — `nextUpdate` passed, `thisUpdate` later, or no `nextUpdate` stated at all — is refused rather than read as a clean bill of health; without `opts.time` the lookup is structural and an absent serial means only that it is not on that list. `pki.path.crlChecker` is the verb for all of them: it is handed the certificate, merges a delta with its base, performs the §6.3.3 correspondence, and decides currency against the material it fetched. Returns DER, or a PEM `X509 CRL` with `opts.pem`; malformed input throws a typed `CrlError`. Parsing stays at `pki.schema.crl.parse` — `sign`, `verify`, `isRevoked` |
240
240
  | `pki.key` | Key-material lifecycle (RFC 5958 / RFC 8018). `encrypt(privateKey, password, opts)` wraps a PKCS#8 private key (DER, PEM, or an extractable `CryptoKey`) into an `EncryptedPrivateKeyInfo` under PBES2 (PBKDF2 with AES-CBC-Pad), where `opts` selects the `cipher` (`aes-256-cbc` default, `aes-192-cbc`, `aes-128-cbc`), the `prf` (`hmacWithSHA256` default, SHA-384/512, SHA-1), the `iterations` (default 600000), and the `salt`. The plaintext is validated as PKCS#8 before encryption, a default `prf` and `keyLength` are omitted so the parameters are byte-exact with OpenSSL, and the output is re-parsed before return. `decrypt(encrypted, password, opts)` recovers the inner `PrivateKeyInfo`, re-validated through `pki.schema.pkcs8.parse`: only PBES2 / PBKDF2 / AES-CBC is accepted (PBES1, PBMAC1, and scrypt are refused), the salt and iteration count are bounded before any derivation (`opts.maxIterations` lowers the cap), and a malformed parameter set or wrong-length IV is a distinct typed error. Because a MAC-less PBES2-CBC decrypt must not become a padding oracle (RFC 8018 §8), a wrong password and a valid-pad-but-not-a-key both surface the one uniform `key/decrypt-failed`. `export(key, opts)` and `import(input, opts)` move a private key as PKCS#8 or a public key as SubjectPublicKeyInfo. The key may come from the platform's WebCrypto or from a separately installed copy of this toolkit, and is exported through whichever holds its material; a non-extractable key, or one whose implementation keeps its material out of reach, is refused with that as the reason. Encoding is delegated to WebCrypto, so RSA carries an explicit NULL, EC a named curve, and Ed25519/Ed448/X25519/X448 omit parameters, and an ambiguous RSA or EC import requires `opts.algorithm`. `generate(algorithm, opts)` produces a key pair over RSA, ECDSA/ECDH, the Edwards and Montgomery curves, and the FIPS post-quantum ML-DSA and ML-KEM; `publicFromPrivate(privateKey)` derives the public key. Returns DER or PEM, with a typed `KeyError` on failure. Parsing stays at `pki.schema.pkcs8.parse` — `encrypt`, `decrypt`, `export`, `import`, `generate`, `publicFromPrivate` |
241
241
  | `pki.pkcs12` | PKCS#12 (.p12/.pfx) issuance and reading (RFC 7292 / RFC 9579). `build(spec, opts)` assembles a store from the OpenSSL-style `{ key, cert, ca?, friendlyName?, localKeyId? }` or the full `{ safeContents: [...] }`, where each element is a plaintext or PBES2-encrypted `SafeContents` of key, shroudedKey, cert, crl, secret, or nested `safeContents` bags. Keys and certs are validated before wrapping, and `friendlyName` (BMPString) and `localKeyId` are single-value. Integrity is a classic Appendix B HMAC (the default, for maximum interoperability) or an RFC 9579 PBMAC1 (`opts.mac.algorithm`) over SHA-256/384/512, with shrouded keys and cert safes encrypted under RFC 8018 PBES2 (AES-128/192/256-CBC). Every password is encoded the PKCS#12 way — BMPString+NULL for the classic MAC, UTF-8 for the PBES2 bags and PBMAC1 — which is what OpenSSL and NSS consume, so a file it emits opens in both, cross-checked bidirectionally. The MAC covers the exact AuthenticatedSafe byte range, a DEFAULT-1 `MacData.iterations` is rejected up front, and the store is re-parsed before return. `verifyMac(pfx, password, opts)` recomputes a classic or PBMAC1 MAC over `macedBytes` and constant-time-compares it, throwing on a MAC-less or public-key-integrity store. Public-key integrity (`opts.integrity.mode: "public-key"`) wraps the AuthenticatedSafe in a CMS SignedData instead of a MAC, signed by any `pki.cms.sign` signer and carrying no MacData (§4); privacy stays independent, so `password` still PBES2-encrypts the bags. Public-key privacy wraps a SafeContents as a CMS EnvelopedData (AES-CBC, `id-envelopedData`, never GCM) encrypted to recipient public keys through the `pki.cms.encrypt` recipient model, via per-safe `recipients` or the `opts.recipientCerts` convenience, restricted to certificate recipients (RSA-OAEP, ECDH, X25519, X448, ML-KEM) since a password or KEK recipient could not be reopened by `open`. All four integrity-by-privacy combinations are permitted (§3.1). `open(pfx, password, opts)` reads a store back: it verifies the MAC first, so a wrong password is the MAC verdict rather than a decrypt error, then PBES2-decrypts every privacy safe and shrouded key bag and returns `{ integrityMode, macVerified, signers, keys, certs, crls, secrets }` — keys as re-validated PKCS#8 DER, certs, CRLs and secrets as raw DER, all with `friendlyName` and `localKeyId`, nested safes recursively. A MAC-less store is refused unless `opts.allowUnauthenticated`. A public-key-integrity store is verified through its CMS SignedData signature first (`pkcs12/signature-invalid` on failure), with the signer surfaced in `signers` but never trust-chained, which remains the caller's `pki.path.validate` step. A legacy-PBE store's Appendix C 3DES and RC2 bags are decrypted, RC2 through an in-tree RFC 2268 cipher, so an `openssl pkcs12 -legacy` or NSS store opens; the legacy RC4 schemes are refused. An `id-envelopedData` safe is decrypted with `opts.recipientKey` after the integrity gate (`pkcs12/no-recipient-key` when absent), every recipient-side fault and every post-integrity decrypt failure collapsing to the uniform `pkcs12/decrypt-failed`, and `opts.keys: 'crypto'` imports each key to a `CryptoKey`. It reads what OpenSSL and NSS produce. Returns DER or a PEM `PKCS12`, with a typed `Pkcs12Error` on failure. Parsing stays at `pki.schema.pkcs12.parse` — `build`, `verifyMac`, `open` |
@@ -248,6 +248,7 @@ comment blocks, is at [pkijs.com](https://pkijs.com).
248
248
  | `pki.trust` | Mozilla and CCADB trust-store ingestion. `parseCertdata` reads the NSS `certdata.txt` object stream and `parseCcadbCsv` the CCADB CSV export, both into one constraint-carrying anchor shape: the per-purpose trust bits, where only `CKT_NSS_TRUSTED_DELEGATOR` grants, and the per-purpose distrust-after dates the bare root list omits. Certificate and trust objects pair by byte-exact issuer and serial rather than adjacency and are cross-checked against the parsed DER, so metadata cannot attach to the wrong root. `anchor()` hands an entry to `pki.path.validate({ trustAnchor, checkPurpose })`. Offline, fail-closed, bounded — `parseCertdata`, `parseCcadbCsv`, `anchor` |
249
249
  | `pki.shbs` | Stateful hash-based signature verification: HSS/LMS (RFC 8554), carried in X.509 by RFC 9802 and in CMS by RFC 9708, profiled by NIST SP 800-208 for CNSA 2.0 firmware signing. `verify` checks an HSS signature, where every level must pass, and `verifyLms` a single-tree LMS, over the raw public-key and signature blobs the parsers already surface. Pure public-input SHA-256 and SHAKE256 hashing, a data-driven typecode registry, and bounds-before-slice reads; a malformed blob throws a typed `ShbsError` while a well-formed but wrong signature returns `false`. Verification only by design, since stateful signing needs atomic one-time-key state that belongs in an HSM — `verify`, `verifyLms` |
250
250
  | `pki.hpke` | Hybrid Public Key Encryption (RFC 9180), the encrypt-to-a-public-key primitive behind TLS ECH, MLS, and OHTTP. `setupS` and `setupR` establish a sender or recipient context (KEM encapsulation plus the HKDF key schedule); the context's `seal` and `open` AEAD-encrypt with a sequence-counter nonce, and `export` derives further secrets; the module-level `seal` and `open` are single-shot wrappers. DHKEM (P-256, P-521, X25519, X448) by HKDF-SHA256/SHA512 by AES-GCM / ChaCha20Poly1305 / export-only, across all four modes, proven against the RFC 9180 Appendix A vectors. DHKEM(P-384) and HKDF-SHA384 are RFC-registered but Appendix A ships no vector for them, so they fail closed until an authoritative KAT exists. Pure composition over `node:crypto`; ML-KEM and X-Wing are a registry data-row extension pending stable drafts — `suites`, `setupS`, `setupR`, `seal`, `open` |
251
+ | `pki.kem` | Composite ML-KEM key establishment (draft-ietf-lamps-pq-composite-kem), a post-quantum ML-KEM hybridized with a traditional RSA-OAEP, ECDH, X25519, or X448 so the established secret holds if either component is later broken. `encapsulate` turns a recipient's composite `SubjectPublicKeyInfo` into a 256-bit shared secret and a ciphertext; `decapsulate` recovers the same secret from the ciphertext and the composite PKCS#8 private key. Each component KEM runs independently and the two secrets are mixed through a SHA3-256 combiner that binds the traditional ciphertext, the traditional public key, and a per-algorithm label. The twelve algorithms pair ML-KEM-768 and ML-KEM-1024 with RSA-OAEP 2048/3072/4096, ECDH over P-256/P-384/P-521 and brainpoolP256r1/P384r1, X25519, and X448, each verified against the draft Appendix G known-answer vectors; a malformed key or ciphertext, an unsupported algorithm, or a component decapsulation failure throws a typed `KemError` — `encapsulate`, `decapsulate` |
251
252
  | `pki.sigstore` | Offline verifier for a Sigstore bundle, the artifact `npm publish --provenance` produces and the registry serves. `verifyBundle` composes five fail-closed legs against caller-pinned trust (Fulcio CA roots and Rekor log keys, never trusted from the bundle): the DSSE signature over its PAE preimage under the Fulcio leaf key, the ephemeral Fulcio certificate chain validated as of the Rekor log time, the RFC 9162 inclusion proof folded to a Rekor-signed tree root, the log entry bound to this exact signature, and the in-toto SLSA subject digest the caller confirms against the published artifact. It reuses the X.509 parser, the RFC 5280 path validator, and the Merkle verifier; the net-new codecs are the DSSE PAE byte-builder and a fail-closed JSON reader. `verified: true` says the artifact was signed and logged, not that a party you trust signed it — Fulcio issues to anyone who completes an OIDC flow, so who signed is decided only by `opts.identity`, and `identityChecked` reports which of its fields were compared. An identity policy naming no field, or a field name that is not one of the three, is refused rather than satisfied — either would accept every signer while reading as a policy in force — `pae`, `parseBundle`, `verifyBundle` |
252
253
  | `pki.inspect` | Human-readable inspection, the pure-JS equivalent of `openssl x509/crl/req/cms -text`. `certificate(pem \| der \| parsed)` renders an OpenSSL-style report: version, serial, signature algorithm, issuer and subject distinguished names, validity, public-key details (curve or modulus size plus the raw point or modulus), every decoded extension with its critical flag, and the signature. `crl`, `csr`, and `cms` render the other formats the same way — a CRL like `openssl crl -text`, a CSR like `openssl req -text`, and a CMS message like `openssl cms -cmsout -print`, with a stable summary for a non-SignedData ContentInfo — and `any(input)` detects the format and routes to the right report. Built over the strict parsers and the two-way OID registry with one set of field renderers, it names extension and algorithm OIDs an OpenSSL build shows only as raw bytes. No OpenSSL dependency, and the format is stable and OpenSSL-familiar rather than pinned to one OpenSSL version. A certificate policy's user notice renders as text, both its explicit text and a notice reference with the notice numbers that identify it, rather than hex, and a malformed part falls back to a hex dump rather than throwing — `certificate`, `crl`, `csr`, `cms`, `any` |
253
254
  | `pki.webauthn` | WebAuthn and passkey verification, both halves: offline trust evaluation of a W3C WebAuthn (Level 3) registration, and signature verification of the assertion every login returns. `parseAttestationObject(bytes)` decodes the CBOR attestation object, authenticatorData, and COSE credential key over the strict `pki.cbor` codec; `parseAuthenticatorData(bytes)` reads the bare form an assertion carries through the same parser; `parseClientData(bytes, opts)` decodes the `clientDataJSON` no signature check looks inside, through the shared JSON guard since these are attacker-chosen bytes, returning the challenge decoded so a caller compares bytes rather than spellings, and checking the ceremony type, challenge, and origin when the relying party supplies what it issued. `verifyAssertion(input)` verifies an assertion signature over `authenticatorData \|\| SHA-256(clientDataJSON)` — raw bytes, no COSE_Sign1, an ES256 signature in ASN.1 DER — and applies the §7.2 step 21 counter rule when a stored `previousSignCount` is given, so a counter that fails to advance is refused as a cloned authenticator. `verify(attestationObject, clientDataHash, opts)` checks the attestation-statement signature and each format's structural bindings for packed, tpm, android-key, apple, fido-u2f, and none: the x5c leaf key, the apple nonce, the tpm `certInfo` Name and `extraData` over the `pubArea`, the android `KeyDescription`, and the fido-u2f `verificationData`. It binds the credential public key to each attestation, through the signed authenticatorData for packed and fido-u2f or a cert or `pubArea`-key equality check for android-key, apple, and tpm, and enforces each leaf's certificate requirements. The credential-key check covers the full WebAuthn COSE algorithm set — ES256/384/512, RS256/384/512, PS256/384/512, EdDSA (Ed25519), and the RFC 9864 fully-specified identifiers ESP256/384/512, Ed25519, and Ed448 — validating the public-key point on its curve, rejecting the compressed EC point form, and enforcing a minimally encoded DER ECDSA signature. The verdict field is `attestationVerified`, and `signatureVerified` for an assertion, rather than a bare `verified`, because a sound statement is a different claim from an acceptable ceremony: an attestation naming another origin's RP ID with user presence clear is perfectly sound and must not be registered. Pass `expectedRpId`, `requireUserPresence`, `requireUserVerification`, or `allowedAlgorithms` and those are checked, with `bindingChecked` reporting which ran, so a check that passed can be told from one that never happened. Pass `opts.clientDataJSON` instead of the digest and the client data is read here too: the ceremony type is checked unconditionally, since a login response replayed into a registration is what that rule stops, and the challenge, origin, and top-level origin are checked against what the relying party issued, with `clientData.checked` reporting which comparisons ran. A registration verdict also carries the `credentialId`, `credentialPublicKey`, and initial `signCount` a later login needs. A credential key declaring COSE algorithm `-65535` (RSASSA-PKCS1-v1_5 with SHA-1) is refused unless `allowedAlgorithms` names it, since every signature that credential ever makes would use SHA-1. Anchoring the trust path has two routes: `opts.metadata` resolves the roots the authenticator's own model registered, and `opts.rootCertificates` pins roots directly, which is what anchors the formats FIDO MDS does not cover, Apple's authenticators and the Google hardware-attestation roots among them. `metadata` governs when both are given, and `anchoredTo` names every route that anchored the path, joined with `+` when more than one did: `"metadata"`, `"rootCertificates"`, and `"safetyNetRoots"` for the android-safetynet chain, which anchors through the roots that format requires whether or not either other route was asked for. It is `null` only when nothing anchored the path. `verifyMetadataBlob(blob, opts)` reads a FIDO Metadata Service (MDS v3) BLOB, the signed catalogue of registered authenticator models, verifying its JWS and chaining its signer to an operator-supplied FIDO root before the payload is parsed, with sequence-number rollback and `nextUpdate` freshness checks. Passing the result as `opts.metadata` to `verify` resolves the authenticator's registered attestation roots from its identifier and requires the trust path to fully validate to one of them, refusing an unlisted or revoked model. `metadataAnchors(entry, opts)` applies the same status gate for a caller anchoring the path themselves: a model the catalogue has disqualified registers no anchors. Both of the catalogue's key spaces are covered: an aaguid, and the attestation-certificate key identifiers a U2F authenticator is listed under instead. No FIDO root is bundled, there is no trust-on-first-use, and retrieving the BLOB is out of scope. Fail-closed with typed `webauthn/*` errors — `parseAttestationObject`, `verify`, `verifyMetadataBlob`, `metadataFor`, `metadataAnchors` |
package/index.js CHANGED
@@ -53,6 +53,7 @@ var pkcs12 = require("./lib/pkcs12-build");
53
53
  var merkle = require("./lib/merkle");
54
54
  var shbs = require("./lib/shbs");
55
55
  var hpke = require("./lib/hpke");
56
+ var compositeKem = require("./lib/composite-kem");
56
57
  var sigstore = require("./lib/sigstore");
57
58
  var est = require("./lib/est");
58
59
  var scep = require("./lib/scep");
@@ -156,6 +157,10 @@ module.exports = {
156
157
  // schedule + AEAD context construction behind TLS ECH / MLS / OHTTP. Pure
157
158
  // composition over node:crypto; the classical DHKEM suites, all four modes.
158
159
  hpke: hpke,
160
+ // `kem` is composite ML-KEM key establishment (draft-ietf-lamps-pq-composite-kem):
161
+ // pki.kem.encapsulate / decapsulate over a post-quantum ML-KEM hybridized with a
162
+ // traditional RSA-OAEP / ECDH / X25519 / X448, mixed through the SHA3-256 combiner.
163
+ kem: compositeKem,
159
164
  // `sigstore` verifies a Sigstore bundle (the npm --provenance artifact): a
160
165
  // keyless Fulcio signature over a DSSE-wrapped in-toto SLSA attestation with a
161
166
  // Rekor inclusion proof -- offline, zero-dep, against caller-pinned trust.
package/lib/cmp-build.js CHANGED
@@ -92,17 +92,17 @@ var KNOWN_HEADER_KEYS = {
92
92
  transactionID: 1, senderNonce: 1, recipNonce: 1, freeText: 1, generalInfo: 1,
93
93
  };
94
94
  var KNOWN_BODY_KEYS = {
95
- ir: 1, cr: 1, kur: 1, p10cr: 1, certConf: 1, pollReq: 1, genm: 1, rr: 1, // request-side
95
+ ir: 1, cr: 1, kur: 1, krr: 1, p10cr: 1, certConf: 1, pollReq: 1, genm: 1, rr: 1, // request-side
96
96
  ip: 1, cp: 1, kup: 1, ccp: 1, krp: 1, rp: 1, genp: 1, error: 1, pollRep: 1, pkiconf: 1, // CA/responder-side
97
97
  nested: 1, // an RA wrapper of complete, independently-protected PKIMessages (RFC 9810 sec. 5.1.3.5)
98
98
  };
99
99
  // The PKIBody arm -> its EXPLICIT context tag number (schema-cmp.js BODY_ARMS). rr is [11], not [15].
100
100
  var BODY_TAG = {
101
- ir: 0, cr: 2, p10cr: 4, kur: 7, rr: 11, genm: 21, certConf: 24, pollReq: 25,
101
+ ir: 0, cr: 2, p10cr: 4, kur: 7, krr: 9, rr: 11, genm: 21, certConf: 24, pollReq: 25,
102
102
  ip: 1, cp: 3, kup: 8, krp: 10, rp: 12, ccp: 14, pkiconf: 19, genp: 22, error: 23, pollRep: 26,
103
103
  nested: 20, // NestedMessageContent (schema-cmp.js BODY_ARMS [20])
104
104
  };
105
- var CRMF_BODY = { ir: 1, cr: 1, kur: 1 }; // arms whose content is a CertReqMessages via pki.crmf.build
105
+ var CRMF_BODY = { ir: 1, cr: 1, kur: 1, krr: 1 }; // arms whose content is a CertReqMessages via pki.crmf.build (RFC 9810 sec. 5.3.7 krr)
106
106
  var CERT_REP_ARM = { ip: 1, cp: 1, kup: 1, ccp: 1 }; // arms carrying a CertRepMessage
107
107
  // Protection has two mutually exclusive forms, and the signature parameters are read only by the
108
108
  // signature one: under PBMAC1 a requested pss or digestAlgorithm selects nothing and the message
@@ -896,7 +896,8 @@ function _collectExtraCerts(opts, protCertDer) {
896
896
  * Build an RFC 9810 CMP `PKIMessage` -- the producing-side inverse of `pki.schema.cmp.parse`. `message` is
897
897
  * `{ header, body }`: `header` carries the `sender` / `recipient` GeneralNames plus optional transaction
898
898
  * metadata (`transactionID`, `senderNonce`, `messageTime`, `freeText`, `generalInfo`, ...); `body` is a
899
- * single-key object naming the arm. Request-side: `{ ir }` / `{ cr }` / `{ kur }` (a `CertReqMessages` spec
899
+ * single-key object naming the arm. Request-side: `{ ir }` / `{ cr }` / `{ kur }` / `{ krr }` (key recovery,
900
+ * RFC 9810 sec. 5.3.7; a `CertReqMessages` spec
900
901
  * delegated to `pki.crmf.build`; the proof-of-possession key is `key` on the arm spec), `{ p10cr }` (a PKCS#10
901
902
  * CertificationRequest DER), `{ certConf }`, `{ pollReq }`, `{ genm }`, `{ rr }`. CA/responder-side: `{ ip }` /
902
903
  * `{ cp }` / `{ kup }` / `{ ccp }` (a `CertRepMessage`: `caPubs` plus `response` of `CertResponse` each with a
@@ -0,0 +1,413 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ // Copyright (c) blamejs contributors
3
+ "use strict";
4
+ /**
5
+ * @module pki.kem
6
+ * @nav Protocols
7
+ * @title Composite ML-KEM
8
+ * @fullname Composite ML-KEM (draft-ietf-lamps-pq-composite-kem)
9
+ * @intro Composite ML-KEM key establishment (draft-ietf-lamps-pq-composite-kem): a post-quantum
10
+ * ML-KEM hybridized with a traditional RSA-OAEP, ECDH, X25519, or X448, so the established shared
11
+ * secret stays secure as long as EITHER component is unbroken. pki.kem.encapsulate turns a
12
+ * recipient's composite public key into a 256-bit shared secret and a ciphertext; pki.kem.decapsulate
13
+ * recovers the same secret from that ciphertext and the composite private key. Each component KEM
14
+ * runs independently, and the two secrets are mixed through the SHA3-256 combiner that also binds the
15
+ * traditional ciphertext, the traditional public key, and a per-algorithm label. All twelve registered
16
+ * algorithms -- ML-KEM-768 and ML-KEM-1024 paired with RSA-OAEP 2048/3072/4096, ECDH over
17
+ * P-256/P-384/P-521 and brainpool, X25519, and X448 -- are verified against the draft Appendix G
18
+ * known-answer vectors.
19
+ * @spec draft-ietf-lamps-pq-composite-kem
20
+ * @card Establish a shared secret with a hybrid post-quantum plus traditional KEM.
21
+ */
22
+ //
23
+ // ML-KEM runs on the toolkit's hardened WebCrypto surface (the FIPS 203 ciphertext-length check +
24
+ // shared-secret zeroization ride along); the traditional component uses node:crypto directly, as the
25
+ // sibling KEM module lib/hpke.js does, promoting RSA-OAEP into a KEM (a fresh random secret encrypted,
26
+ // draft sec. 2.1) and ECDH / X25519 / X448 into a KEM (an ephemeral public key as the ciphertext,
27
+ // draft sec. 2.2). The public key is mlkemEK || tradPK (sec. 4.1) in the SPKI BIT STRING; the private
28
+ // key is mlkemSeed || tradSK (sec. 4.2, a 64-byte ML-KEM seed) in the PKCS#8 privateKey OCTET STRING;
29
+ // the ciphertext is mlkemCT || tradCT (sec. 4.3). The ML-KEM component is the fixed-length first half,
30
+ // and the split point is its parameter-set length.
31
+
32
+ var asn1 = require("./asn1-der");
33
+ var oid = require("./oid");
34
+ var webcrypto = require("./webcrypto");
35
+ var nodeCrypto = require("node:crypto");
36
+ var frameworkError = require("./framework-error");
37
+ var guard = require("./guard-all");
38
+ var pkix = require("./schema-pkix");
39
+ var schemaPkcs8 = require("./schema-pkcs8");
40
+ var subtle = webcrypto.webcrypto.subtle;
41
+ var _b = asn1.build;
42
+ var KemError = frameworkError.KemError;
43
+ var PemError = frameworkError.PemError;
44
+ function _err(code, message, cause) { return new KemError(code, message, cause); }
45
+
46
+ // Accept a composite key as DER (any BufferSource, snapshotted at the door) or as a PEM block with the
47
+ // given label. A PEM decode fault is re-typed into the module's own KemError so the verb's documented
48
+ // "throws a typed KemError" contract holds for every input shape. PEM is detected with the shared armor
49
+ // check (so leading text before "-----BEGIN" is tolerated as elsewhere in the toolkit), and the byte
50
+ // source is snapshot-COPIED first: the async verbs read the key across await points, so it must not alias
51
+ // a caller buffer that can change underneath them (guard.bytes.source, which coerceToDer uses, aliases).
52
+ function _toDer(input, pemLabel, what) {
53
+ if (typeof input === "string") return _pemToDer(input, pemLabel);
54
+ var buf = guard.bytes.snapshotSource(input, KemError, "kem/bad-input", what);
55
+ if (pkix.isPemArmor(buf)) return _pemToDer(buf, pemLabel);
56
+ return buf;
57
+ }
58
+ function _pemToDer(text, label) {
59
+ try { return pkix.pemDecode(text, label, PemError); }
60
+ catch (e) { throw _err("kem/bad-key", "the PEM input is not a valid " + label + " block", e); }
61
+ }
62
+
63
+ // ---- registry (draft sec. 6) -------------------------------------------------
64
+ //
65
+ // One row per composite algorithm, keyed by the composite OID. `trad` is exactly one component shape,
66
+ // each carrying `ctLen`, the exact byte length of its traditional ciphertext component (RSA-OAEP block,
67
+ // EC uncompressed point, or raw OKP ephemeral key), so the composite ciphertext length is fixed and an
68
+ // oversized attacker-controlled component is refused before any key is built:
69
+ // { kind: "rsa", bits, ctLen } RSA-OAEP-KEM, OAEP SHA-256 / MGF1-SHA256 / empty label (sec. 6.1)
70
+ // { kind: "ec", node, curve, ctLen } ECDH DHKEM, `node` the node namedCurve, `curve` the curve OID name
71
+ // { kind: "okp", curve, ctLen } X25519 / X448 DHKEM, `curve` the registered OID name
72
+ // `label` is stored as the AUTHORITATIVE per-row bytes (draft sec. 6): most are ASCII, but the
73
+ // id-MLKEM768-X25519 label is the raw six bytes 5c2e2f2f5e5c and MUST NOT be derived from the name.
74
+ var COMPOSITE_KEM = {};
75
+ function _comp(name, mlkemBits, label, trad) {
76
+ var mlOidName = "id-ml-kem-" + mlkemBits;
77
+ var kp = oid.kemParams(mlOidName);
78
+ COMPOSITE_KEM[oid.byName(name)] = {
79
+ name: name, mlkemWc: "ML-KEM-" + mlkemBits, mlkemOidName: mlOidName,
80
+ mlkemCt: kp.ct, mlkemEk: kp.ek, label: label, trad: trad,
81
+ };
82
+ }
83
+ _comp("id-MLKEM768-RSA2048-SHA3-256", 768, Buffer.from("MLKEM768-RSAOAEP2048", "ascii"), { kind: "rsa", bits: 2048, ctLen: 256 });
84
+ _comp("id-MLKEM768-RSA3072-SHA3-256", 768, Buffer.from("MLKEM768-RSAOAEP3072", "ascii"), { kind: "rsa", bits: 3072, ctLen: 384 });
85
+ _comp("id-MLKEM768-RSA4096-SHA3-256", 768, Buffer.from("MLKEM768-RSAOAEP4096", "ascii"), { kind: "rsa", bits: 4096, ctLen: 512 });
86
+ _comp("id-MLKEM768-X25519-SHA3-256", 768, Buffer.from("5c2e2f2f5e5c", "hex"), { kind: "okp", curve: "X25519", ctLen: 32 });
87
+ _comp("id-MLKEM768-ECDH-P256-SHA3-256", 768, Buffer.from("MLKEM768-P256", "ascii"), { kind: "ec", node: "prime256v1", curve: "prime256v1", ctLen: 65 });
88
+ _comp("id-MLKEM768-ECDH-P384-SHA3-256", 768, Buffer.from("MLKEM768-P384", "ascii"), { kind: "ec", node: "secp384r1", curve: "secp384r1", ctLen: 97 });
89
+ _comp("id-MLKEM768-ECDH-brainpoolP256r1-SHA3-256", 768, Buffer.from("MLKEM768-BP256", "ascii"), { kind: "ec", node: "brainpoolP256r1", curve: "brainpoolP256r1", ctLen: 65 });
90
+ _comp("id-MLKEM1024-RSA3072-SHA3-256", 1024, Buffer.from("MLKEM1024-RSAOAEP3072", "ascii"), { kind: "rsa", bits: 3072, ctLen: 384 });
91
+ _comp("id-MLKEM1024-ECDH-P384-SHA3-256", 1024, Buffer.from("MLKEM1024-P384", "ascii"), { kind: "ec", node: "secp384r1", curve: "secp384r1", ctLen: 97 });
92
+ _comp("id-MLKEM1024-ECDH-brainpoolP384r1-SHA3-256", 1024, Buffer.from("MLKEM1024-BP384", "ascii"), { kind: "ec", node: "brainpoolP384r1", curve: "brainpoolP384r1", ctLen: 97 });
93
+ _comp("id-MLKEM1024-X448-SHA3-256", 1024, Buffer.from("MLKEM1024-X448", "ascii"), { kind: "okp", curve: "X448", ctLen: 56 });
94
+ _comp("id-MLKEM1024-ECDH-P521-SHA3-256", 1024, Buffer.from("MLKEM1024-P521", "ascii"), { kind: "ec", node: "secp521r1", curve: "secp521r1", ctLen: 133 });
95
+
96
+ var MLKEM_SEED = 64; // d || z, both 32 bytes (draft sec. 4.2)
97
+ var RSA_SS = 32; // ss_len for RSA-OAEP-KEM (draft sec. 6.1)
98
+
99
+ // ---- ML-KEM component (toolkit WebCrypto) ------------------------------------
100
+ //
101
+ // The private key is the 64-byte seed; node reconstructs the decapsulation key from a PKCS#8 whose
102
+ // privateKey OCTET STRING wraps the seed as a context-[0] primitive (the OpenSSL / draft seed form),
103
+ // not from node's own { seed } keygen option, whose seed convention differs.
104
+ function _mlkemSeedPkcs8(d, seed) {
105
+ return _b.sequence([
106
+ _b.integer(0n),
107
+ _b.sequence([_b.oid(oid.byName(d.mlkemOidName))]),
108
+ _b.octetString(_b.implicit(0, _b.octetString(seed))),
109
+ ]);
110
+ }
111
+ function _mlkemSpki(d, ek) {
112
+ return _b.sequence([_b.sequence([_b.oid(oid.byName(d.mlkemOidName))]), _b.bitString(ek, 0)]);
113
+ }
114
+ function _mlkemEncaps(d, mlkemEK) {
115
+ return subtle.importKey("spki", _mlkemSpki(d, mlkemEK), { name: d.mlkemWc }, false, ["encapsulateBits"])
116
+ .then(function (k) { return subtle.encapsulateBits({ name: d.mlkemWc }, k); })
117
+ .then(function (r) { return { ss: Buffer.from(r.sharedKey), ct: Buffer.from(r.ciphertext) }; })
118
+ // a malformed ML-KEM public-key half surfaces from the engine as a WebCryptoError; re-type it into
119
+ // the module's own KemError so the verb's typed-error contract holds. The chain runs only the
120
+ // WebCrypto component operations, which never raise a KemError, so the re-type is unconditional.
121
+ .catch(function (e) { throw _err("kem/bad-key", "the ML-KEM component public key is invalid", e); });
122
+ }
123
+ function _mlkemDecaps(d, seed, mlkemCT) {
124
+ return subtle.importKey("pkcs8", _mlkemSeedPkcs8(d, seed), { name: d.mlkemWc }, false, ["decapsulateBits"])
125
+ .then(function (k) { return subtle.decapsulateBits({ name: d.mlkemWc }, k, mlkemCT); })
126
+ .then(function (ss) { return Buffer.from(ss); })
127
+ // Defensive re-type mirroring _mlkemEncaps. Verified-unreachable from the shipped decapsulate path:
128
+ // the caller-checked split always supplies a valid 64-byte ML-KEM seed (any 64 bytes are a valid
129
+ // key) and an exact-parameter-set-length ML-KEM ciphertext, and ML-KEM decapsulation is implicitly
130
+ // rejecting, so neither the import nor the decapsulation of the ML-KEM half can fail here. Kept for
131
+ // node's experimental ML-KEM surface and for symmetry with the reachable encapsulate catch.
132
+ .catch(function (e) { throw _err("kem/bad-key", "the ML-KEM component private key is invalid", e); });
133
+ }
134
+
135
+ // ---- traditional component (node:crypto, like lib/hpke.js) -------------------
136
+ //
137
+ // The traditional public key encodings mixed into the combiner (draft sec. 4.1 / Appendix B): RSA is
138
+ // the RSAPublicKey DER, EC is the uncompressed X9.62 point, X25519 / X448 is the raw curve point.
139
+ function _ecPubFromPoint(d, point) {
140
+ // draft Appendix B: the EC component is the uncompressed X9.62 point (0x04 || X || Y). node would
141
+ // silently decompress a 0x02/0x03 point, so a compressed or hybrid form is refused here as non-canonical;
142
+ // createPublicKey then validates the length and that the point is on the curve.
143
+ if (point.length < 1 || point[0] !== 0x04) throw _err("kem/bad-key", "the EC component point is not in uncompressed form");
144
+ // SubjectPublicKeyInfo { AlgorithmIdentifier { ecPublicKey, namedCurve }, BIT STRING point }.
145
+ var spki = _b.sequence([_b.sequence([_b.oid(oid.byName("ecPublicKey")), _b.oid(oid.byName(d.trad.curve))]), _b.bitString(point, 0)]);
146
+ return nodeCrypto.createPublicKey({ key: spki, format: "der", type: "spki" });
147
+ }
148
+ function _okpPubFromRaw(d, raw) {
149
+ var spki = _b.sequence([_b.sequence([_b.oid(oid.byName(d.trad.curve))]), _b.bitString(raw, 0)]);
150
+ return nodeCrypto.createPublicKey({ key: spki, format: "der", type: "spki" });
151
+ }
152
+ function _okpPrivFromRaw(d, raw) {
153
+ var p8 = _b.sequence([_b.integer(0n), _b.sequence([_b.oid(oid.byName(d.trad.curve))]), _b.octetString(_b.octetString(raw))]);
154
+ return nodeCrypto.createPrivateKey({ key: p8, format: "der", type: "pkcs8" });
155
+ }
156
+ // The subjectPublicKey octets of a public KeyObject (the uncompressed EC point / raw OKP key), read
157
+ // off the SPKI export rather than a JWK export, which node cannot produce for the brainpool curves.
158
+ function _rawPubOf(keyObject) {
159
+ var spki = keyObject.export({ format: "der", type: "spki" });
160
+ return Buffer.from(asn1.read.bitString(asn1.decode(spki).children[1]).bytes);
161
+ }
162
+
163
+ function _tradEncaps(d, tradPK) {
164
+ var trad = d.trad;
165
+ if (trad.kind === "rsa") {
166
+ var pub;
167
+ try {
168
+ // node's createPublicKey ignores trailing bytes after the RSAPublicKey; decode strictly first so a
169
+ // composite key carrying extra bytes after the RSA component is refused (draft sec. 4.1: exact encoding).
170
+ asn1.decode(tradPK);
171
+ pub = nodeCrypto.createPublicKey({ key: tradPK, format: "der", type: "pkcs1" });
172
+ } catch (e) { return Promise.reject(_err("kem/bad-key", "the RSA component public key is not a valid RSAPublicKey", e)); }
173
+ if (pub.asymmetricKeyDetails.modulusLength !== trad.bits) return Promise.reject(_err("kem/bad-key", "the RSA component modulus is not " + trad.bits + " bits (draft sec. 6)"));
174
+ var ss = Buffer.from(nodeCrypto.randomBytes(RSA_SS));
175
+ var ct;
176
+ try { ct = Buffer.from(nodeCrypto.publicEncrypt({ key: pub, padding: nodeCrypto.constants.RSA_PKCS1_OAEP_PADDING, oaepHash: "sha256" }, ss)); }
177
+ catch (e) {
178
+ // the random secret is already allocated; wipe it before rejecting if the RSA public operation fails
179
+ // (draft sec. 3.5). On success it is returned and wiped by the combiner.
180
+ guard.secret.zeroize(ss, KemError, "kem/bad-input", "the RSA-OAEP component secret");
181
+ return Promise.reject(_err("kem/bad-key", "the RSA-OAEP component encryption failed", e));
182
+ }
183
+ return Promise.resolve({ ss: ss, ct: ct });
184
+ }
185
+ // DHKEM: an ephemeral keypair, the shared secret is DH(ephemeral, recipient), the ciphertext is the
186
+ // ephemeral public key in the component's own encoding (draft sec. 2.2). The Diffie-Hellman is inside
187
+ // the try: a structurally valid but low-order recipient point (e.g. an all-zero X25519 key) imports
188
+ // cleanly but makes node's diffieHellman throw, which must surface as a typed fault rather than a raw
189
+ // OpenSSL error escaping the encapsulation.
190
+ var dh, dhCt;
191
+ try {
192
+ var recip = trad.kind === "ec" ? _ecPubFromPoint(d, tradPK) : _okpPubFromRaw(d, tradPK);
193
+ var eph = trad.kind === "ec" ? nodeCrypto.generateKeyPairSync("ec", { namedCurve: trad.node }) : nodeCrypto.generateKeyPairSync(trad.curve.toLowerCase());
194
+ dh = Buffer.from(nodeCrypto.diffieHellman({ privateKey: eph.privateKey, publicKey: recip }));
195
+ dhCt = _rawPubOf(eph.publicKey);
196
+ } catch (e) { return Promise.reject(_err("kem/bad-key", "the " + trad.curve + " public key is invalid", e)); }
197
+ return Promise.resolve({ ss: dh, ct: dhCt });
198
+ }
199
+
200
+ function _tradDecaps(d, tradSK, tradCT) {
201
+ var trad = d.trad;
202
+ if (trad.kind === "rsa") {
203
+ var priv;
204
+ try {
205
+ // node's createPrivateKey ignores trailing bytes after the RSAPrivateKey; decode strictly first so a
206
+ // composite key carrying extra bytes after the RSA component is refused (draft sec. 4.2: exact encoding).
207
+ asn1.decode(tradSK);
208
+ priv = nodeCrypto.createPrivateKey({ key: tradSK, format: "der", type: "pkcs1" });
209
+ } catch (e) { return Promise.reject(_err("kem/bad-key", "the RSA component private key is not a valid RSAPrivateKey", e)); }
210
+ if (priv.asymmetricKeyDetails.modulusLength !== trad.bits) return Promise.reject(_err("kem/bad-key", "the RSA component modulus is not " + trad.bits + " bits (draft sec. 6)"));
211
+ var ss;
212
+ // OAEP-invalid ciphertext and valid-padding-wrong-length plaintext MUST fail identically: a distinct
213
+ // verdict for either is an RSA-OAEP padding-validity oracle (Manger). Both reject with the same code
214
+ // and message AND no cause (the OpenSSL error is dropped, since it too would tell the paths apart), so
215
+ // the caller cannot tell the failure reason apart. draft sec. 2.1 fixes the transported secret at 32
216
+ // bytes; a plaintext of any other length is wiped and rejected here with that same verdict (sec. 3.5).
217
+ try { ss = Buffer.from(nodeCrypto.privateDecrypt({ key: priv, padding: nodeCrypto.constants.RSA_PKCS1_OAEP_PADDING, oaepHash: "sha256" }, tradCT)); }
218
+ catch (_e) { return Promise.reject(_err("kem/decapsulation-failed", "the RSA-OAEP component decryption failed")); }
219
+ if (ss.length !== RSA_SS) {
220
+ guard.secret.zeroize(ss, KemError, "kem/bad-input", "the RSA-OAEP component secret");
221
+ return Promise.reject(_err("kem/decapsulation-failed", "the RSA-OAEP component decryption failed"));
222
+ }
223
+ // The combiner input tradPK is the RSAPublicKey DER (n, e), draft sec. 4.1, taken from the key object.
224
+ return Promise.resolve({ ss: ss, tradPK: Buffer.from(nodeCrypto.createPublicKey(priv).export({ format: "der", type: "pkcs1" })) });
225
+ }
226
+ var priv2, eph;
227
+ try {
228
+ if (trad.kind === "ec") {
229
+ // node's SEC1 reader ignores trailing bytes after the ECPrivateKey; decode strictly first so a
230
+ // composite key carrying extra bytes after the EC component is refused (draft sec. 4.2, exact encoding).
231
+ asn1.decode(tradSK);
232
+ priv2 = nodeCrypto.createPrivateKey({ key: tradSK, format: "der", type: "sec1" });
233
+ } else {
234
+ // the OKP private key is a fixed-length raw scalar; node rejects any wrong length, trailing included.
235
+ priv2 = _okpPrivFromRaw(d, tradSK);
236
+ }
237
+ eph = trad.kind === "ec" ? _ecPubFromPoint(d, tradCT) : _okpPubFromRaw(d, tradCT);
238
+ } catch (e) { return Promise.reject(_err("kem/bad-key", "the " + trad.curve + " key material is invalid", e)); }
239
+ var dh;
240
+ try { dh = Buffer.from(nodeCrypto.diffieHellman({ privateKey: priv2, publicKey: eph })); }
241
+ catch (e) { return Promise.reject(_err("kem/decapsulation-failed", "the " + trad.curve + " Diffie-Hellman failed", e)); }
242
+ return Promise.resolve({ ss: dh, tradPK: _rawPubOf(nodeCrypto.createPublicKey(priv2)) });
243
+ }
244
+
245
+ // ---- combiner (draft sec. 3.4) -----------------------------------------------
246
+ function _combine(d, mlkemSS, tradSS, tradCT, tradPK) {
247
+ var preimage = Buffer.concat([mlkemSS, tradSS, tradCT, tradPK, d.label]);
248
+ return subtle.digest("SHA3-256", preimage).then(function (h) {
249
+ return Buffer.from(h);
250
+ }).finally(function () {
251
+ // draft sec. 3.5: clear the intermediate key material on every path, whether the digest resolves or
252
+ // fails. Only the returned composite secret survives. tradCT / tradPK are public, but the preimage
253
+ // holds copies of both component shared secrets, and mlkemSS / tradSS are the component secrets.
254
+ guard.secret.zeroizeAll([preimage, mlkemSS, tradSS], KemError, "kem/bad-input", "a KEM combiner secret");
255
+ });
256
+ }
257
+
258
+ // Run the two component operations; if EITHER rejects, wipe the shared secret the OTHER already produced
259
+ // before re-throwing, so a component failure leaves no key material readable (draft sec. 3.5 -- clear all
260
+ // buffers and forward the error). On success the combiner wipes both component secrets. `secA` / `secB`
261
+ // extract the secret Buffer from each component's result.
262
+ async function _settleOrWipe(pA, pB, secA, secB) {
263
+ var s = await Promise.allSettled([pA, pB]);
264
+ if (s[0].status === "rejected" || s[1].status === "rejected") {
265
+ if (s[0].status === "fulfilled") guard.secret.zeroize(secA(s[0].value), KemError, "kem/bad-input", "an ML-KEM shared secret");
266
+ if (s[1].status === "fulfilled") guard.secret.zeroize(secB(s[1].value), KemError, "kem/bad-input", "a traditional shared secret");
267
+ throw s[0].status === "rejected" ? s[0].reason : s[1].reason;
268
+ }
269
+ return [s[0].value, s[1].value];
270
+ }
271
+
272
+ // ---- descriptor resolution ---------------------------------------------------
273
+ function _descriptor(algOid) {
274
+ var d = COMPOSITE_KEM[algOid];
275
+ if (!d) throw _err("kem/unsupported-algorithm", "not a composite ML-KEM algorithm: " + (oid.name(algOid) || algOid));
276
+ return d;
277
+ }
278
+ // Resolve the composite descriptor from an algorithm OID, enforcing the draft sec. 5.3 parameters-absent
279
+ // rule. Both verbs feed the same (oid, hasParams) here so the dispatch and the parameters rule live once,
280
+ // whether the AlgorithmIdentifier was read from a hand-decoded SPKI or a schema-parsed OneAsymmetricKey.
281
+ function _descriptorForAlg(algOid, hasParams) {
282
+ if (hasParams) throw _err("kem/bad-algorithm", "a composite ML-KEM AlgorithmIdentifier MUST have absent parameters (draft sec. 5.3)");
283
+ return _descriptor(algOid);
284
+ }
285
+ // A DER node is a universal SEQUENCE (SubjectPublicKeyInfo and AlgorithmIdentifier are both SEQUENCE, not
286
+ // SET or any other constructed tag): a SET carrying the same children is not a canonical encoding.
287
+ function _isSequence(node) {
288
+ return !!node && node.tagClass === "universal" && node.tagNumber === asn1.TAGS.SEQUENCE && !!node.children;
289
+ }
290
+ // Resolve the composite descriptor from a raw AlgorithmIdentifier node (the SPKI encapsulation path).
291
+ function _fromAlgId(algNode) {
292
+ if (!_isSequence(algNode) || algNode.children.length < 1) throw _err("kem/bad-algorithm", "the AlgorithmIdentifier is malformed");
293
+ var algOid;
294
+ try { algOid = asn1.read.oid(algNode.children[0]); }
295
+ catch (e) { throw _err("kem/bad-algorithm", "the AlgorithmIdentifier algorithm is not an OBJECT IDENTIFIER", e); }
296
+ return _descriptorForAlg(algOid, algNode.children.length > 1);
297
+ }
298
+
299
+ // ---- public verbs ------------------------------------------------------------
300
+
301
+ /**
302
+ * @primitive pki.kem.decapsulate
303
+ * @signature pki.kem.decapsulate(privateKey, ciphertext) -> Promise<Buffer>
304
+ * @since 0.6.6
305
+ * @status stable
306
+ * @spec draft-ietf-lamps-pq-composite-kem
307
+ * @defends harvest-now-decrypt-later (CWE-327)
308
+ * @related pki.kem.encapsulate
309
+ *
310
+ * Recover the 256-bit composite shared secret from a ciphertext. `privateKey` is the composite PKCS#8
311
+ * (a `OneAsymmetricKey` DER `Buffer` or `PRIVATE KEY` PEM whose `privateKeyAlgorithm` is a composite
312
+ * ML-KEM OID and whose `privateKey` octets are the raw `mlkemSeed || tradSK`, draft sec. 4.2);
313
+ * `ciphertext` is the composite ciphertext (`mlkemCT || tradCT`, sec. 4.3). The ML-KEM half and the
314
+ * traditional half are decapsulated independently and combined with SHA3-256, so the secret is
315
+ * recovered only when both components agree. A malformed key or ciphertext, an unsupported algorithm,
316
+ * or a component decapsulation failure throws a typed `KemError`.
317
+ *
318
+ * @example
319
+ * // requires: privatePkcs8Der -- the composite ML-KEM PKCS#8 private key (DER)
320
+ * // requires: ciphertext -- the composite KEM ciphertext received from the sender
321
+ * var secret = await pki.kem.decapsulate(privatePkcs8Der, ciphertext); // 32-byte Buffer
322
+ */
323
+ // async so any synchronous fault (an argument that is not a BufferSource, a malformed DER structure)
324
+ // leaves as a rejected promise rather than a synchronous throw, keeping the Promise-returning contract.
325
+ async function _decapsulate(privateKey, ciphertext) {
326
+ var pkcs8 = _toDer(privateKey, "PRIVATE KEY", "the composite ML-KEM private key");
327
+ var ct = guard.bytes.snapshotSource(ciphertext, KemError, "kem/bad-input", "the composite ML-KEM ciphertext");
328
+ var d, sk;
329
+ try {
330
+ try {
331
+ // Compose the shared strict OneAsymmetricKey parser so the version, the algorithm, and the optional
332
+ // [0]/[1] trailing fields are all validated once, rather than reading fixed positions and trusting
333
+ // the rest. The privateKey octets are the raw composite mlkemSeed || tradSK (draft sec. 4.2).
334
+ var info = schemaPkcs8.parse(pkcs8);
335
+ var alg = info.privateKeyAlgorithm;
336
+ d = _descriptorForAlg(alg.oid, alg.parameters !== null);
337
+ sk = Buffer.from(info.privateKey);
338
+ } catch (e) {
339
+ if (e instanceof KemError) throw e;
340
+ // the shared parser rejects a present `parameters` at the envelope; re-map it to the module's own
341
+ // parameters-absent verdict so both verbs report draft sec. 5.3 the same way.
342
+ if (e && e.code === "pkcs8/bad-algorithm-parameters") throw _err("kem/bad-algorithm", "a composite ML-KEM AlgorithmIdentifier MUST have absent parameters (draft sec. 5.3)", e);
343
+ throw _err("kem/bad-key", "the composite ML-KEM private key is not a well-formed OneAsymmetricKey", e);
344
+ }
345
+ try {
346
+ if (sk.length <= MLKEM_SEED) throw _err("kem/bad-key", "the composite private key is shorter than the ML-KEM seed");
347
+ // the composite ciphertext is a fixed length (the ML-KEM ciphertext plus the exact traditional
348
+ // component); reject any other length before building a key, so an attacker-controlled oversized
349
+ // traditional component cannot force an unbounded allocation (CWE-770).
350
+ if (ct.length !== d.mlkemCt + d.trad.ctLen) throw _err("kem/bad-ciphertext", "the composite ciphertext is not the expected " + (d.mlkemCt + d.trad.ctLen) + " bytes for " + d.name);
351
+ var seed = sk.subarray(0, MLKEM_SEED), tradSK = sk.subarray(MLKEM_SEED);
352
+ var mlkemCT = ct.subarray(0, d.mlkemCt), tradCT = ct.subarray(d.mlkemCt);
353
+ var r = await _settleOrWipe(_mlkemDecaps(d, seed, mlkemCT), _tradDecaps(d, tradSK, tradCT),
354
+ function (v) { return v; }, function (v) { return v.ss; });
355
+ return await _combine(d, r[0], r[1].ss, tradCT, r[1].tradPK);
356
+ } finally {
357
+ // the reconstructed private-key copy (ML-KEM seed || traditional private key) is wiped on every path,
358
+ // including the length-validation exits above.
359
+ guard.secret.zeroize(sk, KemError, "kem/bad-input", "the composite private key material");
360
+ }
361
+ } finally {
362
+ // the snapshotted PKCS#8 copy still holds the private-key octets; wipe it on every path (draft sec. 3.5).
363
+ guard.secret.zeroize(pkcs8, KemError, "kem/bad-input", "the composite private key DER");
364
+ }
365
+ }
366
+
367
+ /**
368
+ * @primitive pki.kem.encapsulate
369
+ * @signature pki.kem.encapsulate(publicKey) -> Promise<{ sharedSecret: Buffer, ciphertext: Buffer }>
370
+ * @since 0.6.6
371
+ * @status stable
372
+ * @spec draft-ietf-lamps-pq-composite-kem
373
+ * @defends harvest-now-decrypt-later (CWE-327)
374
+ * @related pki.kem.decapsulate
375
+ *
376
+ * Establish a 256-bit shared secret for a recipient's composite ML-KEM public key. `publicKey` is the
377
+ * composite `SubjectPublicKeyInfo` (a DER `Buffer` or `PUBLIC KEY` PEM whose algorithm is a composite
378
+ * ML-KEM OID and whose subjectPublicKey octets are the raw `mlkemEK || tradPK`, draft sec. 4.1).
379
+ * Returns the `sharedSecret` (a 32-byte `Buffer`) and the `ciphertext` (`mlkemCT || tradCT`) to send to
380
+ * the recipient, who recovers the same secret with `pki.kem.decapsulate`. The ML-KEM and traditional
381
+ * component encapsulations run independently and are mixed through SHA3-256. A malformed or unsupported
382
+ * public key throws a typed `KemError`.
383
+ *
384
+ * @example
385
+ * // requires: recipientSpkiDer -- the recipient's composite ML-KEM SubjectPublicKeyInfo (DER)
386
+ * var out = await pki.kem.encapsulate(recipientSpkiDer);
387
+ * out.sharedSecret.length === 32; // send out.ciphertext to the recipient
388
+ */
389
+ async function _encapsulate(publicKey) {
390
+ var spki = _toDer(publicKey, "PUBLIC KEY", "the composite ML-KEM public key");
391
+ var d, ek;
392
+ try {
393
+ var node = asn1.decode(spki);
394
+ if (!_isSequence(node) || node.children.length !== 2) throw _err("kem/bad-key", "the public key is not a well-formed SubjectPublicKeyInfo");
395
+ d = _fromAlgId(node.children[0]);
396
+ var bs = asn1.read.bitString(node.children[1]);
397
+ if (bs.unusedBits !== 0) throw _err("kem/bad-key", "the composite subjectPublicKey has unused bits");
398
+ ek = Buffer.from(bs.bytes);
399
+ } catch (e) { throw e instanceof KemError ? e : _err("kem/bad-key", "the composite ML-KEM public key is not valid DER", e); }
400
+ if (ek.length <= d.mlkemEk) throw _err("kem/bad-key", "the composite public key is shorter than the ML-KEM component");
401
+ var mlkemEK = ek.subarray(0, d.mlkemEk), tradPK = ek.subarray(d.mlkemEk);
402
+ var r = await _settleOrWipe(_mlkemEncaps(d, mlkemEK), _tradEncaps(d, tradPK),
403
+ function (v) { return v.ss; }, function (v) { return v.ss; });
404
+ var ss = await _combine(d, r[0].ss, r[1].ss, r[1].ct, tradPK);
405
+ return { sharedSecret: ss, ciphertext: Buffer.concat([r[0].ct, r[1].ct]) };
406
+ }
407
+
408
+ // Only the two verbs are public: this module IS the pki.kem namespace, so the internal registry stays
409
+ // unexported to keep it off the operator surface and immutable from outside.
410
+ module.exports = {
411
+ encapsulate: _encapsulate,
412
+ decapsulate: _decapsulate,
413
+ };
@@ -342,6 +342,9 @@ var AcmeError = defineClass("AcmeError", { withCause: true });
342
342
  var TrustError = defineClass("TrustError", { withCause: true });
343
343
  var ShbsError = defineClass("ShbsError", { withCause: true });
344
344
  var HpkeError = defineClass("HpkeError", { withCause: true });
345
+ // KemError -- a malformed composite ML-KEM key or ciphertext, or an unsupported
346
+ // composite algorithm (draft-ietf-lamps-pq-composite-kem). Raised by pki.kem.
347
+ var KemError = defineClass("KemError", { withCause: true });
345
348
  // SigstoreError -- a Sigstore bundle (npm --provenance artifact) that is not a
346
349
  // well-formed / verifiable keyless signature: a malformed or oversize JSON
347
350
  // bundle, an unknown media type or content arm, a DSSE envelope missing a
@@ -406,6 +409,7 @@ module.exports = {
406
409
  C509Error: C509Error,
407
410
  ShbsError: ShbsError,
408
411
  HpkeError: HpkeError,
412
+ KemError: KemError,
409
413
  SigstoreError: SigstoreError,
410
414
  InspectError: InspectError,
411
415
  WebauthnError: WebauthnError,
package/lib/oid.js CHANGED
@@ -394,7 +394,16 @@ var FAMILIES = {
394
394
  "id-MLDSA65-ECDSA-brainpoolP256r1-SHA512": 47, "id-MLDSA65-Ed25519-SHA512": 48,
395
395
  "id-MLDSA87-ECDSA-P384-SHA512": 49, "id-MLDSA87-ECDSA-brainpoolP384r1-SHA512": 50,
396
396
  "id-MLDSA87-Ed448-SHAKE256": 51, "id-MLDSA87-RSA3072-PSS-SHA512": 52,
397
- "id-MLDSA87-RSA4096-PSS-SHA512": 53, "id-MLDSA87-ECDSA-P521-SHA512": 54 } },
397
+ "id-MLDSA87-RSA4096-PSS-SHA512": 53, "id-MLDSA87-ECDSA-P521-SHA512": 54,
398
+ // Composite ML-KEM key-establishment algorithms (draft-ietf-lamps-pq-composite-kem
399
+ // sec. 6): a PQ ML-KEM paired with a traditional RSA-OAEP / ECDH / X25519 / X448 so the
400
+ // established secret stays safe if EITHER primitive is later broken.
401
+ "id-MLKEM768-RSA2048-SHA3-256": 55, "id-MLKEM768-RSA3072-SHA3-256": 56,
402
+ "id-MLKEM768-RSA4096-SHA3-256": 57, "id-MLKEM768-X25519-SHA3-256": 58,
403
+ "id-MLKEM768-ECDH-P256-SHA3-256": 59, "id-MLKEM768-ECDH-P384-SHA3-256": 60,
404
+ "id-MLKEM768-ECDH-brainpoolP256r1-SHA3-256": 61, "id-MLKEM1024-RSA3072-SHA3-256": 62,
405
+ "id-MLKEM1024-ECDH-P384-SHA3-256": 63, "id-MLKEM1024-ECDH-brainpoolP384r1-SHA3-256": 64,
406
+ "id-MLKEM1024-X448-SHA3-256": 65, "id-MLKEM1024-ECDH-P521-SHA3-256": 66 } },
398
407
 
399
408
  // RSA-KEM key-transport algorithm (RFC 9690, obsoletes RFC 5990) on the ISO
400
409
  // 18033-2 arc -- the kem OID an RSA KEMRecipientInfo carries (distinct from the
@@ -433,6 +442,9 @@ var FAMILIES = {
433
442
  // SECG named curves.
434
443
  secg: { base: [1, 3, 132, 0], of: { secp384r1: 34, secp521r1: 35 } },
435
444
 
445
+ // Brainpool named curves (RFC 5639).
446
+ brainpool: { base: [1, 3, 36, 3, 3, 2, 8, 1, 1], of: { brainpoolP256r1: 7, brainpoolP384r1: 11 } },
447
+
436
448
  // Edwards / Montgomery curves (RFC 8410).
437
449
  edwards: { base: [1, 3, 101], of: { X25519: 110, X448: 111, Ed25519: 112, Ed448: 113 } },
438
450
 
@@ -833,6 +845,14 @@ var _PARAMS_ABSENT = new Set();
833
845
  "id-MLDSA87-ECDSA-P384-SHA512", "id-MLDSA87-ECDSA-brainpoolP384r1-SHA512",
834
846
  "id-MLDSA87-Ed448-SHAKE256", "id-MLDSA87-RSA3072-PSS-SHA512",
835
847
  "id-MLDSA87-RSA4096-PSS-SHA512", "id-MLDSA87-ECDSA-P521-SHA512",
848
+ // Composite ML-KEM (draft-ietf-lamps-pq-composite-kem sec. 5.3: the parameters
849
+ // field MUST be absent for every composite KEM AlgorithmIdentifier).
850
+ "id-MLKEM768-RSA2048-SHA3-256", "id-MLKEM768-RSA3072-SHA3-256",
851
+ "id-MLKEM768-RSA4096-SHA3-256", "id-MLKEM768-X25519-SHA3-256",
852
+ "id-MLKEM768-ECDH-P256-SHA3-256", "id-MLKEM768-ECDH-P384-SHA3-256",
853
+ "id-MLKEM768-ECDH-brainpoolP256r1-SHA3-256", "id-MLKEM1024-RSA3072-SHA3-256",
854
+ "id-MLKEM1024-ECDH-P384-SHA3-256", "id-MLKEM1024-ECDH-brainpoolP384r1-SHA3-256",
855
+ "id-MLKEM1024-X448-SHA3-256", "id-MLKEM1024-ECDH-P521-SHA3-256",
836
856
  ].forEach(function (nm) {
837
857
  var d = byName(nm);
838
858
  // A seed-list typo must fail at module load -- admitting undefined would
@@ -851,10 +871,12 @@ var _PARAMS_ABSENT = new Set();
851
871
  * @related pki.oid.name, pki.oid.byName
852
872
  *
853
873
  * True when an AlgorithmIdentifier bearing this OID MUST encode its `parameters`
854
- * field as ABSENT (not an explicit NULL, not any bytes): the FIPS 204 ML-DSA and
855
- * FIPS 205 SLH-DSA signature families and the RFC 8410 Edwards / Montgomery
856
- * curves. The shared AlgorithmIdentifier decoder consults this and fails closed
857
- * on a present-parameters violation, so every format inherits the rule.
874
+ * field as ABSENT (not an explicit NULL, not any bytes). The post-quantum ML-DSA,
875
+ * SLH-DSA, and ML-KEM families, the composite ML-DSA and composite ML-KEM
876
+ * algorithms, HSS/LMS and XMSS, the HKDF key-derivation identifiers, and the
877
+ * RFC 8410 Edwards / Montgomery curves all carry this MUST. The shared
878
+ * AlgorithmIdentifier decoder consults this and fails closed on a
879
+ * present-parameters violation, so every format inherits the rule.
858
880
  *
859
881
  * @example
860
882
  * pki.oid.paramsMustBeAbsent(pki.oid.byName("id-slh-dsa-sha2-128s")); // -> true
@@ -1846,6 +1846,7 @@ module.exports = {
1846
1846
  charTable: _charTable, // build a code-point membership table from a string of allowed characters
1847
1847
  allCharsIn: _allCharsIn, // is a NON-EMPTY string composed only of table members (the /^[chars]+$/ family)
1848
1848
  coerceToDer: coerceToDer,
1849
+ isPemArmor: _isPemArmor, // does a byte source carry a PEM "-----BEGIN" armor (RFC 7468 leading text allowed)
1849
1850
  decodeRoot: decodeRoot,
1850
1851
  runParse: runParse,
1851
1852
  makeNS: makeNS,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@blamejs/pki",
3
- "version": "0.6.4",
3
+ "version": "0.6.6",
4
4
  "description": "Pure-JavaScript PKI toolkit that owns its stack — X.509, ASN.1/DER, CMS, PQC-first.",
5
5
  "license": "Apache-2.0",
6
6
  "author": "blamejs contributors",
package/sbom.cdx.json CHANGED
@@ -2,10 +2,10 @@
2
2
  "$schema": "http://cyclonedx.org/schema/bom-1.5.schema.json",
3
3
  "bomFormat": "CycloneDX",
4
4
  "specVersion": "1.5",
5
- "serialNumber": "urn:uuid:60d582b7-d6d3-4b88-ada8-0fefee2ea11f",
5
+ "serialNumber": "urn:uuid:a919550f-e9fd-4370-816d-2d179d45f774",
6
6
  "version": 1,
7
7
  "metadata": {
8
- "timestamp": "2026-08-31T01:06:56.435Z",
8
+ "timestamp": "2026-08-31T07:36:11.594Z",
9
9
  "lifecycles": [
10
10
  {
11
11
  "phase": "build"
@@ -19,14 +19,14 @@
19
19
  }
20
20
  ],
21
21
  "component": {
22
- "bom-ref": "@blamejs/pki@0.6.4",
22
+ "bom-ref": "@blamejs/pki@0.6.6",
23
23
  "type": "application",
24
24
  "name": "pki",
25
- "version": "0.6.4",
25
+ "version": "0.6.6",
26
26
  "scope": "required",
27
27
  "author": "blamejs contributors",
28
28
  "description": "Pure-JavaScript PKI toolkit that owns its stack — X.509, ASN.1/DER, CMS, PQC-first.",
29
- "purl": "pkg:npm/%40blamejs/pki@0.6.4",
29
+ "purl": "pkg:npm/%40blamejs/pki@0.6.6",
30
30
  "properties": [],
31
31
  "externalReferences": [
32
32
  {
@@ -54,7 +54,7 @@
54
54
  "components": [],
55
55
  "dependencies": [
56
56
  {
57
- "ref": "@blamejs/pki@0.6.4",
57
+ "ref": "@blamejs/pki@0.6.6",
58
58
  "dependsOn": []
59
59
  }
60
60
  ]