@noble/post-quantum 0.5.4 → 0.6.1

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/hybrid.js CHANGED
@@ -50,7 +50,8 @@
50
50
  *
51
51
  * - GPG:
52
52
  * • Concatenate keys.
53
- * • Combiner: SHA3-256(kemShare || ecdhShare || ciphertext || pubKey || algId || domSep || len(domSep))
53
+ * • Combiner:
54
+ * SHA3-256(kemShare || ecdhShare || ciphertext || pubKey || algId || domSep || len(domSep))
54
55
  *
55
56
  * - TLS:
56
57
  * • Transcript-based derivation (HKDF).
@@ -84,30 +85,66 @@ import { sha256 } from '@noble/hashes/sha2.js';
84
85
  import { sha3_256, shake256 } from '@noble/hashes/sha3.js';
85
86
  import { abytes, ahash, anumber } from '@noble/hashes/utils.js';
86
87
  import { ml_kem1024, ml_kem768 } from "./ml-kem.js";
87
- import { cleanBytes, randomBytes, splitCoder, } from "./utils.js";
88
+ import { cleanBytes, copyBytes, randomBytes, splitCoder, validateSigOpts, validateVerOpts, } from "./utils.js";
88
89
  // Can re-use if decide to signatures support, on other hand getSecretKey is specific and ugly
89
90
  function ecKeygen(curve, allowZeroKey = false) {
90
91
  const lengths = curve.lengths;
91
92
  let keygen = curve.keygen;
92
93
  if (allowZeroKey) {
94
+ // Only the ECDSA/Weierstrass branch uses raw scalar-byte secret keys here. Edwards seeds are
95
+ // hashed/pruned and Montgomery keys are clamped byte strings, so forcing Point.Fn semantics on
96
+ // those curves would change key construction instead of just relaxing scalar range handling.
97
+ if (!('getSharedSecret' in curve && 'sign' in curve && 'verify' in curve))
98
+ throw new Error('allowZeroKey requires a Weierstrass curve');
99
+ // This legacy flag is really "skip the +1 shift" for vector matching, not "accept scalar 0".
100
+ // It swaps seeded Weierstrass keygen from reduction into [1, ORDER) to direct reduction into
101
+ // [0, ORDER), which preserves exact reduced bytes but still leaves scalar 0 invalid.
93
102
  // This is ugly, but we need to return exact results here.
94
103
  const wCurve = curve;
95
104
  const Fn = wCurve.Point.Fn;
96
- if (!Fn)
97
- throw new Error('No Point.Fn');
105
+ // Unlike noble-curves' seeded Weierstrass keygen, this path removes the post-reduction +1.
106
+ // That is enough to match exact reduced-vector bytes, but an all-zero seed still reduces to
107
+ // scalar 0 here and getPublicKey(secretKey) throws instead of "allowing zero".
98
108
  keygen = (seed = randomBytes(lengths.seed)) => {
99
109
  abytes(seed, lengths.seed, 'seed');
100
110
  const seedScalar = Fn.isLE ? bytesToNumberLE(seed) : bytesToNumberBE(seed);
101
- const secretKey = Fn.toBytes(Fn.create(seedScalar)); // Fixes modulo bias, but not zero
102
- return { secretKey, publicKey: curve.getPublicKey(secretKey) };
111
+ // Reduce directly into [0, ORDER); scalar 0 still stays invalid.
112
+ const secretKey = Fn.toBytes(Fn.create(seedScalar));
113
+ return {
114
+ secretKey: secretKey,
115
+ publicKey: curve.getPublicKey(secretKey),
116
+ };
103
117
  };
104
118
  }
105
119
  return {
106
120
  lengths: { secretKey: lengths.secretKey, publicKey: lengths.publicKey, seed: lengths.seed },
107
- keygen,
121
+ keygen: (seed) => keygen(seed),
108
122
  getPublicKey: (secretKey) => curve.getPublicKey(secretKey),
109
123
  };
110
124
  }
125
+ /**
126
+ * Wraps an ECDH-capable curve as a KEM.
127
+ * Shared secrets stay in the wrapped curve's raw ECDH byte format with no built-in KDF.
128
+ * On SEC 1 / Weierstrass curves, that means the compressed shared-point body without the
129
+ * 1-byte `0x02` / `0x03` prefix.
130
+ * The X25519 path also leaves RFC 7748's optional all-zero shared-secret check to callers.
131
+ * @param curve - Curve with `getSharedSecret`.
132
+ * @param allowZeroKey - Legacy vector-matching toggle for Weierstrass keygen.
133
+ * On Weierstrass curves this removes the usual post-reduction `+1` shift, changing seeded scalar
134
+ * reduction from `[1, ORDER)` to direct reduction into `[0, ORDER)`. It does not make scalar zero
135
+ * valid: an all-zero seed still derives scalar `0` and throws in `curve.getPublicKey(...)`.
136
+ * Only supported on Weierstrass/ECDSA curves.
137
+ * @returns KEM wrapper over the curve.
138
+ * @throws If the curve does not expose `getSharedSecret`. {@link Error}
139
+ * @example
140
+ * Wrap an ECDH-capable curve as a generic KEM.
141
+ * ```ts
142
+ * import { x25519 } from '@noble/curves/ed25519.js';
143
+ * import { ecdhKem } from '@noble/post-quantum/hybrid.js';
144
+ * const kem = ecdhKem(x25519);
145
+ * const publicKeyLen = kem.lengths.publicKey;
146
+ * ```
147
+ */
111
148
  export function ecdhKem(curve, allowZeroKey = false) {
112
149
  const kg = ecKeygen(curve, allowZeroKey);
113
150
  if (!curve.getSharedSecret)
@@ -117,18 +154,51 @@ export function ecdhKem(curve, allowZeroKey = false) {
117
154
  keygen: kg.keygen,
118
155
  getPublicKey: kg.getPublicKey,
119
156
  encapsulate(publicKey, rand = randomBytes(curve.lengths.seed)) {
120
- const ek = this.keygen(rand).secretKey;
121
- const sharedSecret = this.decapsulate(publicKey, ek);
122
- const cipherText = curve.getPublicKey(ek);
123
- cleanBytes(ek);
124
- return { sharedSecret, cipherText };
157
+ // Some curve.keygen(seed) paths reuse the provided seed buffer as secretKey; detach caller
158
+ // randomness first so cleanBytes() only wipes wrapper-owned material.
159
+ const seed = copyBytes(rand);
160
+ let ek = undefined;
161
+ try {
162
+ ek = this.keygen(seed).secretKey;
163
+ const sharedSecret = this.decapsulate(publicKey, ek);
164
+ const cipherText = curve.getPublicKey(ek);
165
+ return { sharedSecret, cipherText };
166
+ }
167
+ finally {
168
+ // Invalid peer public keys can make decapsulation throw; wipe both the detached seed and
169
+ // derived ephemeral secret key even when encapsulation aborts before returning.
170
+ cleanBytes(seed);
171
+ if (ek)
172
+ cleanBytes(ek);
173
+ }
125
174
  },
126
175
  decapsulate(cipherText, secretKey) {
127
176
  const res = curve.getSharedSecret(secretKey, cipherText);
128
- return curve.lengths.publicKeyHasPrefix ? res.subarray(1) : res;
177
+ return (curve.lengths.publicKeyHasPrefix ? res.subarray(1) : res);
129
178
  },
130
179
  };
131
180
  }
181
+ /**
182
+ * Wraps a curve signer as a generic `Signer`.
183
+ * Signatures stay in the wrapped curve's native byte encoding.
184
+ * This wrapper does not normalize or document which per-curve signing options are meaningful.
185
+ * @param curve - Curve with `sign` and `verify`.
186
+ * @param allowZeroKey - Legacy vector-matching toggle for Weierstrass keygen.
187
+ * On Weierstrass curves this removes the usual post-reduction `+1` shift, changing seeded scalar
188
+ * reduction from `[1, ORDER)` to direct reduction into `[0, ORDER)`. It does not make scalar zero
189
+ * valid: an all-zero seed still derives scalar `0` and throws in `curve.getPublicKey(...)`.
190
+ * Only supported on Weierstrass/ECDSA curves.
191
+ * @returns Signer wrapper over the curve.
192
+ * @throws If the curve does not expose `sign` and `verify`. {@link Error}
193
+ * @example
194
+ * Wrap a curve signer as a generic signer.
195
+ * ```ts
196
+ * import { ed25519 } from '@noble/curves/ed25519.js';
197
+ * import { ecSigner } from '@noble/post-quantum/hybrid.js';
198
+ * const signer = ecSigner(ed25519);
199
+ * const sigLen = signer.lengths.signature;
200
+ * ```
201
+ */
132
202
  export function ecSigner(curve, allowZeroKey = false) {
133
203
  const kg = ecKeygen(curve, allowZeroKey);
134
204
  if (!curve.sign || !curve.verify)
@@ -137,11 +207,31 @@ export function ecSigner(curve, allowZeroKey = false) {
137
207
  lengths: { ...kg.lengths, signature: curve.lengths.signature, signRand: 0 },
138
208
  keygen: kg.keygen,
139
209
  getPublicKey: kg.getPublicKey,
140
- sign: (message, secretKey) => curve.sign(message, secretKey),
141
- verify: (signature, message, publicKey) => curve.verify(signature, message, publicKey),
210
+ sign: (message, secretKey, opts = {}) => {
211
+ validateSigOpts(opts);
212
+ // This generic wrapper intentionally keeps the Signer contract to message + key only.
213
+ // Backend-specific knobs like ECDSA extraEntropy or Ed25519ctx context cannot be forwarded
214
+ // uniformly through combineSigners(), so callers that need them must use the curve directly.
215
+ if (opts.extraEntropy !== undefined)
216
+ throw new Error('ecSigner does not support extraEntropy; use the underlying curve directly');
217
+ if (opts.context !== undefined)
218
+ throw new Error('ecSigner does not support context; use the underlying curve directly');
219
+ return curve.sign(message, secretKey);
220
+ },
221
+ /** Verify one wrapped curve signature.
222
+ * Returns the wrapped curve's `verify()` result for well-formed inputs. Throws on unsupported
223
+ * generic opts and lets wrapped-curve malformed-input errors escape unchanged.
224
+ */
225
+ verify: (signature, message, publicKey, opts = {}) => {
226
+ validateVerOpts(opts);
227
+ if (opts.context !== undefined)
228
+ throw new Error('ecSigner does not support context; use the underlying curve directly');
229
+ return curve.verify(signature, message, publicKey);
230
+ },
142
231
  };
143
232
  }
144
233
  function splitLengths(lst, name) {
234
+ // Preserve caller order exactly; raw numeric fields still decode as splitCoder() subarray views.
145
235
  return splitCoder(name, ...lst.map((i) => {
146
236
  if (typeof i.lengths[name] !== 'number')
147
237
  throw new Error('wrong length: ' + name);
@@ -149,11 +239,29 @@ function splitLengths(lst, name) {
149
239
  }));
150
240
  }
151
241
  // It is XOF for most cases, but can be more complex!
242
+ /**
243
+ * Adapts an XOF into an `ExpandSeed` callback.
244
+ * The returned callback interprets its second argument as an output byte length passed as `dkLen`.
245
+ * @param xof - Extendable-output hash function.
246
+ * @returns Seed expander using `dkLen`.
247
+ * @example
248
+ * Adapt an XOF into a seed expander.
249
+ * ```ts
250
+ * import { shake256 } from '@noble/hashes/sha3.js';
251
+ * import { expandSeedXof } from '@noble/post-quantum/hybrid.js';
252
+ * const expandSeed = expandSeedXof(shake256);
253
+ * const seed = expandSeed(new Uint8Array([1]), 4);
254
+ * ```
255
+ */
152
256
  export function expandSeedXof(xof) {
153
- return (seed, seedLen) => xof(seed, { dkLen: seedLen });
257
+ // Forward the caller seed directly: XOFs are expected to treat inputs as read-only, and this
258
+ // adapter only translates the requested byte length into the hash API's `dkLen` option.
259
+ return ((seed, seedLen) => xof(seed, { dkLen: seedLen }));
154
260
  }
155
261
  function combineKeys(realSeedLen, // how much bytes expandSeed expects
156
- expandSeed, ...ck) {
262
+ expandSeed_, ...ck_) {
263
+ const expandSeed = expandSeed_;
264
+ const ck = ck_;
157
265
  const seedCoder = splitLengths(ck, 'seed');
158
266
  const pkCoder = splitLengths(ck, 'publicKey');
159
267
  // Allows to use identity functions for combiner/expandSeed
@@ -162,104 +270,276 @@ expandSeed, ...ck) {
162
270
  anumber(realSeedLen);
163
271
  function expandDecapsulationKey(seed) {
164
272
  abytes(seed, realSeedLen);
165
- const expanded = seedCoder.decode(expandSeed(seed, seedCoder.bytesLen));
166
- const keys = ck.map((i, j) => i.keygen(expanded[j]));
167
- const secretKey = keys.map((i) => i.secretKey);
168
- const publicKey = keys.map((i) => i.publicKey);
169
- return { secretKey, publicKey };
273
+ const expandedRaw = expandSeed(seed, seedCoder.bytesLen);
274
+ // Identity/subarray expanders can hand back caller-owned seed storage. Detach those outputs so
275
+ // later cleanup can wipe the expanded schedule without mutating the caller's root seed bytes.
276
+ const expandedSeed = expandedRaw.buffer === seed.buffer ? copyBytes(expandedRaw) : expandedRaw;
277
+ const expanded = [];
278
+ const keySecret = [];
279
+ const secretKey = [];
280
+ const publicKey = [];
281
+ let ok = false;
282
+ try {
283
+ // seedCoder.decode() returns zero-copy slices into expandedSeed and can throw before child
284
+ // keygen() runs, so keep the raw expanded buffer separate and copy each child seed before any
285
+ // later cleanup wipes the shared backing bytes.
286
+ for (const part of seedCoder.decode(expandedSeed))
287
+ expanded.push(copyBytes(part));
288
+ for (let i = 0; i < ck.length; i++) {
289
+ const keys = ck[i].keygen(expanded[i]);
290
+ keySecret.push(keys.secretKey);
291
+ secretKey.push(copyBytes(keys.secretKey));
292
+ publicKey.push(keys.publicKey);
293
+ }
294
+ ok = true;
295
+ return { secretKey, publicKey };
296
+ }
297
+ finally {
298
+ // Child keygen() can throw after deriving only a prefix of the composite key schedule. Keep
299
+ // the exported copies on success, but wipe all temporary and partially built secret material
300
+ // on either path so failures do not strand derived child seeds in memory.
301
+ cleanBytes(expandedSeed, expanded, keySecret);
302
+ if (!ok)
303
+ cleanBytes(secretKey);
304
+ }
170
305
  }
171
306
  return {
172
307
  info: { lengths: { seed: realSeedLen, publicKey: pkCoder.bytesLen, secretKey: realSeedLen } },
173
308
  getPublicKey(secretKey) {
309
+ // Composite secret keys are root seeds, so public-key derivation reruns key expansion from
310
+ // that seed instead of decoding a packed child-secret-key structure.
174
311
  return this.keygen(secretKey).publicKey;
175
312
  },
176
313
  keygen(seed = randomBytes(realSeedLen)) {
177
314
  const { publicKey: pk, secretKey } = expandDecapsulationKey(seed);
178
- const publicKey = pkCoder.encode(pk);
179
- cleanBytes(pk);
180
- cleanBytes(secretKey);
181
- return { secretKey: seed, publicKey };
315
+ try {
316
+ const publicKey = pkCoder.encode(pk);
317
+ return { secretKey: seed, publicKey };
318
+ }
319
+ finally {
320
+ cleanBytes(pk);
321
+ // The exported secretKey is the caller/root seed itself; child secret keys are internal
322
+ // expansion outputs that are cleaned whether encoding succeeds or throws.
323
+ cleanBytes(secretKey);
324
+ }
182
325
  },
183
326
  expandDecapsulationKey,
184
327
  realSeedLen,
185
328
  };
186
329
  }
187
330
  // This generic function that combines multiple KEMs into single one
331
+ /**
332
+ * Combines multiple KEMs into one composite KEM.
333
+ * @param realSeedLen - Input seed length expected by `expandSeed`.
334
+ * @param realMsgLen - Shared-secret length returned by `combiner`.
335
+ * @param expandSeed - Seed expander used to derive per-KEM seeds.
336
+ * @param combiner - Combines the per-KEM outputs into one shared secret.
337
+ * @param kems - KEM implementations to combine.
338
+ * @returns Composite KEM.
339
+ * @example
340
+ * Combine multiple KEMs into one composite KEM.
341
+ * ```ts
342
+ * import { shake256 } from '@noble/hashes/sha3.js';
343
+ * import { combineKEMS, expandSeedXof } from '@noble/post-quantum/hybrid.js';
344
+ * import { ml_kem768 } from '@noble/post-quantum/ml-kem.js';
345
+ * const hybrid = combineKEMS(
346
+ * 32,
347
+ * 32,
348
+ * expandSeedXof(shake256),
349
+ * (_pk, _ct, sharedSecrets) => sharedSecrets[0],
350
+ * ml_kem768,
351
+ * ml_kem768
352
+ * );
353
+ * const { publicKey } = hybrid.keygen();
354
+ * ```
355
+ */
188
356
  export function combineKEMS(realSeedLen, // how much bytes expandSeed expects
189
357
  realMsgLen, // how much bytes combiner returns
190
358
  expandSeed, combiner, ...kems) {
191
- const keys = combineKeys(realSeedLen, expandSeed, ...kems);
192
- const ctCoder = splitLengths(kems, 'cipherText');
193
- const pkCoder = splitLengths(kems, 'publicKey');
194
- const msgCoder = splitLengths(kems, 'msg');
359
+ const rawCombiner = combiner;
360
+ const rawKems = kems;
361
+ const keys = combineKeys(realSeedLen, expandSeed, ...rawKems);
362
+ const ctCoder = splitLengths(rawKems, 'cipherText');
363
+ const pkCoder = splitLengths(rawKems, 'publicKey');
364
+ const msgCoder = splitLengths(rawKems, 'msg');
195
365
  if (realMsgLen === undefined)
196
366
  realMsgLen = msgCoder.bytesLen;
197
367
  anumber(realMsgLen);
198
- return {
199
- lengths: {
200
- ...keys.info.lengths,
201
- msg: realMsgLen,
202
- msgRand: msgCoder.bytesLen,
203
- cipherText: ctCoder.bytesLen,
204
- },
368
+ const lengths = Object.freeze({
369
+ ...keys.info.lengths,
370
+ msg: realMsgLen,
371
+ msgRand: msgCoder.bytesLen,
372
+ cipherText: ctCoder.bytesLen,
373
+ });
374
+ return Object.freeze({
375
+ lengths,
205
376
  getPublicKey: keys.getPublicKey,
206
377
  keygen: keys.keygen,
207
378
  encapsulate(pk, randomness = randomBytes(msgCoder.bytesLen)) {
208
379
  const pks = pkCoder.decode(pk);
209
380
  const rand = msgCoder.decode(randomness);
210
- const enc = kems.map((i, j) => i.encapsulate(pks[j], rand[j]));
211
- const sharedSecret = enc.map((i) => i.sharedSecret);
212
- const cipherText = enc.map((i) => i.cipherText);
213
- const res = {
214
- sharedSecret: combiner(pks, cipherText, sharedSecret),
215
- cipherText: ctCoder.encode(cipherText),
216
- };
217
- cleanBytes(sharedSecret, cipherText);
218
- return res;
381
+ const sharedSecret = [];
382
+ const cipherText = [];
383
+ try {
384
+ for (let i = 0; i < rawKems.length; i++) {
385
+ const enc = rawKems[i].encapsulate(pks[i], rand[i]);
386
+ sharedSecret.push(enc.sharedSecret);
387
+ cipherText.push(enc.cipherText);
388
+ }
389
+ return {
390
+ // Detach the combiner result before cleanup: a caller-provided combiner may alias one of
391
+ // the child sharedSecret buffers, and those child buffers are zeroized immediately below.
392
+ sharedSecret: copyBytes(rawCombiner(pks, cipherText, sharedSecret)),
393
+ cipherText: ctCoder.encode(cipherText),
394
+ };
395
+ }
396
+ finally {
397
+ // Child encapsulation or combiner failures can happen after some components already
398
+ // returned secret material; zeroize whatever was produced before propagating the error.
399
+ cleanBytes(sharedSecret, cipherText);
400
+ }
219
401
  },
220
402
  decapsulate(ct, seed) {
221
403
  const cts = ctCoder.decode(ct);
222
404
  const { publicKey, secretKey } = keys.expandDecapsulationKey(seed);
223
- const sharedSecret = kems.map((i, j) => i.decapsulate(cts[j], secretKey[j]));
224
- return combiner(publicKey, cts, sharedSecret);
405
+ const sharedSecret = rawKems.map((i, j) => i.decapsulate(cts[j], secretKey[j]));
406
+ try {
407
+ // Detach the decapsulation result before cleanup: the combiner may hand back one of the
408
+ // child shared-secret buffers, and those temporary buffers are zeroized below.
409
+ return copyBytes(rawCombiner(publicKey, cts, sharedSecret));
410
+ }
411
+ finally {
412
+ // Decapsulation only needs the expanded child secret keys and child shared secrets for this
413
+ // call; keep the caller/root seed intact, but wipe all derived material even on errors.
414
+ cleanBytes(secretKey, sharedSecret);
415
+ }
225
416
  },
226
- };
417
+ });
227
418
  }
228
419
  // There is no specs for this, but can be useful
229
420
  // realSeedLen: how much bytes expandSeed expects.
421
+ /**
422
+ * Combines multiple signers into one composite signer.
423
+ * @param realSeedLen - Input seed length expected by `expandSeed`.
424
+ * @param expandSeed - Seed expander used to derive per-signer seeds.
425
+ * @param signers - Signers to combine.
426
+ * @returns Composite signer.
427
+ * @example
428
+ * Combine multiple signers into one composite signer.
429
+ * ```ts
430
+ * import { shake256 } from '@noble/hashes/sha3.js';
431
+ * import { combineSigners, expandSeedXof } from '@noble/post-quantum/hybrid.js';
432
+ * import { ml_dsa44 } from '@noble/post-quantum/ml-dsa.js';
433
+ * const hybrid = combineSigners(32, expandSeedXof(shake256), ml_dsa44, ml_dsa44);
434
+ * const { publicKey } = hybrid.keygen();
435
+ * ```
436
+ */
230
437
  export function combineSigners(realSeedLen, expandSeed, ...signers) {
231
- const keys = combineKeys(realSeedLen, expandSeed, ...signers);
232
- const sigCoder = splitLengths(signers, 'signature');
233
- const pkCoder = splitLengths(signers, 'publicKey');
438
+ const rawSigners = signers;
439
+ const keys = combineKeys(realSeedLen, expandSeed, ...rawSigners);
440
+ const sigCoder = splitLengths(rawSigners, 'signature');
441
+ const pkCoder = splitLengths(rawSigners, 'publicKey');
234
442
  return {
235
443
  lengths: { ...keys.info.lengths, signature: sigCoder.bytesLen, signRand: 0 },
236
444
  getPublicKey: keys.getPublicKey,
237
445
  keygen: keys.keygen,
238
- sign(message, seed) {
446
+ sign(message, seed, opts = {}) {
447
+ validateSigOpts(opts);
448
+ // This generic wrapper intentionally keeps the composite signer contract to message + root
449
+ // seed only. Per-signer opts like context or extraEntropy cannot be preserved uniformly
450
+ // across mixed backends, so callers that need them must use the underlying signer directly.
451
+ if (opts.extraEntropy !== undefined)
452
+ throw new Error('combineSigners does not support extraEntropy; use the underlying signer directly');
453
+ if (opts.context !== undefined)
454
+ throw new Error('combineSigners does not support context; use the underlying signer directly');
239
455
  const { secretKey } = keys.expandDecapsulationKey(seed);
240
- // NOTE: we probably can make different hashes for different algorithms
241
- // same way as we do for kem, but not sure if this a good idea.
242
- const sigs = signers.map((i, j) => i.sign(message, secretKey[j]));
243
- return sigCoder.encode(sigs);
456
+ try {
457
+ const sigs = rawSigners.map((i, j) => i.sign(message, secretKey[j]));
458
+ return sigCoder.encode(sigs);
459
+ }
460
+ finally {
461
+ // Composite secret keys are root seeds; the per-signer child secret keys are temporary
462
+ // expansion outputs and must not stay live after the combined signature is produced.
463
+ cleanBytes(secretKey);
464
+ }
244
465
  },
245
- verify: (signature, message, publicKey) => {
466
+ /** Verify one combined signature.
467
+ * Returns `false` when the aggregate signature/publicKey decode succeeds but any child verify
468
+ * check fails. Throws on unsupported generic opts or malformed aggregate encodings.
469
+ */
470
+ verify: (signature, message, publicKey, opts = {}) => {
471
+ validateVerOpts(opts);
472
+ if (opts.context !== undefined)
473
+ throw new Error('combineSigners does not support context; use the underlying signer directly');
246
474
  const pks = pkCoder.decode(publicKey);
247
475
  const sigs = sigCoder.decode(signature);
248
- for (let i = 0; i < signers.length; i++) {
249
- if (!signers[i].verify(sigs[i], message, pks[i]))
476
+ for (let i = 0; i < rawSigners.length; i++) {
477
+ if (!rawSigners[i].verify(sigs[i], message, pks[i]))
250
478
  return false;
251
479
  }
252
480
  return true;
253
481
  },
254
482
  };
255
483
  }
484
+ /**
485
+ * Builds a QSF hybrid KEM preset from a PQ KEM and an elliptic-curve KEM.
486
+ * The combined shared-secret length follows `kdf.outputLen`; the built-in presets use 32-byte
487
+ * SHA3-256 output, while custom `kdf` choices inherit their own digest size.
488
+ * Its combiner hashes `ss0 || ss1 || ct1 || pk1 || label`, not the full
489
+ * `(c1, c2, ek1, ek2)` example input shape from SP 800-227 equation (15).
490
+ * Labels are encoded with `asciiToBytes()`, so non-ASCII labels are rejected.
491
+ * @param label - Domain-separation label.
492
+ * @param pqc - Post-quantum KEM.
493
+ * @param curveKEM - Classical curve KEM.
494
+ * @param xof - XOF used for seed expansion.
495
+ * @param kdf - Hash used for the final combiner.
496
+ * @returns Hybrid KEM.
497
+ * @example
498
+ * Build a QSF hybrid KEM preset from a PQ KEM and an elliptic-curve KEM.
499
+ * ```ts
500
+ * import { p256 } from '@noble/curves/nist.js';
501
+ * import { sha3_256, shake256 } from '@noble/hashes/sha3.js';
502
+ * import { QSF, ecdhKem } from '@noble/post-quantum/hybrid.js';
503
+ * import { ml_kem768 } from '@noble/post-quantum/ml-kem.js';
504
+ * const kem = QSF('example', ml_kem768, ecdhKem(p256, true), shake256, sha3_256);
505
+ * const publicKeyLen = kem.lengths.publicKey;
506
+ * ```
507
+ */
256
508
  export function QSF(label, pqc, curveKEM, xof, kdf) {
257
509
  ahash(xof);
258
510
  ahash(kdf);
259
- return combineKEMS(32, 32, expandSeedXof(xof), (pk, ct, ss) => kdf(concatBytes(ss[0], ss[1], ct[1], pk[1], asciiToBytes(label))), pqc, curveKEM);
511
+ return combineKEMS(32, kdf.outputLen, expandSeedXof(xof), (pk, ct, ss) => kdf(concatBytes(ss[0], ss[1], ct[1], pk[1], asciiToBytes(label))), pqc, curveKEM);
260
512
  }
261
- export const QSF_ml_kem768_p256 = QSF('QSF-KEM(ML-KEM-768,P-256)-XOF(SHAKE256)-KDF(SHA3-256)', ml_kem768, ecdhKem(p256, true), shake256, sha3_256);
262
- export const QSF_ml_kem1024_p384 = QSF('QSF-KEM(ML-KEM-1024,P-384)-XOF(SHAKE256)-KDF(SHA3-256)', ml_kem1024, ecdhKem(p384, true), shake256, sha3_256);
513
+ /** QSF preset combining ML-KEM-768 with P-256. */
514
+ export const QSF_ml_kem768_p256 = /* @__PURE__ */ (() => QSF('QSF-KEM(ML-KEM-768,P-256)-XOF(SHAKE256)-KDF(SHA3-256)', ml_kem768, ecdhKem(p256, true), shake256, sha3_256))();
515
+ /** QSF preset combining ML-KEM-1024 with P-384. */
516
+ export const QSF_ml_kem1024_p384 = /* @__PURE__ */ (() => QSF('QSF-KEM(ML-KEM-1024,P-384)-XOF(SHAKE256)-KDF(SHA3-256)', ml_kem1024, ecdhKem(p384, true), shake256, sha3_256))();
517
+ /**
518
+ * Builds the "KitchenSink" hybrid KEM combiner.
519
+ * The current builder always derives a fixed 32-byte output,
520
+ * regardless of the hash's native output size.
521
+ * Its HKDF extract step uses implicit zero salt with IKM
522
+ * `hybrid_prk || ss0 || ss1 || ct0 || pk0 || ct1 || pk1 || label`.
523
+ * Its HKDF expand step fixes `info` to `len || 'shared_secret' || ''`.
524
+ * Labels are encoded with `asciiToBytes()`, so non-ASCII labels are rejected.
525
+ * @param label - Domain-separation label.
526
+ * @param pqc - Post-quantum KEM.
527
+ * @param curveKEM - Classical curve KEM.
528
+ * @param xof - XOF used for seed expansion.
529
+ * @param hash - Hash used for HKDF extraction and expansion.
530
+ * @returns Hybrid KEM.
531
+ * @example
532
+ * Build the "KitchenSink" hybrid KEM combiner.
533
+ * ```ts
534
+ * import { sha256 } from '@noble/hashes/sha2.js';
535
+ * import { shake256 } from '@noble/hashes/sha3.js';
536
+ * import { createKitchenSink, ecdhKem } from '@noble/post-quantum/hybrid.js';
537
+ * import { ml_kem768 } from '@noble/post-quantum/ml-kem.js';
538
+ * import { x25519 } from '@noble/curves/ed25519.js';
539
+ * const kem = createKitchenSink('example', ml_kem768, ecdhKem(x25519), shake256, sha256);
540
+ * const publicKeyLen = kem.lengths.publicKey;
541
+ * ```
542
+ */
263
543
  export function createKitchenSink(label, pqc, curveKEM, xof, hash) {
264
544
  ahash(xof);
265
545
  ahash(hash);
@@ -274,16 +554,35 @@ export function createKitchenSink(label, pqc, curveKEM, xof, hash) {
274
554
  return res;
275
555
  }, pqc, curveKEM);
276
556
  }
277
- const x25519kem = ecdhKem(x25519);
278
- export const KitchenSink_ml_kem768_x25519 = createKitchenSink('KitchenSink-KEM(ML-KEM-768,X25519)-XOF(SHAKE256)-KDF(HKDF-SHA-256)', ml_kem768, x25519kem, shake256, sha256);
557
+ // Internal alias only: this stays exactly `ecdhKem(x25519)`
558
+ // and inherits that wrapper's mutation/oracle behavior.
559
+ const x25519kem = /* @__PURE__ */ ecdhKem(x25519);
560
+ /** KitchenSink preset combining ML-KEM-768 with X25519.
561
+ * Caller randomness splits into 32 ML-KEM coins plus a 32-byte X25519 ephemeral-secret seed.
562
+ */
563
+ export const KitchenSink_ml_kem768_x25519 = /* @__PURE__ */ (() => createKitchenSink('KitchenSink-KEM(ML-KEM-768,X25519)-XOF(SHAKE256)-KDF(HKDF-SHA-256)', ml_kem768, x25519kem, shake256, sha256))();
279
564
  // Always X25519 and ML-KEM - 768, no point to export
565
+ /** X25519 + ML-KEM-768 hybrid preset.
566
+ * Uses the hard-coded domain-separation label `\\.//^\\` and hashes only `ct1 || pk1`
567
+ * from the X25519 side in addition to the two component shared secrets.
568
+ */
280
569
  export const ml_kem768_x25519 = /* @__PURE__ */ (() => combineKEMS(32, 32, expandSeedXof(shake256),
281
570
  // Awesome label, so much escaping hell in a single line.
282
571
  (pk, ct, ss) => sha3_256(concatBytes(ss[0], ss[1], ct[1], pk[1], asciiToBytes('\\.//^\\'))), ml_kem768, x25519kem))();
572
+ /**
573
+ * Internal SEC 1-style KEM wrapper for NIST curves.
574
+ * `nseed` is only the rejection-sampling byte budget for deriving one nonzero scalar:
575
+ * current presets use `128` bytes for P-256 and `48` bytes for P-384.
576
+ * `decapsulate()` returns the uncompressed shared point body `x || y` without the `0x04`
577
+ * prefix, not the SEC 1 `x_P`-only primitive output, because current hybrid combiners hash
578
+ * both coordinates.
579
+ */
283
580
  function nistCurveKem(curve, scalarLen, elemLen, nseed) {
284
581
  const Fn = curve.Point.Fn;
285
582
  if (!Fn)
286
583
  throw new Error('no Point.Fn');
584
+ // Scan scalar-sized windows until one decodes to a nonzero scalar in `[1, n-1]`; if every
585
+ // window is zero or out of range, fail instead of silently reducing modulo `n`.
287
586
  function rejectionSampling(seed) {
288
587
  let sk;
289
588
  for (let start = 0, end = scalarLen;; start = end, end += scalarLen) {
@@ -314,11 +613,19 @@ function nistCurveKem(curve, scalarLen, elemLen, nseed) {
314
613
  },
315
614
  encapsulate(publicKey, rand = randomBytes(nseed)) {
316
615
  abytes(rand, nseed, 'rand');
317
- const { secretKey: ek } = rejectionSampling(rand);
318
- const sharedSecret = this.decapsulate(publicKey, ek);
319
- const cipherText = curve.getPublicKey(ek, false);
320
- cleanBytes(ek);
321
- return { sharedSecret, cipherText };
616
+ let ek = undefined;
617
+ try {
618
+ ek = rejectionSampling(rand).secretKey;
619
+ const sharedSecret = this.decapsulate(publicKey, ek);
620
+ const cipherText = curve.getPublicKey(ek, false);
621
+ return { sharedSecret, cipherText };
622
+ }
623
+ finally {
624
+ // Rejection-sampled NIST-curve ephemeral secret keys are temporary encapsulation state and
625
+ // must be wiped even if peer-key validation or shared-secret derivation throws.
626
+ if (ek)
627
+ cleanBytes(ek);
628
+ }
322
629
  },
323
630
  decapsulate(cipherText, secretKey) {
324
631
  const full = curve.getSharedSecret(secretKey, cipherText);
@@ -326,6 +633,14 @@ function nistCurveKem(curve, scalarLen, elemLen, nseed) {
326
633
  },
327
634
  };
328
635
  }
636
+ /**
637
+ * Internal ML-KEM + NIST-curve combiner.
638
+ * `nseed` controls only the curve-side rejection-sampling budget; it is expanded from the
639
+ * 32-byte root seed and is not itself part of the exported secret-key length.
640
+ * The domain-separation `label` is used only in the final `sha3_256` combiner, not in
641
+ * `shake256(seed, { dkLen: 64 + nseed })`,
642
+ * and the combiner hashes `ss0 || ss1 || ct1 || pk1 || label`.
643
+ */
329
644
  function concreteHybridKem(label, mlkem, curve, nseed) {
330
645
  const { secretKey: scalarLen, publicKeyUncompressed: elemLen } = curve.lengths;
331
646
  if (!scalarLen || !elemLen)
@@ -341,14 +656,23 @@ function concreteHybridKem(label, mlkem, curve, nseed) {
341
656
  return concatBytes(mlkemSeed, curveSeed);
342
657
  }, (pk, ct, ss) => sha3_256(concatBytes(ss[0], ss[1], ct[1], pk[1], asciiToBytes(label))), mlkem, curveKem);
343
658
  }
659
+ /** P-256 + ML-KEM-768 hybrid preset. */
344
660
  export const ml_kem768_p256 = /* @__PURE__ */ (() => concreteHybridKem('MLKEM768-P256', ml_kem768, p256, 128))();
661
+ /** P-384 + ML-KEM-1024 hybrid preset. */
345
662
  export const ml_kem1024_p384 = /* @__PURE__ */ (() => concreteHybridKem('MLKEM1024-P384', ml_kem1024, p384, 48))();
346
663
  // Legacy aliases
347
- export const XWing = ml_kem768_x25519;
348
- export const MLKEM768X25519 = ml_kem768_x25519;
349
- export const MLKEM768P256 = ml_kem768_p256;
350
- export const MLKEM1024P384 = ml_kem1024_p384;
351
- export const QSFMLKEM768P256 = QSF_ml_kem768_p256;
352
- export const QSFMLKEM1024P384 = QSF_ml_kem1024_p384;
353
- export const KitchenSinkMLKEM768X25519 = KitchenSink_ml_kem768_x25519;
664
+ /** Legacy alias for `ml_kem768_x25519`. */
665
+ export const XWing = /* @__PURE__ */ (() => ml_kem768_x25519)();
666
+ /** Legacy alias for `ml_kem768_x25519`. */
667
+ export const MLKEM768X25519 = /* @__PURE__ */ (() => ml_kem768_x25519)();
668
+ /** Legacy alias for `ml_kem768_p256`. */
669
+ export const MLKEM768P256 = /* @__PURE__ */ (() => ml_kem768_p256)();
670
+ /** Legacy alias for `ml_kem1024_p384`. */
671
+ export const MLKEM1024P384 = /* @__PURE__ */ (() => ml_kem1024_p384)();
672
+ /** Legacy alias for `QSF_ml_kem768_p256`. */
673
+ export const QSFMLKEM768P256 = /* @__PURE__ */ (() => QSF_ml_kem768_p256)();
674
+ /** Legacy alias for `QSF_ml_kem1024_p384`. */
675
+ export const QSFMLKEM1024P384 = /* @__PURE__ */ (() => QSF_ml_kem1024_p384)();
676
+ /** Legacy alias for `KitchenSink_ml_kem768_x25519`. */
677
+ export const KitchenSinkMLKEM768X25519 = /* @__PURE__ */ (() => KitchenSink_ml_kem768_x25519)();
354
678
  //# sourceMappingURL=hybrid.js.map