@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/utils.js ADDED
@@ -0,0 +1,606 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.oidNist = exports.nextTick = exports.swap32IfBE = exports.swap8IfBE = exports.isLE = void 0;
4
+ exports.isBytes = isBytes;
5
+ exports.anumber = anumber;
6
+ exports.abytes = abytes;
7
+ exports.copyBytes = copyBytes;
8
+ exports.ahash = ahash;
9
+ exports.aexists = aexists;
10
+ exports.aoutput = aoutput;
11
+ exports.u8 = u8;
12
+ exports.u32 = u32;
13
+ exports.clean = clean;
14
+ exports.createView = createView;
15
+ exports.rotr = rotr;
16
+ exports.rotl = rotl;
17
+ exports.byteSwap = byteSwap;
18
+ exports.byteSwap32 = byteSwap32;
19
+ exports.bytesToHex = bytesToHex;
20
+ exports.hexToBytes = hexToBytes;
21
+ exports.asyncLoop = asyncLoop;
22
+ exports.utf8ToBytes = utf8ToBytes;
23
+ exports.kdfInputToBytes = kdfInputToBytes;
24
+ exports.concatBytes = concatBytes;
25
+ exports.checkOpts = checkOpts;
26
+ exports.createHasher = createHasher;
27
+ exports.randomBytes = randomBytes;
28
+ /**
29
+ * Checks if something is Uint8Array. Be careful: nodejs Buffer will return true.
30
+ * @param a - value to test
31
+ * @returns `true` when the value is a Uint8Array-compatible view.
32
+ * @example
33
+ * Check whether a value is a Uint8Array-compatible view.
34
+ * ```ts
35
+ * isBytes(new Uint8Array([1, 2, 3]));
36
+ * ```
37
+ */
38
+ function isBytes(a) {
39
+ // Plain `instanceof Uint8Array` is too strict for some Buffer / proxy / cross-realm cases.
40
+ // The fallback still requires a real ArrayBuffer view, so plain
41
+ // JSON-deserialized `{ constructor: ... }` spoofing is rejected, and
42
+ // `BYTES_PER_ELEMENT === 1` keeps the fallback on byte-oriented views.
43
+ return (a instanceof Uint8Array ||
44
+ (ArrayBuffer.isView(a) &&
45
+ a.constructor.name === 'Uint8Array' &&
46
+ 'BYTES_PER_ELEMENT' in a &&
47
+ a.BYTES_PER_ELEMENT === 1));
48
+ }
49
+ /**
50
+ * Asserts something is a non-negative integer.
51
+ * @param n - number to validate
52
+ * @param title - label included in thrown errors
53
+ * @throws On wrong argument types. {@link TypeError}
54
+ * @throws On wrong argument ranges or values. {@link RangeError}
55
+ * @example
56
+ * Validate a non-negative integer option.
57
+ * ```ts
58
+ * anumber(32, 'length');
59
+ * ```
60
+ */
61
+ function anumber(n, title = '') {
62
+ if (typeof n !== 'number') {
63
+ const prefix = title && `"${title}" `;
64
+ throw new TypeError(`${prefix}expected number, got ${typeof n}`);
65
+ }
66
+ if (!Number.isSafeInteger(n) || n < 0) {
67
+ const prefix = title && `"${title}" `;
68
+ throw new RangeError(`${prefix}expected integer >= 0, got ${n}`);
69
+ }
70
+ }
71
+ /**
72
+ * Asserts something is Uint8Array.
73
+ * @param value - value to validate
74
+ * @param length - optional exact length constraint
75
+ * @param title - label included in thrown errors
76
+ * @returns The validated byte array.
77
+ * @throws On wrong argument types. {@link TypeError}
78
+ * @throws On wrong argument ranges or values. {@link RangeError}
79
+ * @example
80
+ * Validate that a value is a byte array.
81
+ * ```ts
82
+ * abytes(new Uint8Array([1, 2, 3]));
83
+ * ```
84
+ */
85
+ function abytes(value, length, title = '') {
86
+ const bytes = isBytes(value);
87
+ const len = value?.length;
88
+ const needsLen = length !== undefined;
89
+ if (!bytes || (needsLen && len !== length)) {
90
+ const prefix = title && `"${title}" `;
91
+ const ofLen = needsLen ? ` of length ${length}` : '';
92
+ const got = bytes ? `length=${len}` : `type=${typeof value}`;
93
+ const message = prefix + 'expected Uint8Array' + ofLen + ', got ' + got;
94
+ if (!bytes)
95
+ throw new TypeError(message);
96
+ throw new RangeError(message);
97
+ }
98
+ return value;
99
+ }
100
+ /**
101
+ * Copies bytes into a fresh Uint8Array.
102
+ * Buffer-style slices can alias the same backing store, so callers that need ownership should copy.
103
+ * @param bytes - source bytes to clone
104
+ * @returns Freshly allocated copy of `bytes`.
105
+ * @throws On wrong argument types. {@link TypeError}
106
+ * @example
107
+ * Clone a byte array before mutating it.
108
+ * ```ts
109
+ * const copy = copyBytes(new Uint8Array([1, 2, 3]));
110
+ * ```
111
+ */
112
+ function copyBytes(bytes) {
113
+ // `Uint8Array.from(...)` would also accept arrays / other typed arrays. Keep this helper strict
114
+ // because callers use it at byte-validation boundaries before mutating the detached copy.
115
+ return Uint8Array.from(abytes(bytes));
116
+ }
117
+ /**
118
+ * Asserts something is a wrapped hash constructor.
119
+ * @param h - hash constructor to validate
120
+ * @throws On wrong argument types or invalid hash wrapper shape. {@link TypeError}
121
+ * @throws On invalid hash metadata ranges or values. {@link RangeError}
122
+ * @throws If the hash metadata allows empty outputs or block sizes. {@link Error}
123
+ * @example
124
+ * Validate a callable hash wrapper.
125
+ * ```ts
126
+ * import { ahash } from '@decryption/hashes/utils.js';
127
+ * import { sha256 } from '@decryption/hashes/sha2.js';
128
+ * ahash(sha256);
129
+ * ```
130
+ */
131
+ function ahash(h) {
132
+ if (typeof h !== 'function' || typeof h.create !== 'function')
133
+ throw new TypeError('Hash must wrapped by utils.createHasher');
134
+ anumber(h.outputLen);
135
+ anumber(h.blockLen);
136
+ // HMAC and KDF callers treat these as real byte lengths; allowing zero lets fake wrappers pass
137
+ // validation and can produce empty outputs instead of failing fast.
138
+ if (h.outputLen < 1)
139
+ throw new Error('"outputLen" must be >= 1');
140
+ if (h.blockLen < 1)
141
+ throw new Error('"blockLen" must be >= 1');
142
+ }
143
+ /**
144
+ * Asserts a hash instance has not been destroyed or finished.
145
+ * @param instance - hash instance to validate
146
+ * @param checkFinished - whether to reject finalized instances
147
+ * @throws If the hash instance has already been destroyed or finalized. {@link Error}
148
+ * @example
149
+ * Validate that a hash instance is still usable.
150
+ * ```ts
151
+ * import { aexists } from '@decryption/hashes/utils.js';
152
+ * import { sha256 } from '@decryption/hashes/sha2.js';
153
+ * const hash = sha256.create();
154
+ * aexists(hash);
155
+ * ```
156
+ */
157
+ function aexists(instance, checkFinished = true) {
158
+ if (instance.destroyed)
159
+ throw new Error('Hash instance has been destroyed');
160
+ if (checkFinished && instance.finished)
161
+ throw new Error('Hash#digest() has already been called');
162
+ }
163
+ /**
164
+ * Asserts output is a sufficiently-sized byte array.
165
+ * @param out - destination buffer
166
+ * @param instance - hash instance providing output length
167
+ * Oversized buffers are allowed; downstream code only promises to fill the first `outputLen` bytes.
168
+ * @throws On wrong argument types. {@link TypeError}
169
+ * @throws On wrong argument ranges or values. {@link RangeError}
170
+ * @example
171
+ * Validate a caller-provided digest buffer.
172
+ * ```ts
173
+ * import { aoutput } from '@decryption/hashes/utils.js';
174
+ * import { sha256 } from '@decryption/hashes/sha2.js';
175
+ * const hash = sha256.create();
176
+ * aoutput(new Uint8Array(hash.outputLen), hash);
177
+ * ```
178
+ */
179
+ function aoutput(out, instance) {
180
+ abytes(out, undefined, 'digestInto() output');
181
+ const min = instance.outputLen;
182
+ if (out.length < min) {
183
+ throw new RangeError('"digestInto() output" expected to be of length >=' + min);
184
+ }
185
+ }
186
+ /**
187
+ * Casts a typed array view to Uint8Array.
188
+ * @param arr - source typed array
189
+ * @returns Uint8Array view over the same buffer.
190
+ * @example
191
+ * Reinterpret a typed array as bytes.
192
+ * ```ts
193
+ * u8(new Uint32Array([1, 2]));
194
+ * ```
195
+ */
196
+ function u8(arr) {
197
+ return new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);
198
+ }
199
+ /**
200
+ * Casts a typed array view to Uint32Array.
201
+ * `arr.byteOffset` must already be 4-byte aligned or the platform
202
+ * Uint32Array constructor will throw.
203
+ * @param arr - source typed array
204
+ * @returns Uint32Array view over the same buffer.
205
+ * @example
206
+ * Reinterpret a byte array as 32-bit words.
207
+ * ```ts
208
+ * u32(new Uint8Array(8));
209
+ * ```
210
+ */
211
+ function u32(arr) {
212
+ return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));
213
+ }
214
+ /**
215
+ * Zeroizes typed arrays in place. Warning: JS provides no guarantees.
216
+ * @param arrays - arrays to overwrite with zeros
217
+ * @example
218
+ * Zeroize sensitive buffers in place.
219
+ * ```ts
220
+ * clean(new Uint8Array([1, 2, 3]));
221
+ * ```
222
+ */
223
+ function clean(...arrays) {
224
+ for (let i = 0; i < arrays.length; i++) {
225
+ arrays[i].fill(0);
226
+ }
227
+ }
228
+ /**
229
+ * Creates a DataView for byte-level manipulation.
230
+ * @param arr - source typed array
231
+ * @returns DataView over the same buffer region.
232
+ * @example
233
+ * Create a DataView over an existing buffer.
234
+ * ```ts
235
+ * createView(new Uint8Array(4));
236
+ * ```
237
+ */
238
+ function createView(arr) {
239
+ return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
240
+ }
241
+ /**
242
+ * Rotate-right operation for uint32 values.
243
+ * @param word - source word
244
+ * @param shift - shift amount in bits
245
+ * @returns Rotated word.
246
+ * @example
247
+ * Rotate a 32-bit word to the right.
248
+ * ```ts
249
+ * rotr(0x12345678, 8);
250
+ * ```
251
+ */
252
+ function rotr(word, shift) {
253
+ return (word << (32 - shift)) | (word >>> shift);
254
+ }
255
+ /**
256
+ * Rotate-left operation for uint32 values.
257
+ * @param word - source word
258
+ * @param shift - shift amount in bits
259
+ * @returns Rotated word.
260
+ * @example
261
+ * Rotate a 32-bit word to the left.
262
+ * ```ts
263
+ * rotl(0x12345678, 8);
264
+ * ```
265
+ */
266
+ function rotl(word, shift) {
267
+ return (word << shift) | ((word >>> (32 - shift)) >>> 0);
268
+ }
269
+ /** Whether the current platform is little-endian. */
270
+ exports.isLE = (() => new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44)();
271
+ /**
272
+ * Byte-swap operation for uint32 values.
273
+ * @param word - source word
274
+ * @returns Word with reversed byte order.
275
+ * @example
276
+ * Reverse the byte order of a 32-bit word.
277
+ * ```ts
278
+ * byteSwap(0x11223344);
279
+ * ```
280
+ */
281
+ function byteSwap(word) {
282
+ return (((word << 24) & 0xff000000) |
283
+ ((word << 8) & 0xff0000) |
284
+ ((word >>> 8) & 0xff00) |
285
+ ((word >>> 24) & 0xff));
286
+ }
287
+ /**
288
+ * Conditionally byte-swaps one 32-bit word on big-endian platforms.
289
+ * @param n - source word
290
+ * @returns Original or byte-swapped word depending on platform endianness.
291
+ * @example
292
+ * Normalize a 32-bit word for host endianness.
293
+ * ```ts
294
+ * swap8IfBE(0x11223344);
295
+ * ```
296
+ */
297
+ exports.swap8IfBE = exports.isLE
298
+ ? (n) => n
299
+ : (n) => byteSwap(n) >>> 0;
300
+ /**
301
+ * Byte-swaps every word of a Uint32Array in place.
302
+ * @param arr - array to mutate
303
+ * @returns The same array after mutation; callers pass live state arrays here.
304
+ * @example
305
+ * Reverse the byte order of every word in place.
306
+ * ```ts
307
+ * byteSwap32(new Uint32Array([0x11223344]));
308
+ * ```
309
+ */
310
+ function byteSwap32(arr) {
311
+ for (let i = 0; i < arr.length; i++) {
312
+ arr[i] = byteSwap(arr[i]);
313
+ }
314
+ return arr;
315
+ }
316
+ /**
317
+ * Conditionally byte-swaps a Uint32Array on big-endian platforms.
318
+ * @param u - array to normalize for host endianness
319
+ * @returns Original or byte-swapped array depending on platform endianness.
320
+ * On big-endian runtimes this mutates `u` in place via `byteSwap32(...)`.
321
+ * @example
322
+ * Normalize a word array for host endianness.
323
+ * ```ts
324
+ * swap32IfBE(new Uint32Array([0x11223344]));
325
+ * ```
326
+ */
327
+ exports.swap32IfBE = exports.isLE
328
+ ? (u) => u
329
+ : byteSwap32;
330
+ // Built-in hex conversion https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex
331
+ const hasHexBuiltin = /* @__PURE__ */ (() =>
332
+ // @ts-ignore
333
+ typeof Uint8Array.from([]).toHex === 'function' && typeof Uint8Array.fromHex === 'function')();
334
+ // Array where index 0xf0 (240) is mapped to string 'f0'
335
+ const hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0'));
336
+ /**
337
+ * Convert byte array to hex string.
338
+ * Uses the built-in function when available and assumes it matches the tested
339
+ * fallback semantics.
340
+ * @param bytes - bytes to encode
341
+ * @returns Lowercase hexadecimal string.
342
+ * @throws On wrong argument types. {@link TypeError}
343
+ * @example
344
+ * Convert bytes to lowercase hexadecimal.
345
+ * ```ts
346
+ * bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])); // 'cafe0123'
347
+ * ```
348
+ */
349
+ function bytesToHex(bytes) {
350
+ abytes(bytes);
351
+ // @ts-ignore
352
+ if (hasHexBuiltin)
353
+ return bytes.toHex();
354
+ // pre-caching improves the speed 6x
355
+ let hex = '';
356
+ for (let i = 0; i < bytes.length; i++) {
357
+ hex += hexes[bytes[i]];
358
+ }
359
+ return hex;
360
+ }
361
+ // We use optimized technique to convert hex string to byte array
362
+ const asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 };
363
+ function asciiToBase16(ch) {
364
+ if (ch >= asciis._0 && ch <= asciis._9)
365
+ return ch - asciis._0; // '2' => 50-48
366
+ if (ch >= asciis.A && ch <= asciis.F)
367
+ return ch - (asciis.A - 10); // 'B' => 66-(65-10)
368
+ if (ch >= asciis.a && ch <= asciis.f)
369
+ return ch - (asciis.a - 10); // 'b' => 98-(97-10)
370
+ return;
371
+ }
372
+ /**
373
+ * Convert hex string to byte array. Uses built-in function, when available.
374
+ * @param hex - hexadecimal string to decode
375
+ * @returns Decoded bytes.
376
+ * @throws On wrong argument types. {@link TypeError}
377
+ * @throws On wrong argument ranges or values. {@link RangeError}
378
+ * @example
379
+ * Decode lowercase hexadecimal into bytes.
380
+ * ```ts
381
+ * hexToBytes('cafe0123'); // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])
382
+ * ```
383
+ */
384
+ function hexToBytes(hex) {
385
+ if (typeof hex !== 'string')
386
+ throw new TypeError('hex string expected, got ' + typeof hex);
387
+ if (hasHexBuiltin) {
388
+ try {
389
+ return Uint8Array.fromHex(hex);
390
+ }
391
+ catch (error) {
392
+ if (error instanceof SyntaxError)
393
+ throw new RangeError(error.message);
394
+ throw error;
395
+ }
396
+ }
397
+ const hl = hex.length;
398
+ const al = hl / 2;
399
+ if (hl % 2)
400
+ throw new RangeError('hex string expected, got unpadded hex of length ' + hl);
401
+ const array = new Uint8Array(al);
402
+ for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {
403
+ const n1 = asciiToBase16(hex.charCodeAt(hi));
404
+ const n2 = asciiToBase16(hex.charCodeAt(hi + 1));
405
+ if (n1 === undefined || n2 === undefined) {
406
+ const char = hex[hi] + hex[hi + 1];
407
+ throw new RangeError('hex string expected, got non-hex character "' + char + '" at index ' + hi);
408
+ }
409
+ array[ai] = n1 * 16 + n2; // multiply first octet, e.g. 'a3' => 10*16+3 => 160 + 3 => 163
410
+ }
411
+ return array;
412
+ }
413
+ /**
414
+ * There is no setImmediate in browser and setTimeout is slow.
415
+ * This yields to the Promise/microtask scheduler queue, not to timers or the
416
+ * full macrotask event loop.
417
+ * @example
418
+ * Yield to the next scheduler tick.
419
+ * ```ts
420
+ * await nextTick();
421
+ * ```
422
+ */
423
+ const nextTick = async () => { };
424
+ exports.nextTick = nextTick;
425
+ /**
426
+ * Returns control to the Promise/microtask scheduler every `tick`
427
+ * milliseconds to avoid blocking long loops.
428
+ * @param iters - number of loop iterations to run
429
+ * @param tick - maximum time slice in milliseconds
430
+ * @param cb - callback executed on each iteration
431
+ * @example
432
+ * Run a loop that periodically yields back to the event loop.
433
+ * ```ts
434
+ * await asyncLoop(2, 0, () => {});
435
+ * ```
436
+ */
437
+ async function asyncLoop(iters, tick, cb) {
438
+ let ts = Date.now();
439
+ for (let i = 0; i < iters; i++) {
440
+ cb(i);
441
+ // Date.now() is not monotonic, so in case if clock goes backwards we return return control too
442
+ const diff = Date.now() - ts;
443
+ if (diff >= 0 && diff < tick)
444
+ continue;
445
+ await (0, exports.nextTick)();
446
+ ts += diff;
447
+ }
448
+ }
449
+ /**
450
+ * Converts string to bytes using UTF8 encoding.
451
+ * Built-in doesn't validate input to be string: we do the check.
452
+ * Non-ASCII details are delegated to the platform `TextEncoder`.
453
+ * @param str - string to encode
454
+ * @returns UTF-8 encoded bytes.
455
+ * @throws On wrong argument types. {@link TypeError}
456
+ * @example
457
+ * Encode a string as UTF-8 bytes.
458
+ * ```ts
459
+ * utf8ToBytes('abc'); // Uint8Array.from([97, 98, 99])
460
+ * ```
461
+ */
462
+ function utf8ToBytes(str) {
463
+ if (typeof str !== 'string')
464
+ throw new TypeError('string expected');
465
+ return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809
466
+ }
467
+ /**
468
+ * Helper for KDFs: consumes Uint8Array or string.
469
+ * String inputs are UTF-8 encoded; byte-array inputs stay aliased to the caller buffer.
470
+ * @param data - user-provided KDF input
471
+ * @param errorTitle - label included in thrown errors
472
+ * @returns Byte representation of the input.
473
+ * @throws On wrong argument types. {@link TypeError}
474
+ * @example
475
+ * Normalize KDF input to bytes.
476
+ * ```ts
477
+ * kdfInputToBytes('password');
478
+ * ```
479
+ */
480
+ function kdfInputToBytes(data, errorTitle = '') {
481
+ if (typeof data === 'string')
482
+ return utf8ToBytes(data);
483
+ return abytes(data, undefined, errorTitle);
484
+ }
485
+ /**
486
+ * Copies several Uint8Arrays into one.
487
+ * @param arrays - arrays to concatenate
488
+ * @returns Concatenated byte array.
489
+ * @throws On wrong argument types. {@link TypeError}
490
+ * @example
491
+ * Concatenate multiple byte arrays.
492
+ * ```ts
493
+ * concatBytes(new Uint8Array([1]), new Uint8Array([2]));
494
+ * ```
495
+ */
496
+ function concatBytes(...arrays) {
497
+ let sum = 0;
498
+ for (let i = 0; i < arrays.length; i++) {
499
+ const a = arrays[i];
500
+ abytes(a);
501
+ sum += a.length;
502
+ }
503
+ const res = new Uint8Array(sum);
504
+ for (let i = 0, pad = 0; i < arrays.length; i++) {
505
+ const a = arrays[i];
506
+ res.set(a, pad);
507
+ pad += a.length;
508
+ }
509
+ return res;
510
+ }
511
+ /**
512
+ * Merges default options and passed options.
513
+ * @param defaults - base option object
514
+ * @param opts - user overrides
515
+ * @returns Merged option object. The merge mutates `defaults` in place.
516
+ * @throws On wrong argument types. {@link TypeError}
517
+ * @example
518
+ * Merge user overrides onto default options.
519
+ * ```ts
520
+ * checkOpts({ dkLen: 32 }, { asyncTick: 10 });
521
+ * ```
522
+ */
523
+ function checkOpts(defaults, opts) {
524
+ if (opts !== undefined && {}.toString.call(opts) !== '[object Object]')
525
+ throw new TypeError('options must be object or undefined');
526
+ const merged = Object.assign(defaults, opts);
527
+ return merged;
528
+ }
529
+ /**
530
+ * Creates a callable hash function from a stateful class constructor.
531
+ * @param hashCons - hash constructor or factory
532
+ * @param info - optional metadata such as DER OID
533
+ * @returns Frozen callable hash wrapper with `.create()`.
534
+ * Wrapper construction eagerly calls `hashCons(undefined)` once to read
535
+ * `outputLen` / `blockLen`, so constructor side effects happen at module
536
+ * init time.
537
+ * @example
538
+ * Wrap a stateful hash constructor into a callable helper.
539
+ * ```ts
540
+ * import { createHasher } from '@decryption/hashes/utils.js';
541
+ * import { sha256 } from '@decryption/hashes/sha2.js';
542
+ * const wrapped = createHasher(sha256.create, { oid: sha256.oid });
543
+ * wrapped(new Uint8Array([1]));
544
+ * ```
545
+ */
546
+ function createHasher(hashCons, info = {}) {
547
+ const hashC = (msg, opts) => hashCons(opts)
548
+ .update(msg)
549
+ .digest();
550
+ const tmp = hashCons(undefined);
551
+ hashC.outputLen = tmp.outputLen;
552
+ hashC.blockLen = tmp.blockLen;
553
+ hashC.canXOF = tmp.canXOF;
554
+ hashC.create = (opts) => hashCons(opts);
555
+ Object.assign(hashC, info);
556
+ return Object.freeze(hashC);
557
+ }
558
+ /**
559
+ * Cryptographically secure PRNG backed by `crypto.getRandomValues`.
560
+ * @param bytesLength - number of random bytes to generate
561
+ * @returns Random bytes.
562
+ * The platform `getRandomValues()` implementation still defines any
563
+ * single-call length cap, and this helper rejects oversize requests
564
+ * with a stable library `RangeError` instead of host-specific errors.
565
+ * @throws On wrong argument types. {@link TypeError}
566
+ * @throws On wrong argument ranges or values. {@link RangeError}
567
+ * @throws If the current runtime does not provide `crypto.getRandomValues`. {@link Error}
568
+ * @example
569
+ * Generate a fresh random key or nonce.
570
+ * ```ts
571
+ * const key = randomBytes(16);
572
+ * ```
573
+ */
574
+ function randomBytes(bytesLength = 32) {
575
+ // Match the repo's other length-taking helpers instead of relying on Uint8Array coercion.
576
+ anumber(bytesLength, 'bytesLength');
577
+ const cr = typeof globalThis === 'object' ? globalThis.crypto : null;
578
+ if (typeof cr?.getRandomValues !== 'function')
579
+ throw new Error('crypto.getRandomValues must be defined');
580
+ // Web Cryptography API Level 2 §10.1.1:
581
+ // if `byteLength > 65536`, throw `QuotaExceededError`.
582
+ // Keep the guard explicit so callers can see the quota in code
583
+ // instead of discovering it by reading the spec or host errors.
584
+ // This wrapper surfaces the same quota as a stable library RangeError.
585
+ if (bytesLength > 65536)
586
+ throw new RangeError(`"bytesLength" expected <= 65536, got ${bytesLength}`);
587
+ return cr.getRandomValues(new Uint8Array(bytesLength));
588
+ }
589
+ /**
590
+ * Creates OID metadata for NIST hashes with prefix `06 09 60 86 48 01 65 03 04 02`.
591
+ * @param suffix - final OID byte for the selected hash.
592
+ * The helper accepts any byte even though only the documented NIST hash
593
+ * suffixes are meaningful downstream.
594
+ * @returns Object containing the DER-encoded OID.
595
+ * @example
596
+ * Build OID metadata for a NIST hash.
597
+ * ```ts
598
+ * oidNist(0x01);
599
+ * ```
600
+ */
601
+ const oidNist = (suffix) => ({
602
+ // Current NIST hashAlgs suffixes used here fit in one DER subidentifier octet.
603
+ // Larger suffix values would need base-128 OID encoding and a different length byte.
604
+ oid: Uint8Array.from([0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, suffix]),
605
+ });
606
+ exports.oidNist = oidNist;