@theqrl/mldsa87 2.1.0 → 2.1.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.
Files changed (2) hide show
  1. package/dist/cjs/mldsa87.js +302 -50
  2. package/package.json +10 -10
@@ -64,18 +64,17 @@ const zetas = [
64
64
  -1362209, 3937738, 1400424, -846154, 1976782,
65
65
  ];
66
66
 
67
- /**
68
- * Internal helpers for u64. BigUint64Array is too slow as per 2025, so we implement it using Uint32Array.
69
- * @todo re-check https://issues.chromium.org/issues/42212588
70
- * @module
71
- */
72
67
  const U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);
73
68
  const _32n = /* @__PURE__ */ BigInt(32);
69
+ // Split bigint into two 32-bit halves. With `le=true`, returned fields become `{ h: low, l: high
70
+ // }` to match little-endian word order rather than the property names.
74
71
  function fromBig(n, le = false) {
75
72
  if (le)
76
73
  return { h: Number(n & U32_MASK64), l: Number((n >> _32n) & U32_MASK64) };
77
74
  return { h: Number((n >> _32n) & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 };
78
75
  }
76
+ // Split bigint list into `[highWords, lowWords]` when `le=false`; with `le=true`, the first array
77
+ // holds the low halves because `fromBig(...)` swaps the semantic meaning of `h` and `l`.
79
78
  function split(lst, le = false) {
80
79
  const len = lst.length;
81
80
  let Ah = new Uint32Array(len);
@@ -86,30 +85,72 @@ function split(lst, le = false) {
86
85
  }
87
86
  return [Ah, Al];
88
87
  }
89
- // Left rotate for Shift in [1, 32)
88
+ // High 32-bit half of a 64-bit left rotate, valid for `s` in `1..31`.
90
89
  const rotlSH = (h, l, s) => (h << s) | (l >>> (32 - s));
90
+ // Low 32-bit half of a 64-bit left rotate, valid for `s` in `1..31`.
91
91
  const rotlSL = (h, l, s) => (l << s) | (h >>> (32 - s));
92
- // Left rotate for Shift in (32, 64), NOTE: 32 is special case.
92
+ // High 32-bit half of a 64-bit left rotate, valid for `s` in `33..63`; `32` uses `rotr32*`.
93
93
  const rotlBH = (h, l, s) => (l << (s - 32)) | (h >>> (64 - s));
94
+ // Low 32-bit half of a 64-bit left rotate, valid for `s` in `33..63`; `32` uses `rotr32*`.
94
95
  const rotlBL = (h, l, s) => (h << (s - 32)) | (l >>> (64 - s));
95
96
 
96
97
  /**
97
- * Utilities for hex, bytes, CSPRNG.
98
- * @module
98
+ * Checks if something is Uint8Array. Be careful: nodejs Buffer will return true.
99
+ * @param a - value to test
100
+ * @returns `true` when the value is a Uint8Array-compatible view.
101
+ * @example
102
+ * Check whether a value is a Uint8Array-compatible view.
103
+ * ```ts
104
+ * isBytes(new Uint8Array([1, 2, 3]));
105
+ * ```
99
106
  */
100
- /*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */
101
- /** Checks if something is Uint8Array. Be careful: nodejs Buffer will return true. */
102
107
  function isBytes(a) {
103
- return a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');
108
+ // Plain `instanceof Uint8Array` is too strict for some Buffer / proxy / cross-realm cases.
109
+ // The fallback still requires a real ArrayBuffer view, so plain
110
+ // JSON-deserialized `{ constructor: ... }` spoofing is rejected, and
111
+ // `BYTES_PER_ELEMENT === 1` keeps the fallback on byte-oriented views.
112
+ return (a instanceof Uint8Array ||
113
+ (ArrayBuffer.isView(a) &&
114
+ a.constructor.name === 'Uint8Array' &&
115
+ 'BYTES_PER_ELEMENT' in a &&
116
+ a.BYTES_PER_ELEMENT === 1));
104
117
  }
105
- /** Asserts something is positive integer. */
118
+ /**
119
+ * Asserts something is a non-negative integer.
120
+ * @param n - number to validate
121
+ * @param title - label included in thrown errors
122
+ * @throws On wrong argument types. {@link TypeError}
123
+ * @throws On wrong argument ranges or values. {@link RangeError}
124
+ * @example
125
+ * Validate a non-negative integer option.
126
+ * ```ts
127
+ * anumber(32, 'length');
128
+ * ```
129
+ */
106
130
  function anumber(n, title = '') {
131
+ if (typeof n !== 'number') {
132
+ const prefix = title && `"${title}" `;
133
+ throw new TypeError(`${prefix}expected number, got ${typeof n}`);
134
+ }
107
135
  if (!Number.isSafeInteger(n) || n < 0) {
108
136
  const prefix = title && `"${title}" `;
109
- throw new Error(`${prefix}expected integer >= 0, got ${n}`);
137
+ throw new RangeError(`${prefix}expected integer >= 0, got ${n}`);
110
138
  }
111
139
  }
112
- /** Asserts something is Uint8Array. */
140
+ /**
141
+ * Asserts something is Uint8Array.
142
+ * @param value - value to validate
143
+ * @param length - optional exact length constraint
144
+ * @param title - label included in thrown errors
145
+ * @returns The validated byte array.
146
+ * @throws On wrong argument types. {@link TypeError}
147
+ * @throws On wrong argument ranges or values. {@link RangeError}
148
+ * @example
149
+ * Validate that a value is a byte array.
150
+ * ```ts
151
+ * abytes(new Uint8Array([1, 2, 3]));
152
+ * ```
153
+ */
113
154
  function abytes(value, length, title = '') {
114
155
  const bytes = isBytes(value);
115
156
  const len = value?.length;
@@ -118,51 +159,130 @@ function abytes(value, length, title = '') {
118
159
  const prefix = title && `"${title}" `;
119
160
  const ofLen = '';
120
161
  const got = bytes ? `length=${len}` : `type=${typeof value}`;
121
- throw new Error(prefix + 'expected Uint8Array' + ofLen + ', got ' + got);
162
+ const message = prefix + 'expected Uint8Array' + ofLen + ', got ' + got;
163
+ if (!bytes)
164
+ throw new TypeError(message);
165
+ throw new RangeError(message);
122
166
  }
123
167
  return value;
124
168
  }
125
- /** Asserts a hash instance has not been destroyed / finished */
169
+ /**
170
+ * Asserts a hash instance has not been destroyed or finished.
171
+ * @param instance - hash instance to validate
172
+ * @param checkFinished - whether to reject finalized instances
173
+ * @throws If the hash instance has already been destroyed or finalized. {@link Error}
174
+ * @example
175
+ * Validate that a hash instance is still usable.
176
+ * ```ts
177
+ * import { aexists } from '@noble/hashes/utils.js';
178
+ * import { sha256 } from '@noble/hashes/sha2.js';
179
+ * const hash = sha256.create();
180
+ * aexists(hash);
181
+ * ```
182
+ */
126
183
  function aexists(instance, checkFinished = true) {
127
184
  if (instance.destroyed)
128
185
  throw new Error('Hash instance has been destroyed');
129
186
  if (checkFinished && instance.finished)
130
187
  throw new Error('Hash#digest() has already been called');
131
188
  }
132
- /** Asserts output is properly-sized byte array */
189
+ /**
190
+ * Asserts output is a sufficiently-sized byte array.
191
+ * @param out - destination buffer
192
+ * @param instance - hash instance providing output length
193
+ * Oversized buffers are allowed; downstream code only promises to fill the first `outputLen` bytes.
194
+ * @throws On wrong argument types. {@link TypeError}
195
+ * @throws On wrong argument ranges or values. {@link RangeError}
196
+ * @example
197
+ * Validate a caller-provided digest buffer.
198
+ * ```ts
199
+ * import { aoutput } from '@noble/hashes/utils.js';
200
+ * import { sha256 } from '@noble/hashes/sha2.js';
201
+ * const hash = sha256.create();
202
+ * aoutput(new Uint8Array(hash.outputLen), hash);
203
+ * ```
204
+ */
133
205
  function aoutput(out, instance) {
134
206
  abytes(out, undefined, 'digestInto() output');
135
207
  const min = instance.outputLen;
136
208
  if (out.length < min) {
137
- throw new Error('"digestInto() output" expected to be of length >=' + min);
209
+ throw new RangeError('"digestInto() output" expected to be of length >=' + min);
138
210
  }
139
211
  }
140
- /** Cast u8 / u16 / u32 to u32. */
212
+ /**
213
+ * Casts a typed array view to Uint32Array.
214
+ * `arr.byteOffset` must already be 4-byte aligned or the platform
215
+ * Uint32Array constructor will throw.
216
+ * @param arr - source typed array
217
+ * @returns Uint32Array view over the same buffer.
218
+ * @example
219
+ * Reinterpret a byte array as 32-bit words.
220
+ * ```ts
221
+ * u32(new Uint8Array(8));
222
+ * ```
223
+ */
141
224
  function u32(arr) {
142
225
  return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));
143
226
  }
144
- /** Zeroize a byte array. Warning: JS provides no guarantees. */
227
+ /**
228
+ * Zeroizes typed arrays in place. Warning: JS provides no guarantees.
229
+ * @param arrays - arrays to overwrite with zeros
230
+ * @example
231
+ * Zeroize sensitive buffers in place.
232
+ * ```ts
233
+ * clean(new Uint8Array([1, 2, 3]));
234
+ * ```
235
+ */
145
236
  function clean(...arrays) {
146
237
  for (let i = 0; i < arrays.length; i++) {
147
238
  arrays[i].fill(0);
148
239
  }
149
240
  }
150
- /** Is current platform little-endian? Most are. Big-Endian platform: IBM */
241
+ /** Whether the current platform is little-endian. */
151
242
  const isLE = /* @__PURE__ */ (() => new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44)();
152
- /** The byte swap operation for uint32 */
243
+ /**
244
+ * Byte-swap operation for uint32 values.
245
+ * @param word - source word
246
+ * @returns Word with reversed byte order.
247
+ * @example
248
+ * Reverse the byte order of a 32-bit word.
249
+ * ```ts
250
+ * byteSwap(0x11223344);
251
+ * ```
252
+ */
153
253
  function byteSwap(word) {
154
254
  return (((word << 24) & 0xff000000) |
155
255
  ((word << 8) & 0xff0000) |
156
256
  ((word >>> 8) & 0xff00) |
157
257
  ((word >>> 24) & 0xff));
158
258
  }
159
- /** In place byte swap for Uint32Array */
259
+ /**
260
+ * Byte-swaps every word of a Uint32Array in place.
261
+ * @param arr - array to mutate
262
+ * @returns The same array after mutation; callers pass live state arrays here.
263
+ * @example
264
+ * Reverse the byte order of every word in place.
265
+ * ```ts
266
+ * byteSwap32(new Uint32Array([0x11223344]));
267
+ * ```
268
+ */
160
269
  function byteSwap32(arr) {
161
270
  for (let i = 0; i < arr.length; i++) {
162
271
  arr[i] = byteSwap(arr[i]);
163
272
  }
164
273
  return arr;
165
274
  }
275
+ /**
276
+ * Conditionally byte-swaps a Uint32Array on big-endian platforms.
277
+ * @param u - array to normalize for host endianness
278
+ * @returns Original or byte-swapped array depending on platform endianness.
279
+ * On big-endian runtimes this mutates `u` in place via `byteSwap32(...)`.
280
+ * @example
281
+ * Normalize a word array for host endianness.
282
+ * ```ts
283
+ * swap32IfBE(new Uint32Array([0x11223344]));
284
+ * ```
285
+ */
166
286
  const swap32IfBE = isLE
167
287
  ? (u) => u
168
288
  : byteSwap32;
@@ -183,42 +303,89 @@ function asciiToBase16(ch) {
183
303
  }
184
304
  /**
185
305
  * Convert hex string to byte array. Uses built-in function, when available.
186
- * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])
306
+ * @param hex - hexadecimal string to decode
307
+ * @returns Decoded bytes.
308
+ * @throws On wrong argument types. {@link TypeError}
309
+ * @throws On wrong argument ranges or values. {@link RangeError}
310
+ * @example
311
+ * Decode lowercase hexadecimal into bytes.
312
+ * ```ts
313
+ * hexToBytes('cafe0123'); // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])
314
+ * ```
187
315
  */
188
316
  function hexToBytes$1(hex) {
189
317
  if (typeof hex !== 'string')
190
- throw new Error('hex string expected, got ' + typeof hex);
191
- // @ts-ignore
192
- if (hasHexBuiltin)
193
- return Uint8Array.fromHex(hex);
318
+ throw new TypeError('hex string expected, got ' + typeof hex);
319
+ if (hasHexBuiltin) {
320
+ try {
321
+ return Uint8Array.fromHex(hex);
322
+ }
323
+ catch (error) {
324
+ if (error instanceof SyntaxError)
325
+ throw new RangeError(error.message);
326
+ throw error;
327
+ }
328
+ }
194
329
  const hl = hex.length;
195
330
  const al = hl / 2;
196
331
  if (hl % 2)
197
- throw new Error('hex string expected, got unpadded hex of length ' + hl);
332
+ throw new RangeError('hex string expected, got unpadded hex of length ' + hl);
198
333
  const array = new Uint8Array(al);
199
334
  for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {
200
335
  const n1 = asciiToBase16(hex.charCodeAt(hi));
201
336
  const n2 = asciiToBase16(hex.charCodeAt(hi + 1));
202
337
  if (n1 === undefined || n2 === undefined) {
203
338
  const char = hex[hi] + hex[hi + 1];
204
- throw new Error('hex string expected, got non-hex character "' + char + '" at index ' + hi);
339
+ throw new RangeError('hex string expected, got non-hex character "' + char + '" at index ' + hi);
205
340
  }
206
341
  array[ai] = n1 * 16 + n2; // multiply first octet, e.g. 'a3' => 10*16+3 => 160 + 3 => 163
207
342
  }
208
343
  return array;
209
344
  }
210
- /** Creates function with outputLen, blockLen, create properties from a class constructor. */
345
+ /**
346
+ * Creates a callable hash function from a stateful class constructor.
347
+ * @param hashCons - hash constructor or factory
348
+ * @param info - optional metadata such as DER OID
349
+ * @returns Frozen callable hash wrapper with `.create()`.
350
+ * Wrapper construction eagerly calls `hashCons(undefined)` once to read
351
+ * `outputLen` / `blockLen`, so constructor side effects happen at module
352
+ * init time.
353
+ * @example
354
+ * Wrap a stateful hash constructor into a callable helper.
355
+ * ```ts
356
+ * import { createHasher } from '@noble/hashes/utils.js';
357
+ * import { sha256 } from '@noble/hashes/sha2.js';
358
+ * const wrapped = createHasher(sha256.create, { oid: sha256.oid });
359
+ * wrapped(new Uint8Array([1]));
360
+ * ```
361
+ */
211
362
  function createHasher(hashCons, info = {}) {
212
- const hashC = (msg, opts) => hashCons(opts).update(msg).digest();
363
+ const hashC = (msg, opts) => hashCons(opts)
364
+ .update(msg)
365
+ .digest();
213
366
  const tmp = hashCons(undefined);
214
367
  hashC.outputLen = tmp.outputLen;
215
368
  hashC.blockLen = tmp.blockLen;
369
+ hashC.canXOF = tmp.canXOF;
216
370
  hashC.create = (opts) => hashCons(opts);
217
371
  Object.assign(hashC, info);
218
372
  return Object.freeze(hashC);
219
373
  }
220
- /** Creates OID opts for NIST hashes, with prefix 06 09 60 86 48 01 65 03 04 02. */
374
+ /**
375
+ * Creates OID metadata for NIST hashes with prefix `06 09 60 86 48 01 65 03 04 02`.
376
+ * @param suffix - final OID byte for the selected hash.
377
+ * The helper accepts any byte even though only the documented NIST hash
378
+ * suffixes are meaningful downstream.
379
+ * @returns Object containing the DER-encoded OID.
380
+ * @example
381
+ * Build OID metadata for a NIST hash.
382
+ * ```ts
383
+ * oidNist(0x01);
384
+ * ```
385
+ */
221
386
  const oidNist = (suffix) => ({
387
+ // Current NIST hashAlgs suffixes used here fit in one DER subidentifier octet.
388
+ // Larger suffix values would need base-128 OID encoding and a different length byte.
222
389
  oid: Uint8Array.from([0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, suffix]),
223
390
  });
224
391
 
@@ -226,9 +393,11 @@ const oidNist = (suffix) => ({
226
393
  * SHA3 (keccak) hash function, based on a new "Sponge function" design.
227
394
  * Different from older hashes, the internal state is bigger than output size.
228
395
  *
229
- * Check out [FIPS-202](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.202.pdf),
230
- * [Website](https://keccak.team/keccak.html),
231
- * [the differences between SHA-3 and Keccak](https://crypto.stackexchange.com/questions/15727/what-are-the-key-differences-between-the-draft-sha-3-standard-and-the-keccak-sub).
396
+ * Check out
397
+ * {@link https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.202.pdf | FIPS-202},
398
+ * {@link https://keccak.team/keccak.html | Website}, and
399
+ * {@link https://crypto.stackexchange.com/q/15727 | the differences between
400
+ * SHA-3 and Keccak}.
232
401
  *
233
402
  * Check out `sha3-addons` module for cSHAKE, k12, and others.
234
403
  * @module
@@ -241,6 +410,8 @@ const _1n = BigInt(1);
241
410
  const _2n = BigInt(2);
242
411
  const _7n = BigInt(7);
243
412
  const _256n = BigInt(256);
413
+ // FIPS 202 Algorithm 5 rc(): when the outgoing bit is 1, the 8-bit LFSR xors
414
+ // taps 0, 4, 5, and 6, which compresses to the feedback mask `0x71`.
244
415
  const _0x71n = BigInt(0x71);
245
416
  const SHA3_PI = [];
246
417
  const SHA3_ROTL = [];
@@ -261,13 +432,31 @@ for (let round = 0, R = _1n, x = 1, y = 0; round < 24; round++) {
261
432
  _SHA3_IOTA.push(t);
262
433
  }
263
434
  const IOTAS = split(_SHA3_IOTA, true);
435
+ // `split(..., true)` keeps the local little-endian lane-word layout used by
436
+ // `state32`, so these `H` / `L` tables follow the file's first-word /
437
+ // second-word lane slots rather than `_u64.ts`'s usual high/low naming.
264
438
  const SHA3_IOTA_H = IOTAS[0];
265
439
  const SHA3_IOTA_L = IOTAS[1];
266
440
  // Left rotation (without 0, 32, 64)
267
441
  const rotlH = (h, l, s) => (s > 32 ? rotlBH(h, l, s) : rotlSH(h, l, s));
268
442
  const rotlL = (h, l, s) => (s > 32 ? rotlBL(h, l, s) : rotlSL(h, l, s));
269
- /** `keccakf1600` internal function, additionally allows to adjust round count. */
443
+ /**
444
+ * `keccakf1600` internal permutation, additionally allows adjusting the round count.
445
+ * @param s - 5x5 Keccak state encoded as 25 lanes split into 50 uint32 words
446
+ * in this file's local little-endian lane-word order
447
+ * @param rounds - number of rounds to execute
448
+ * @throws If `rounds` is outside the supported `1..24` range. {@link Error}
449
+ * @example
450
+ * Permute a Keccak state with the default 24 rounds.
451
+ * ```ts
452
+ * keccakP(new Uint32Array(50));
453
+ * ```
454
+ */
270
455
  function keccakP(s, rounds = 24) {
456
+ anumber(rounds, 'rounds');
457
+ // This implementation precomputes only the standard Keccak-f[1600] 24-round Iota table.
458
+ if (rounds < 1 || rounds > 24)
459
+ throw new Error('"rounds" expected integer 1..24');
271
460
  const B = new Uint32Array(5 * 2);
272
461
  // NOTE: all indices are x2 since we store state as u32 instead of u64 (bigints to slow in js)
273
462
  for (let round = 24 - rounds; round < 24; round++) {
@@ -300,11 +489,21 @@ function keccakP(s, rounds = 24) {
300
489
  s[PI + 1] = Tl;
301
490
  }
302
491
  // Chi (χ)
492
+ // Same as:
493
+ // for (let x = 0; x < 10; x++) B[x] = s[y + x];
494
+ // for (let x = 0; x < 10; x++) s[y + x] ^= ~B[(x + 2) % 10] & B[(x + 4) % 10];
303
495
  for (let y = 0; y < 50; y += 10) {
304
- for (let x = 0; x < 10; x++)
305
- B[x] = s[y + x];
306
- for (let x = 0; x < 10; x++)
307
- s[y + x] ^= ~B[(x + 2) % 10] & B[(x + 4) % 10];
496
+ const b0 = s[y], b1 = s[y + 1], b2 = s[y + 2], b3 = s[y + 3];
497
+ s[y] ^= ~s[y + 2] & s[y + 4];
498
+ s[y + 1] ^= ~s[y + 3] & s[y + 5];
499
+ s[y + 2] ^= ~s[y + 4] & s[y + 6];
500
+ s[y + 3] ^= ~s[y + 5] & s[y + 7];
501
+ s[y + 4] ^= ~s[y + 6] & s[y + 8];
502
+ s[y + 5] ^= ~s[y + 7] & s[y + 9];
503
+ s[y + 6] ^= ~s[y + 8] & b0;
504
+ s[y + 7] ^= ~s[y + 9] & b1;
505
+ s[y + 8] ^= ~b0 & b2;
506
+ s[y + 9] ^= ~b1 & b3;
308
507
  }
309
508
  // Iota (ι)
310
509
  s[0] ^= SHA3_IOTA_H[round];
@@ -312,7 +511,23 @@ function keccakP(s, rounds = 24) {
312
511
  }
313
512
  clean(B);
314
513
  }
315
- /** Keccak sponge function. */
514
+ /**
515
+ * Keccak sponge function.
516
+ * @param blockLen - absorb/squeeze rate in bytes
517
+ * @param suffix - domain separation suffix byte
518
+ * @param outputLen - default digest length in bytes. This base sponge only
519
+ * requires a non-negative integer; wrappers that need positive output
520
+ * lengths must enforce that themselves.
521
+ * @param enableXOF - whether XOF output is allowed
522
+ * @param rounds - number of Keccak-f rounds
523
+ * @example
524
+ * Build a sponge state, absorb bytes, then finalize a digest.
525
+ * ```ts
526
+ * const hash = new Keccak(136, 0x06, 32);
527
+ * hash.update(new Uint8Array([1, 2, 3]));
528
+ * hash.digest();
529
+ * ```
530
+ */
316
531
  class Keccak {
317
532
  state;
318
533
  pos = 0;
@@ -323,6 +538,7 @@ class Keccak {
323
538
  blockLen;
324
539
  suffix;
325
540
  outputLen;
541
+ canXOF;
326
542
  enableXOF = false;
327
543
  rounds;
328
544
  // NOTE: we accept arguments in bytes instead of bits here.
@@ -331,6 +547,7 @@ class Keccak {
331
547
  this.suffix = suffix;
332
548
  this.outputLen = outputLen;
333
549
  this.enableXOF = enableXOF;
550
+ this.canXOF = enableXOF;
334
551
  this.rounds = rounds;
335
552
  // Can be passed from user as dkLen
336
553
  anumber(outputLen, 'outputLen');
@@ -370,8 +587,13 @@ class Keccak {
370
587
  return;
371
588
  this.finished = true;
372
589
  const { state, suffix, pos, blockLen } = this;
373
- // Do the padding
590
+ // FIPS 202 appends the SHA3/SHAKE domain-separation suffix before pad10*1.
591
+ // These byte values already include the first padding bit, while the
592
+ // final `0x80` below supplies the closing `1` bit in the last rate byte.
374
593
  state[pos] ^= suffix;
594
+ // If that combined suffix lands in the last rate byte and already sets
595
+ // bit 7, absorb it first so the final pad10*1 bit can be xored into a
596
+ // fresh block.
375
597
  if ((suffix & 0x80) !== 0 && pos === blockLen - 1)
376
598
  this.keccak();
377
599
  state[blockLen - 1] ^= 0x80;
@@ -394,7 +616,9 @@ class Keccak {
394
616
  return out;
395
617
  }
396
618
  xofInto(out) {
397
- // Sha3/Keccak usage with XOF is probably mistake, only SHAKE instances can do XOF
619
+ // Plain SHA3/Keccak usage with XOF is probably a mistake, but this base
620
+ // class is also reused by SHAKE/cSHAKE/KMAC/TupleHash/ParallelHash/
621
+ // TurboSHAKE/KangarooTwelve wrappers that intentionally enable XOF.
398
622
  if (!this.enableXOF)
399
623
  throw new Error('XOF is not possible for this instance');
400
624
  return this.writeInto(out);
@@ -407,12 +631,14 @@ class Keccak {
407
631
  aoutput(out, this);
408
632
  if (this.finished)
409
633
  throw new Error('digest() was already called');
410
- this.writeInto(out);
634
+ // `aoutput(...)` allows oversized buffers; digestInto() must fill only the advertised digest.
635
+ this.writeInto(out.subarray(0, this.outputLen));
411
636
  this.destroy();
412
- return out;
413
637
  }
414
638
  digest() {
415
- return this.digestInto(new Uint8Array(this.outputLen));
639
+ const out = new Uint8Array(this.outputLen);
640
+ this.digestInto(out);
641
+ return out;
416
642
  }
417
643
  destroy() {
418
644
  this.destroyed = true;
@@ -421,6 +647,9 @@ class Keccak {
421
647
  _cloneInto(to) {
422
648
  const { blockLen, suffix, outputLen, rounds, enableXOF } = this;
423
649
  to ||= new Keccak(blockLen, suffix, outputLen, enableXOF, rounds);
650
+ // Reused destinations can come from a different rate/capacity variant, so clone must rewrite
651
+ // the sponge geometry as well as the state words.
652
+ to.blockLen = blockLen;
424
653
  to.state32.set(this.state32);
425
654
  to.pos = this.pos;
426
655
  to.posOut = this.posOut;
@@ -430,16 +659,39 @@ class Keccak {
430
659
  to.suffix = suffix;
431
660
  to.outputLen = outputLen;
432
661
  to.enableXOF = enableXOF;
662
+ // Clones must preserve the public capability bit too; `_KMAC` reuses this path and deep clone
663
+ // tests compare instance fields directly, so leaving `canXOF` behind makes the clone lie.
664
+ to.canXOF = this.canXOF;
433
665
  to.destroyed = this.destroyed;
434
666
  return to;
435
667
  }
436
668
  }
437
669
  const genShake = (suffix, blockLen, outputLen, info = {}) => createHasher((opts = {}) => new Keccak(blockLen, suffix, opts.dkLen === undefined ? outputLen : opts.dkLen, true), info);
438
- /** SHAKE128 XOF with 128-bit security. */
670
+ /**
671
+ * SHAKE128 XOF with 128-bit security and a 16-byte default output.
672
+ * @param msg - message bytes to hash
673
+ * @param opts - Optional output-length override. See {@link ShakeOpts}.
674
+ * @returns Digest bytes.
675
+ * @example
676
+ * Hash a message with SHAKE128.
677
+ * ```ts
678
+ * shake128(new Uint8Array([97, 98, 99]), { dkLen: 32 });
679
+ * ```
680
+ */
439
681
  const shake128 =
440
682
  /* @__PURE__ */
441
683
  genShake(0x1f, 168, 16, /* @__PURE__ */ oidNist(0x0b));
442
- /** SHAKE256 XOF with 256-bit security. */
684
+ /**
685
+ * SHAKE256 XOF with 256-bit security and a 32-byte default output.
686
+ * @param msg - message bytes to hash
687
+ * @param opts - Optional output-length override. See {@link ShakeOpts}.
688
+ * @returns Digest bytes.
689
+ * @example
690
+ * Hash a message with SHAKE256.
691
+ * ```ts
692
+ * shake256(new Uint8Array([97, 98, 99]), { dkLen: 64 });
693
+ * ```
694
+ */
443
695
  const shake256 =
444
696
  /* @__PURE__ */
445
697
  genShake(0x1f, 136, 32, /* @__PURE__ */ oidNist(0x0c));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@theqrl/mldsa87",
3
- "version": "2.1.0",
3
+ "version": "2.1.1",
4
4
  "description": "ML-DSA-87 cryptography",
5
5
  "keywords": [
6
6
  "ml-dsa",
@@ -63,24 +63,24 @@
63
63
  "@rollup/plugin-node-resolve": "16.0.3",
64
64
  "c8": "11.0.0",
65
65
  "chai": "6.2.2",
66
- "eslint": "10.0.3",
66
+ "eslint": "10.3.0",
67
67
  "eslint-config-prettier": "10.1.8",
68
68
  "eslint-plugin-import-x": "4.16.2",
69
69
  "eslint-plugin-prettier": "5.5.5",
70
- "globals": "17.4.0",
71
- "minimatch": "10.2.4",
70
+ "globals": "17.6.0",
71
+ "minimatch": "10.2.5",
72
72
  "mocha": "11.7.5",
73
- "prettier": "3.8.1",
74
- "rollup": "4.59.0",
75
- "serialize-javascript": "7.0.4",
76
- "tar": "7.5.11"
73
+ "prettier": "3.8.3",
74
+ "rollup": "4.60.3",
75
+ "serialize-javascript": "7.0.5",
76
+ "tar": "7.5.14"
77
77
  },
78
78
  "dependencies": {
79
- "@noble/hashes": "2.0.1"
79
+ "@noble/hashes": "2.2.0"
80
80
  },
81
81
  "overrides": {
82
82
  "diff": "8.0.3",
83
- "minimatch": "10.2.4"
83
+ "minimatch": "10.2.5"
84
84
  },
85
85
  "c8": {
86
86
  "include": [