@blamejs/pki 0.6.5 → 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 +10 -1
- package/README.md +1 -0
- package/index.js +5 -0
- package/lib/composite-kem.js +413 -0
- package/lib/framework-error.js +4 -0
- package/lib/oid.js +27 -5
- package/lib/schema-pkix.js +1 -0
- package/package.json +1 -1
- package/sbom.cdx.json +6 -6
package/CHANGELOG.md
CHANGED
|
@@ -4,7 +4,16 @@ 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.
|
|
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
|
|
8
17
|
|
|
9
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).
|
|
10
19
|
|
package/README.md
CHANGED
|
@@ -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.
|
|
@@ -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
|
+
};
|
package/lib/framework-error.js
CHANGED
|
@@ -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)
|
|
855
|
-
*
|
|
856
|
-
*
|
|
857
|
-
*
|
|
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
|
package/lib/schema-pkix.js
CHANGED
|
@@ -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
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:
|
|
5
|
+
"serialNumber": "urn:uuid:a919550f-e9fd-4370-816d-2d179d45f774",
|
|
6
6
|
"version": 1,
|
|
7
7
|
"metadata": {
|
|
8
|
-
"timestamp": "2026-08-
|
|
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.
|
|
22
|
+
"bom-ref": "@blamejs/pki@0.6.6",
|
|
23
23
|
"type": "application",
|
|
24
24
|
"name": "pki",
|
|
25
|
-
"version": "0.6.
|
|
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.
|
|
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.
|
|
57
|
+
"ref": "@blamejs/pki@0.6.6",
|
|
58
58
|
"dependsOn": []
|
|
59
59
|
}
|
|
60
60
|
]
|