@decryption/hashes 0.2.0

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 (60) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +75 -0
  3. package/_blake.d.ts +20 -0
  4. package/_blake.js +56 -0
  5. package/_md.d.ts +98 -0
  6. package/_md.js +207 -0
  7. package/_u64.d.ts +62 -0
  8. package/_u64.js +106 -0
  9. package/argon2.d.ts +111 -0
  10. package/argon2.js +525 -0
  11. package/blake1.d.ts +155 -0
  12. package/blake1.js +599 -0
  13. package/blake2.d.ts +183 -0
  14. package/blake2.js +540 -0
  15. package/blake3.d.ts +67 -0
  16. package/blake3.js +287 -0
  17. package/eskdf.d.ts +91 -0
  18. package/eskdf.js +223 -0
  19. package/esm/_blake.js +51 -0
  20. package/esm/_md.js +201 -0
  21. package/esm/_u64.js +83 -0
  22. package/esm/argon2.js +516 -0
  23. package/esm/blake1.js +559 -0
  24. package/esm/blake2.js +500 -0
  25. package/esm/blake3.js +283 -0
  26. package/esm/eskdf.js +217 -0
  27. package/esm/hkdf.js +119 -0
  28. package/esm/hmac.js +92 -0
  29. package/esm/index.js +34 -0
  30. package/esm/legacy.js +326 -0
  31. package/esm/pbkdf2.js +134 -0
  32. package/esm/scrypt.js +256 -0
  33. package/esm/sha2.js +457 -0
  34. package/esm/sha3-addons.js +782 -0
  35. package/esm/sha3.js +430 -0
  36. package/esm/utils.js +577 -0
  37. package/esm/webcrypto.js +163 -0
  38. package/hkdf.d.ts +63 -0
  39. package/hkdf.js +125 -0
  40. package/hmac.d.ts +46 -0
  41. package/hmac.js +96 -0
  42. package/index.d.ts +0 -0
  43. package/index.js +34 -0
  44. package/legacy.d.ts +101 -0
  45. package/legacy.js +332 -0
  46. package/package.json +47 -0
  47. package/pbkdf2.d.ts +55 -0
  48. package/pbkdf2.js +138 -0
  49. package/scrypt.d.ts +64 -0
  50. package/scrypt.js +260 -0
  51. package/sha2.d.ts +248 -0
  52. package/sha2.js +499 -0
  53. package/sha3-addons.d.ts +460 -0
  54. package/sha3-addons.js +791 -0
  55. package/sha3.d.ts +198 -0
  56. package/sha3.js +435 -0
  57. package/utils.d.ts +518 -0
  58. package/utils.js +606 -0
  59. package/webcrypto.d.ts +119 -0
  60. package/webcrypto.js +168 -0
package/sha3-addons.js ADDED
@@ -0,0 +1,791 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.keccakprg = exports._KeccakPRG = exports.HopMAC256 = exports.HopMAC128 = exports.kt256 = exports.kt128 = exports._KangarooTwelve = exports.turboshake256 = exports.turboshake128 = exports.parallelhash256xof = exports.parallelhash128xof = exports.parallelhash256 = exports.parallelhash128 = exports._ParallelHash = exports.tuplehash256xof = exports.tuplehash128xof = exports.tuplehash256 = exports.tuplehash128 = exports._TupleHash = exports.kmac256xof = exports.kmac128xof = exports.kmac256 = exports.kmac128 = exports._KMAC = exports.cshake256 = exports.cshake128 = void 0;
4
+ /**
5
+ * SHA3 (keccak) addons.
6
+ *
7
+ * * cSHAKE, KMAC, TupleHash, ParallelHash + XOF variants from
8
+ * {@link https://csrc.nist.gov/pubs/sp/800/185/final | NIST SP 800-185}
9
+ * * KangarooTwelve 🦘 and TurboSHAKE - reduced-round keccak from
10
+ * {@link https://datatracker.ietf.org/doc/rfc9861/ | RFC 9861}
11
+ * * KeccakPRG: Pseudo-random generator based on Keccak
12
+ * ({@link https://keccak.team/files/CSF-0.1.pdf | pdf})
13
+ * @module
14
+ */
15
+ const sha3_1 = require("./sha3");
16
+ const utils_1 = require("./utils");
17
+ // cSHAKE && KMAC (NIST SP800-185)
18
+ const _8n = /* @__PURE__ */ BigInt(8);
19
+ const _ffn = /* @__PURE__ */ BigInt(0xff);
20
+ // It is safe to use bigints here, since they used only for length encoding (not actual data).
21
+ // We use bigints in sha256 for lengths too.
22
+ // Callers are still expected to supply SP 800-185-valid lengths
23
+ // (`0 <= x < 2^2040`); this helper does not enforce that bound.
24
+ function leftEncode(n) {
25
+ n = BigInt(n);
26
+ const res = [Number(n & _ffn)];
27
+ n >>= _8n;
28
+ for (; n > 0; n >>= _8n)
29
+ res.unshift(Number(n & _ffn));
30
+ res.unshift(res.length);
31
+ return new Uint8Array(res);
32
+ }
33
+ // Same caller contract as `leftEncode(...)`: lengths must already satisfy SP 800-185 §2.3.1.
34
+ function rightEncode(n) {
35
+ n = BigInt(n);
36
+ const res = [Number(n & _ffn)];
37
+ n >>= _8n;
38
+ for (; n > 0; n >>= _8n)
39
+ res.unshift(Number(n & _ffn));
40
+ res.push(res.length);
41
+ return new Uint8Array(res);
42
+ }
43
+ // `dkLen` validation is deferred to the downstream Keccak constructor.
44
+ function chooseLen(opts, outputLen) {
45
+ return opts.dkLen === undefined ? outputLen : opts.dkLen;
46
+ }
47
+ const abytesOrZero = (buf, title = '') => {
48
+ if (buf === undefined)
49
+ return EMPTY_BUFFER;
50
+ (0, utils_1.abytes)(buf, undefined, title);
51
+ return buf;
52
+ };
53
+ // NOTE: second modulo is necessary since we don't need to add padding if the
54
+ // current element takes a whole block.
55
+ // Callers only pass the fixed positive Keccak rates here (`168` or `136`);
56
+ // `block <= 0` is not validated locally.
57
+ const getPadding = (len, block) => new Uint8Array((block - (len % block)) % block);
58
+ // Personalization
59
+ function cshakePers(hash, opts = {}) {
60
+ const h = hash;
61
+ if (!opts || (opts.personalization === undefined && opts.NISTfn === undefined))
62
+ return h;
63
+ // Encode and pad inplace to avoid unneccesary memory copies/slices so we
64
+ // don't need to zero them later.
65
+ // bytepad(encode_string(N) || encode_string(S), rate), where `rate` is the
66
+ // current cSHAKE/KMAC/TupleHash/ParallelHash block length.
67
+ const blockLenBytes = leftEncode(h.blockLen);
68
+ const fn = opts.NISTfn === undefined ? EMPTY_BUFFER : (0, utils_1.kdfInputToBytes)(opts.NISTfn);
69
+ const fnLen = leftEncode(_8n * BigInt(fn.length)); // length in bits
70
+ const pers = abytesOrZero(opts.personalization, 'personalization');
71
+ const persLen = leftEncode(_8n * BigInt(pers.length)); // length in bits
72
+ if (!fn.length && !pers.length)
73
+ return h;
74
+ // SP 800-185 cSHAKE appends `00` instead of SHAKE's `1111`; in this Keccak implementation
75
+ // that changes the delimited suffix byte from `0x1f` to `0x04` once N or S is non-empty.
76
+ h.suffix = 0x04;
77
+ h.update(blockLenBytes).update(fnLen).update(fn).update(persLen).update(pers);
78
+ let totalLen = blockLenBytes.length + fnLen.length + fn.length + persLen.length + pers.length;
79
+ h.update(getPadding(totalLen, h.blockLen));
80
+ return h;
81
+ }
82
+ const gencShake = (suffix, blockLen, outputLen) => (0, utils_1.createHasher)((opts = {}) => cshakePers(new sha3_1.Keccak(blockLen, suffix, chooseLen(opts, outputLen), true), opts));
83
+ /**
84
+ * 128-bit NIST cSHAKE XOF.
85
+ * @param msg - message bytes to hash
86
+ * @param opts - Optional output, personalization, and NIST function-name
87
+ * settings. When both `NISTfn` and `personalization` are empty,
88
+ * SP 800-185 defines this as plain SHAKE128. Defaults to 16 output bytes
89
+ * when `dkLen` is omitted. See {@link cShakeOpts}.
90
+ * @returns Digest bytes.
91
+ * @example
92
+ * Hash a message with cSHAKE128.
93
+ * ```ts
94
+ * cshake128(new Uint8Array([1, 2, 3]), { dkLen: 32 });
95
+ * ```
96
+ */
97
+ exports.cshake128 = gencShake(0x1f, 168, 16);
98
+ /**
99
+ * 256-bit NIST cSHAKE XOF.
100
+ * @param msg - message bytes to hash
101
+ * @param opts - Optional output, personalization, and NIST function-name
102
+ * settings. When both `NISTfn` and `personalization` are empty,
103
+ * SP 800-185 defines this as plain SHAKE256. Defaults to 32 output bytes
104
+ * when `dkLen` is omitted. See {@link cShakeOpts}.
105
+ * @returns Digest bytes.
106
+ * @example
107
+ * Hash a message with cSHAKE256.
108
+ * ```ts
109
+ * cshake256(new Uint8Array([1, 2, 3]), { dkLen: 64 });
110
+ * ```
111
+ */
112
+ exports.cshake256 = gencShake(0x1f, 136, 32);
113
+ /**
114
+ * Internal KMAC class.
115
+ * SP 800-185 §8.4.1 still recommends keys at least as long as the target
116
+ * security strength.
117
+ */
118
+ class _KMAC extends sha3_1.Keccak {
119
+ constructor(blockLen, outputLen, enableXOF, key, opts = {}) {
120
+ super(blockLen, 0x1f, outputLen, enableXOF);
121
+ // Preload T = bytepad(encode_string("KMAC") || encode_string(S), rate); later updates append
122
+ // newX = bytepad(encode_string(K), rate) || X and `finish()` appends right_encode(L or 0).
123
+ cshakePers(this, {
124
+ NISTfn: 'KMAC',
125
+ personalization: opts.personalization,
126
+ });
127
+ (0, utils_1.abytes)(key, undefined, 'key');
128
+ // 1. newX = bytepad(encode_string(K), rate) || X || right_encode(L),
129
+ // with `rate = this.blockLen`.
130
+ const blockLenBytes = leftEncode(this.blockLen);
131
+ const keyLen = leftEncode(_8n * BigInt(key.length));
132
+ this.update(blockLenBytes).update(keyLen).update(key);
133
+ const totalLen = blockLenBytes.length + keyLen.length + key.length;
134
+ this.update(getPadding(totalLen, this.blockLen));
135
+ }
136
+ finish() {
137
+ // SP 800-185 uses right_encode(L) for fixed-length KMAC and right_encode(0) for KMACXOF.
138
+ // outputLen in bits
139
+ if (!this.finished)
140
+ this.update(rightEncode(this.enableXOF ? 0 : _8n * BigInt(this.outputLen)));
141
+ super.finish();
142
+ }
143
+ _cloneInto(to) {
144
+ // Create new instance without calling constructor since the key
145
+ // is already in state and we don't know it.
146
+ // Force "to" to be instance of KMAC instead of Sha3.
147
+ if (!to) {
148
+ to = Object.create(Object.getPrototypeOf(this), {});
149
+ to.state = this.state.slice();
150
+ to.blockLen = this.blockLen;
151
+ to.state32 = (0, utils_1.u32)(to.state);
152
+ }
153
+ return super._cloneInto(to);
154
+ }
155
+ clone() {
156
+ return this._cloneInto();
157
+ }
158
+ }
159
+ exports._KMAC = _KMAC;
160
+ function genKmac(blockLen, outputLen, xof = false) {
161
+ // One-shot XOF wrappers still finalize via `.digest()` because `_KMAC`
162
+ // already bakes the requested output length into the state.
163
+ const kmac = (key, message, opts) => kmac.create(key, opts).update(message).digest();
164
+ kmac.create = (key, opts = {}) => new _KMAC(blockLen, chooseLen(opts, outputLen), xof, key, opts);
165
+ return kmac;
166
+ }
167
+ /**
168
+ * 128-bit Keccak MAC.
169
+ * @param key - MAC key bytes
170
+ * @param message - message bytes to authenticate
171
+ * @param opts - Optional output and personalization settings. Defaults to
172
+ * 16 output bytes when `dkLen` is omitted. See {@link cShakeOpts}.
173
+ * @returns Authentication tag bytes.
174
+ * @example
175
+ * Authenticate a message with KMAC128.
176
+ * ```ts
177
+ * kmac128(new Uint8Array([1, 2, 3]), new Uint8Array([4, 5, 6]));
178
+ * ```
179
+ */
180
+ exports.kmac128 = genKmac(168, 16);
181
+ /**
182
+ * 256-bit Keccak MAC.
183
+ * @param key - MAC key bytes
184
+ * @param message - message bytes to authenticate
185
+ * @param opts - Optional output and personalization settings. Defaults to
186
+ * 32 output bytes when `dkLen` is omitted. See {@link cShakeOpts}.
187
+ * @returns Authentication tag bytes.
188
+ * @example
189
+ * Authenticate a message with KMAC256.
190
+ * ```ts
191
+ * kmac256(new Uint8Array([1, 2, 3]), new Uint8Array([4, 5, 6]));
192
+ * ```
193
+ */
194
+ exports.kmac256 = genKmac(136, 32);
195
+ /**
196
+ * 128-bit Keccak-MAC XOF.
197
+ * @param key - MAC key bytes
198
+ * @param message - message bytes to authenticate
199
+ * @param opts - Optional output and personalization settings. Defaults to
200
+ * 16 output bytes when `dkLen` is omitted. See {@link cShakeOpts}.
201
+ * @returns Authentication tag bytes.
202
+ * @example
203
+ * Authenticate a message with KMAC128 XOF output.
204
+ * ```ts
205
+ * kmac128xof(new Uint8Array([1, 2, 3]), new Uint8Array([4, 5, 6]), { dkLen: 32 });
206
+ * ```
207
+ */
208
+ exports.kmac128xof = genKmac(168, 16, true);
209
+ /**
210
+ * 256-bit Keccak-MAC XOF.
211
+ * @param key - MAC key bytes
212
+ * @param message - message bytes to authenticate
213
+ * @param opts - Optional output and personalization settings. Defaults to
214
+ * 32 output bytes when `dkLen` is omitted. See {@link cShakeOpts}.
215
+ * @returns Authentication tag bytes.
216
+ * @example
217
+ * Authenticate a message with KMAC256 XOF output.
218
+ * ```ts
219
+ * kmac256xof(new Uint8Array([1, 2, 3]), new Uint8Array([4, 5, 6]), { dkLen: 64 });
220
+ * ```
221
+ */
222
+ exports.kmac256xof = genKmac(136, 32, true);
223
+ /**
224
+ * Internal TupleHash class for byte-array tuple elements.
225
+ * This implementation relies on SP 800-185's byte-oriented encoding form
226
+ * rather than arbitrary bit strings.
227
+ */
228
+ class _TupleHash extends sha3_1.Keccak {
229
+ constructor(blockLen, outputLen, enableXOF, opts = {}) {
230
+ super(blockLen, 0x1f, outputLen, enableXOF);
231
+ cshakePers(this, {
232
+ NISTfn: 'TupleHash',
233
+ personalization: opts.personalization,
234
+ });
235
+ // Change update after cshake processed
236
+ this.update = (data) => {
237
+ (0, utils_1.abytes)(data);
238
+ // SP 800-185 encodes each tuple element as
239
+ // encode_string(X[i]) = left_encode(len(X[i])) || X[i].
240
+ super.update(leftEncode(_8n * BigInt(data.length)));
241
+ super.update(data);
242
+ return this;
243
+ };
244
+ }
245
+ finish() {
246
+ // SP 800-185 uses right_encode(L) for fixed-length TupleHash
247
+ // and right_encode(0) for TupleHashXOF.
248
+ if (!this.finished)
249
+ // outputLen in bits
250
+ super.update(rightEncode(this.enableXOF ? 0 : _8n * BigInt(this.outputLen)));
251
+ super.finish();
252
+ }
253
+ _cloneInto(to) {
254
+ to ||= new _TupleHash(this.blockLen, this.outputLen, this.enableXOF);
255
+ return super._cloneInto(to);
256
+ }
257
+ clone() {
258
+ return this._cloneInto();
259
+ }
260
+ }
261
+ exports._TupleHash = _TupleHash;
262
+ function genTuple(blockLen, outputLen, xof = false) {
263
+ // One-shot XOF wrappers still use `.digest()` because `_TupleHash` stores
264
+ // the requested output length in the state itself.
265
+ const tuple = (messages, opts) => {
266
+ const h = tuple.create(opts);
267
+ if (!Array.isArray(messages))
268
+ throw new Error('expected array of messages');
269
+ for (const msg of messages)
270
+ h.update(msg);
271
+ return h.digest();
272
+ };
273
+ tuple.create = (opts = {}) => new _TupleHash(blockLen, chooseLen(opts, outputLen), xof, opts);
274
+ return tuple;
275
+ }
276
+ /**
277
+ * 128-bit TupleHASH. `tuple(['ab', 'cd']) != tuple(['a', 'bcd'])`.
278
+ * @param messages - ordered byte-array tuple
279
+ * @param opts - Optional output and personalization settings. Defaults to
280
+ * 16 output bytes when `dkLen` is omitted. See {@link cShakeOpts}.
281
+ * @returns Digest bytes.
282
+ * @example
283
+ * Hash a tuple of byte arrays with TupleHash128.
284
+ * ```ts
285
+ * tuplehash128([new Uint8Array([1]), new Uint8Array([2])]);
286
+ * ```
287
+ */
288
+ exports.tuplehash128 = genTuple(168, 16);
289
+ /**
290
+ * 256-bit TupleHASH. `tuple(['ab', 'cd']) != tuple(['a', 'bcd'])`.
291
+ * @param messages - ordered byte-array tuple
292
+ * @param opts - Optional output and personalization settings. Defaults to
293
+ * 32 output bytes when `dkLen` is omitted. See {@link cShakeOpts}.
294
+ * @returns Digest bytes.
295
+ * @example
296
+ * Hash a tuple of byte arrays with TupleHash256.
297
+ * ```ts
298
+ * tuplehash256([new Uint8Array([1]), new Uint8Array([2])]);
299
+ * ```
300
+ */
301
+ exports.tuplehash256 = genTuple(136, 32);
302
+ /**
303
+ * 128-bit TupleHASH XOF.
304
+ * @param messages - ordered byte-array tuple
305
+ * @param opts - Optional output and personalization settings. Defaults to
306
+ * 16 output bytes when `dkLen` is omitted. See {@link cShakeOpts}.
307
+ * @returns Digest bytes.
308
+ * @example
309
+ * Hash a tuple of byte arrays with TupleHash128 XOF output.
310
+ * ```ts
311
+ * tuplehash128xof([new Uint8Array([1]), new Uint8Array([2])], { dkLen: 32 });
312
+ * ```
313
+ */
314
+ exports.tuplehash128xof = genTuple(168, 16, true);
315
+ /**
316
+ * 256-bit TupleHASH XOF.
317
+ * @param messages - ordered byte-array tuple
318
+ * @param opts - Optional output and personalization settings. Defaults to
319
+ * 32 output bytes when `dkLen` is omitted. See {@link cShakeOpts}.
320
+ * @returns Digest bytes.
321
+ * @example
322
+ * Hash a tuple of byte arrays with TupleHash256 XOF output.
323
+ * ```ts
324
+ * tuplehash256xof([new Uint8Array([1]), new Uint8Array([2])], { dkLen: 64 });
325
+ * ```
326
+ */
327
+ exports.tuplehash256xof = genTuple(136, 32, true);
328
+ /** Internal Parallel Keccak Hash class. */
329
+ class _ParallelHash extends sha3_1.Keccak {
330
+ leafHash;
331
+ leafCons;
332
+ chunkPos = 0; // Position of current block in chunk
333
+ chunksDone = 0; // How many chunks we already have
334
+ chunkLen;
335
+ constructor(blockLen, outputLen, leafCons, enableXOF, opts = {}) {
336
+ super(blockLen, 0x1f, outputLen, enableXOF);
337
+ cshakePers(this, {
338
+ NISTfn: 'ParallelHash',
339
+ personalization: opts.personalization,
340
+ });
341
+ this.leafCons = leafCons;
342
+ let { blockLen: B = 8 } = opts;
343
+ (0, utils_1.anumber)(B);
344
+ // blockLen=0 makes take=0 in update(), so pos never advances and the hash hangs.
345
+ if (B < 1)
346
+ throw new Error('"blockLen" must be >= 1, got ' + B);
347
+ this.chunkLen = B;
348
+ // SP 800-185 initializes z = left_encode(B); each completed chunk appends
349
+ // one fixed-size cSHAKE leaf digest before finish() adds right_encode(n)
350
+ // and right_encode(L or 0).
351
+ super.update(leftEncode(B));
352
+ // Change update after cshake processed
353
+ this.update = (data) => {
354
+ (0, utils_1.abytes)(data);
355
+ const { chunkLen, leafCons } = this;
356
+ for (let pos = 0, len = data.length; pos < len;) {
357
+ if (this.chunkPos == chunkLen || !this.leafHash) {
358
+ if (this.leafHash) {
359
+ super.update(this.leafHash.digest());
360
+ this.chunksDone++;
361
+ }
362
+ this.leafHash = leafCons();
363
+ this.chunkPos = 0;
364
+ }
365
+ const take = Math.min(chunkLen - this.chunkPos, len - pos);
366
+ this.leafHash.update(data.subarray(pos, pos + take));
367
+ this.chunkPos += take;
368
+ pos += take;
369
+ }
370
+ return this;
371
+ };
372
+ }
373
+ finish() {
374
+ if (this.finished)
375
+ return;
376
+ if (this.leafHash) {
377
+ super.update(this.leafHash.digest());
378
+ this.chunksDone++;
379
+ }
380
+ // SP 800-185 finishes ParallelHash as
381
+ // z || right_encode(n) || right_encode(L); XOF mode replaces
382
+ // right_encode(L) with right_encode(0).
383
+ super.update(rightEncode(this.chunksDone));
384
+ // outputLen in bits
385
+ super.update(rightEncode(this.enableXOF ? 0 : _8n * BigInt(this.outputLen)));
386
+ super.finish();
387
+ }
388
+ _cloneInto(to) {
389
+ to ||= new _ParallelHash(this.blockLen, this.outputLen, this.leafCons, this.enableXOF);
390
+ to.leafCons = this.leafCons;
391
+ // Reused destinations can carry a stale partial leaf
392
+ // when the source is still on the root sponge.
393
+ if (this.leafHash)
394
+ to.leafHash = this.leafHash._cloneInto(to.leafHash);
395
+ else if (to.leafHash) {
396
+ to.leafHash.destroy();
397
+ to.leafHash = undefined;
398
+ }
399
+ to.chunkPos = this.chunkPos;
400
+ to.chunkLen = this.chunkLen;
401
+ to.chunksDone = this.chunksDone;
402
+ return super._cloneInto(to);
403
+ }
404
+ destroy() {
405
+ super.destroy.call(this);
406
+ if (this.leafHash)
407
+ this.leafHash.destroy();
408
+ }
409
+ clone() {
410
+ return this._cloneInto();
411
+ }
412
+ }
413
+ exports._ParallelHash = _ParallelHash;
414
+ function genPrl(blockLen, outputLen, leaf, xof = false) {
415
+ const parallel = (message, opts) => parallel.create(opts).update(message).digest();
416
+ parallel.create = (opts = {}) => new _ParallelHash(blockLen, chooseLen(opts, outputLen),
417
+ // SP 800-185 fixes leaf digests at 256 bits for ParallelHash128 and
418
+ // 512 bits for ParallelHash256; only the final cSHAKE output uses the
419
+ // caller-selected dkLen.
420
+ () => leaf.create({ dkLen: 2 * outputLen }), xof, opts);
421
+ parallel.outputLen = outputLen;
422
+ parallel.blockLen = blockLen;
423
+ parallel.canXOF = xof;
424
+ return parallel;
425
+ }
426
+ /**
427
+ * 128-bit ParallelHash. In JS, it is not parallel.
428
+ * @param msg - message bytes to hash
429
+ * @param opts - Optional output, personalization, and chunking settings.
430
+ * Defaults to 16 output bytes when `dkLen` is omitted.
431
+ * See {@link ParallelOpts}.
432
+ * @returns Digest bytes.
433
+ * @example
434
+ * Hash a message with ParallelHash128.
435
+ * ```ts
436
+ * parallelhash128(new Uint8Array([1, 2, 3]));
437
+ * ```
438
+ */
439
+ exports.parallelhash128 = genPrl(168, 16, exports.cshake128);
440
+ /**
441
+ * 256-bit ParallelHash. In JS, it is not parallel.
442
+ * @param msg - message bytes to hash
443
+ * @param opts - Optional output, personalization, and chunking settings.
444
+ * Defaults to 32 output bytes when `dkLen` is omitted.
445
+ * See {@link ParallelOpts}.
446
+ * @returns Digest bytes.
447
+ * @example
448
+ * Hash a message with ParallelHash256.
449
+ * ```ts
450
+ * parallelhash256(new Uint8Array([1, 2, 3]));
451
+ * ```
452
+ */
453
+ exports.parallelhash256 = genPrl(136, 32, exports.cshake256);
454
+ /**
455
+ * 128-bit ParallelHash XOF. In JS, it is not parallel.
456
+ * @param msg - message bytes to hash
457
+ * @param opts - Optional output, personalization, and chunking settings.
458
+ * Defaults to 16 output bytes when `dkLen` is omitted.
459
+ * See {@link ParallelOpts}.
460
+ * @returns Digest bytes.
461
+ * @example
462
+ * Hash a message with ParallelHash128 XOF output.
463
+ * ```ts
464
+ * parallelhash128xof(new Uint8Array([1, 2, 3]), { dkLen: 32 });
465
+ * ```
466
+ */
467
+ exports.parallelhash128xof = genPrl(168, 16, exports.cshake128, true);
468
+ /**
469
+ * 256-bit ParallelHash XOF. In JS, it is not parallel.
470
+ * @param msg - message bytes to hash
471
+ * @param opts - Optional output, personalization, and chunking settings.
472
+ * Defaults to 32 output bytes when `dkLen` is omitted.
473
+ * See {@link ParallelOpts}.
474
+ * @returns Digest bytes.
475
+ * @example
476
+ * Hash a message with ParallelHash256 XOF output.
477
+ * ```ts
478
+ * parallelhash256xof(new Uint8Array([1, 2, 3]), { dkLen: 64 });
479
+ * ```
480
+ */
481
+ exports.parallelhash256xof = genPrl(136, 32, exports.cshake256, true);
482
+ const genTurbo = (blockLen, outputLen) => (0, utils_1.createHasher)((opts = {}) => {
483
+ const D = opts.D === undefined ? 0x1f : opts.D;
484
+ // RFC 9861 §2.1 fixes the default `D = 0x1f`; §2.2 defines the 12-round
485
+ // TurboSHAKE family selected here.
486
+ if (!Number.isSafeInteger(D) || D < 0x01 || D > 0x7f)
487
+ throw new Error('"D" (domain separation byte) must be 0x01..0x7f, got: ' + D);
488
+ const dkLen = opts.dkLen === undefined ? outputLen : opts.dkLen;
489
+ // RFC 9861 §§2.1-2.2 define output length L as a positive integer.
490
+ if (dkLen < 1)
491
+ throw new Error('"dkLen" must be >= 1');
492
+ return new sha3_1.Keccak(blockLen, D, dkLen, true, 12);
493
+ });
494
+ /**
495
+ * TurboSHAKE 128-bit: reduced 12-round keccak.
496
+ * Should've been a simple "shake with 12 rounds", but we got a whole new
497
+ * spec about Turbo SHAKE Pro MAX.
498
+ * @param msg - message bytes to hash
499
+ * @param opts - Optional output-length and domain-separation settings.
500
+ * RFC 9861 §2.1 defaults `D` to `0x1f`. Defaults to 32 output bytes when
501
+ * `dkLen` is omitted. See {@link TurboshakeOpts}.
502
+ * @returns Digest bytes.
503
+ * @example
504
+ * Hash a message with TurboSHAKE128.
505
+ * ```ts
506
+ * turboshake128(new Uint8Array([1, 2, 3]), { dkLen: 32 });
507
+ * ```
508
+ */
509
+ exports.turboshake128 = genTurbo(168, 32);
510
+ /**
511
+ * TurboSHAKE 256-bit: reduced 12-round keccak.
512
+ * @param msg - message bytes to hash
513
+ * @param opts - Optional output-length and domain-separation settings.
514
+ * RFC 9861 §2.1 defaults `D` to `0x1f`. Defaults to 64 output bytes when
515
+ * `dkLen` is omitted. See {@link TurboshakeOpts}.
516
+ * @returns Digest bytes.
517
+ * @example
518
+ * Hash a message with TurboSHAKE256.
519
+ * ```ts
520
+ * turboshake256(new Uint8Array([1, 2, 3]), { dkLen: 64 });
521
+ * ```
522
+ */
523
+ exports.turboshake256 = genTurbo(136, 64);
524
+ // Same as NIST rightEncode, but returns `[0]` for the zero string.
525
+ // Callers still need to keep `x < 256^255` per RFC 9861 §3.3.
526
+ function rightEncodeK12(n) {
527
+ n = BigInt(n);
528
+ const res = [];
529
+ for (; n > 0; n >>= _8n)
530
+ res.unshift(Number(n & _ffn));
531
+ res.push(res.length);
532
+ return Uint8Array.from(res);
533
+ }
534
+ const EMPTY_BUFFER = /* @__PURE__ */ Uint8Array.of();
535
+ /** Internal K12 hash class. */
536
+ class _KangarooTwelve extends sha3_1.Keccak {
537
+ chunkLen = 8192;
538
+ leafHash;
539
+ leafLen;
540
+ personalization;
541
+ chunkPos = 0; // Position of current block in chunk
542
+ chunksDone = 0; // How many chunks we already have
543
+ constructor(blockLen, leafLen, outputLen, rounds, opts) {
544
+ super(blockLen, 0x07, outputLen, true, rounds);
545
+ // RFC 9861 §3 defines output length L as a positive integer.
546
+ if (outputLen < 1)
547
+ throw new Error('"dkLen" must be >= 1');
548
+ this.leafLen = leafLen;
549
+ this.personalization =
550
+ opts.personalization === undefined
551
+ ? EMPTY_BUFFER
552
+ : (0, utils_1.copyBytes)((0, utils_1.abytes)(opts.personalization, undefined, 'personalization'));
553
+ }
554
+ update(data) {
555
+ (0, utils_1.abytes)(data);
556
+ const { chunkLen, blockLen, leafLen, rounds } = this;
557
+ for (let pos = 0, len = data.length; pos < len;) {
558
+ if (this.chunkPos == chunkLen) {
559
+ if (this.leafHash)
560
+ super.update(this.leafHash.digest());
561
+ else {
562
+ // RFC 9861 §3.2 switches from SingleNode (`07`) to FinalNode (`06`)
563
+ // once S exceeds 8192 bytes and prefixes S_0 with
564
+ // `03 00 00 00 00 00 00 00`.
565
+ this.suffix = 0x06; // Its safe to change suffix here since its used only in digest()
566
+ super.update(Uint8Array.from([3, 0, 0, 0, 0, 0, 0, 0]));
567
+ }
568
+ // Secondary chunks S_1..S_(n-1) become fixed-length
569
+ // CV_i = TurboSHAKE*(S_i, `0B`, 32|64) chaining values.
570
+ this.leafHash = new sha3_1.Keccak(blockLen, 0x0b, leafLen, false, rounds);
571
+ this.chunksDone++;
572
+ this.chunkPos = 0;
573
+ }
574
+ const take = Math.min(chunkLen - this.chunkPos, len - pos);
575
+ const chunk = data.subarray(pos, pos + take);
576
+ if (this.leafHash)
577
+ this.leafHash.update(chunk);
578
+ else
579
+ super.update(chunk);
580
+ this.chunkPos += take;
581
+ pos += take;
582
+ }
583
+ return this;
584
+ }
585
+ finish() {
586
+ if (this.finished)
587
+ return;
588
+ const { personalization } = this;
589
+ // RFC 9861 §3.2 forms S = M || C || length_encode(|C|) before any tree hashing logic.
590
+ this.update(personalization).update(rightEncodeK12(personalization.length));
591
+ // Leaf hash
592
+ if (this.leafHash) {
593
+ // Multi-chunk K12 appends
594
+ // CV_1..CV_(n-1) || length_encode(n-1) || `FF FF`
595
+ // before the final TurboSHAKE call.
596
+ super.update(this.leafHash.digest());
597
+ super.update(rightEncodeK12(this.chunksDone));
598
+ super.update(Uint8Array.from([0xff, 0xff]));
599
+ }
600
+ super.finish.call(this);
601
+ }
602
+ destroy() {
603
+ super.destroy.call(this);
604
+ if (this.leafHash)
605
+ this.leafHash.destroy();
606
+ // Personalization is copied on create/clone, so destroy can wipe it
607
+ // without touching caller input.
608
+ if (this.personalization !== EMPTY_BUFFER)
609
+ (0, utils_1.clean)(this.personalization);
610
+ this.personalization = EMPTY_BUFFER;
611
+ }
612
+ _cloneInto(to) {
613
+ const { blockLen, leafLen, leafHash, outputLen, rounds } = this;
614
+ const personalization = this.personalization === EMPTY_BUFFER ? EMPTY_BUFFER : (0, utils_1.copyBytes)(this.personalization);
615
+ // Personalization is absorbed only during finish(), so clones need the same pending value.
616
+ to ||= new _KangarooTwelve(blockLen, leafLen, outputLen, rounds, {
617
+ personalization,
618
+ });
619
+ super._cloneInto(to);
620
+ // Reused destinations can carry a stale leaf from an older multi-chunk state.
621
+ if (leafHash)
622
+ to.leafHash = leafHash._cloneInto(to.leafHash);
623
+ else if (to.leafHash) {
624
+ to.leafHash.destroy();
625
+ to.leafHash = undefined;
626
+ }
627
+ // Snapshot the pending personalization so clone state does not alias caller-owned input.
628
+ to.personalization = personalization;
629
+ to.leafLen = this.leafLen;
630
+ to.chunkPos = this.chunkPos;
631
+ to.chunksDone = this.chunksDone;
632
+ return to;
633
+ }
634
+ clone() {
635
+ return this._cloneInto();
636
+ }
637
+ }
638
+ exports._KangarooTwelve = _KangarooTwelve;
639
+ /**
640
+ * 128-bit KangarooTwelve (k12): reduced 12-round keccak.
641
+ * @param msg - message bytes to hash
642
+ * @param opts - Optional output and personalization settings. Defaults to
643
+ * 32 output bytes when `dkLen` is omitted. See {@link KangarooOpts}.
644
+ * @returns Digest bytes.
645
+ * @example
646
+ * Hash a message with KangarooTwelve-128.
647
+ * ```ts
648
+ * kt128(new Uint8Array([1, 2, 3]));
649
+ * ```
650
+ */
651
+ exports.kt128 = (0, utils_1.createHasher)((opts = {}) => new _KangarooTwelve(168, 32, chooseLen(opts, 32), 12, opts));
652
+ /**
653
+ * 256-bit KangarooTwelve (k12): reduced 12-round keccak.
654
+ * @param msg - message bytes to hash
655
+ * @param opts - Optional output and personalization settings. Defaults to
656
+ * 64 output bytes when `dkLen` is omitted. See {@link KangarooOpts}.
657
+ * @returns Digest bytes.
658
+ * @example
659
+ * Hash a message with KangarooTwelve-256.
660
+ * ```ts
661
+ * kt256(new Uint8Array([1, 2, 3]));
662
+ * ```
663
+ */
664
+ exports.kt256 = (0, utils_1.createHasher)((opts = {}) => new _KangarooTwelve(136, 64, chooseLen(opts, 64), 12, opts));
665
+ const genHopMAC = (hash) => (key, message, personalization, dkLen) => {
666
+ const h = hash;
667
+ return h(key, { personalization: h(message, { personalization }), dkLen });
668
+ };
669
+ /**
670
+ * 128-bit KangarooTwelve-based MAC.
671
+ *
672
+ * These untested (there is no test vectors or implementation available). Use at your own risk.
673
+ * HopMAC128(Key, M, C, L) = KT128(Key, KT128(M, C, 32), L)
674
+ * HopMAC256(Key, M, C, L) = KT256(Key, KT256(M, C, 64), L)
675
+ * The inner KangarooTwelve call always uses a fixed 32-byte digest here,
676
+ * regardless of the outer `dkLen`.
677
+ * @param key - MAC key bytes
678
+ * @param message - message bytes to authenticate
679
+ * @param personalization - personalization bytes mixed into the inner hash
680
+ * @param dkLen - optional output length in bytes
681
+ * @returns Authentication tag bytes.
682
+ * @example
683
+ * Authenticate a message with HopMAC128.
684
+ * ```ts
685
+ * HopMAC128(new Uint8Array([1]), new Uint8Array([2]), new Uint8Array([3]), 32);
686
+ * ```
687
+ */
688
+ exports.HopMAC128 = genHopMAC(exports.kt128);
689
+ /**
690
+ * 256-bit KangarooTwelve-based MAC.
691
+ * Like `HopMAC128`, there are no test vectors or known independent
692
+ * implementations available for cross-checking.
693
+ * @param key - MAC key bytes
694
+ * @param message - message bytes to authenticate
695
+ * @param personalization - personalization bytes mixed into the inner hash
696
+ * @param dkLen - optional output length in bytes. The inner KangarooTwelve
697
+ * call still uses a fixed 64-byte digest here, regardless of the outer
698
+ * `dkLen`.
699
+ * @returns Authentication tag bytes.
700
+ * @example
701
+ * Authenticate a message with HopMAC256.
702
+ * ```ts
703
+ * HopMAC256(new Uint8Array([1]), new Uint8Array([2]), new Uint8Array([3]), 64);
704
+ * ```
705
+ */
706
+ exports.HopMAC256 = genHopMAC(exports.kt256);
707
+ /**
708
+ * More at
709
+ * {@link https://github.com/XKCP/XKCP/tree/master/lib/high/Keccak/PRG}.
710
+ * Accepted capacities must keep `rho = 1598 - capacity` byte-aligned, and
711
+ * `.clean()` later also requires `rate > 801`.
712
+ */
713
+ class _KeccakPRG extends sha3_1.Keccak {
714
+ rate;
715
+ constructor(capacity) {
716
+ (0, utils_1.anumber)(capacity);
717
+ const rate = 1600 - capacity;
718
+ const rho = rate - 2;
719
+ // Rho must be full bytes
720
+ if (capacity < 0 || capacity > 1600 - 10 || rho % 8)
721
+ throw new Error('invalid capacity');
722
+ // blockLen = rho in bytes
723
+ super(rho / 8, 0, 0, true);
724
+ this.rate = rate;
725
+ this.posOut = Math.floor((rate + 7) / 8);
726
+ }
727
+ keccak() {
728
+ // Duplex padding
729
+ this.state[this.pos] ^= 0x01;
730
+ this.state[this.blockLen] ^= 0x02; // Rho is full bytes
731
+ super.keccak();
732
+ this.pos = 0;
733
+ this.posOut = 0;
734
+ }
735
+ update(data) {
736
+ super.update(data);
737
+ this.posOut = this.blockLen;
738
+ return this;
739
+ }
740
+ finish() { }
741
+ digestInto(_out) {
742
+ throw new Error('digest is not allowed, use .randomBytes() instead');
743
+ }
744
+ addEntropy(seed) {
745
+ this.update(seed);
746
+ }
747
+ randomBytes(length) {
748
+ return this.xof(length);
749
+ }
750
+ clean() {
751
+ // clean() mutates live sponge state just like randomBytes(),
752
+ // so destroyed instances must reject it.
753
+ (0, utils_1.aexists)(this, false);
754
+ if (this.rate < 1600 / 2 + 1)
755
+ throw new Error('rate is too low to use .forget()');
756
+ this.keccak();
757
+ for (let i = 0; i < this.blockLen; i++)
758
+ this.state[i] = 0;
759
+ this.pos = this.blockLen;
760
+ this.keccak();
761
+ this.posOut = this.blockLen;
762
+ }
763
+ _cloneInto(to) {
764
+ const { rate } = this;
765
+ to ||= new _KeccakPRG(1600 - rate);
766
+ super._cloneInto(to);
767
+ to.rate = rate;
768
+ return to;
769
+ }
770
+ clone() {
771
+ return this._cloneInto();
772
+ }
773
+ }
774
+ exports._KeccakPRG = _KeccakPRG;
775
+ /**
776
+ * KeccakPRG: pseudo-random generator based on Keccak.
777
+ * See {@link https://keccak.team/files/CSF-0.1.pdf}.
778
+ * @param capacity - sponge capacity in bits. Accepted values are those that
779
+ * keep `rho = 1598 - capacity` byte-aligned; the default `254` is chosen
780
+ * because it satisfies that duplex layout while leaving a wide byte-aligned
781
+ * rate.
782
+ * @returns PRG instance backed by a Keccak sponge.
783
+ * @example
784
+ * Create a Keccak-based pseudorandom generator and read bytes from it.
785
+ * ```ts
786
+ * const prg = keccakprg(254);
787
+ * prg.randomBytes(8);
788
+ * ```
789
+ */
790
+ const keccakprg = (capacity = 254) => new _KeccakPRG(capacity);
791
+ exports.keccakprg = keccakprg;