@decryption/ciphers 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.
package/utils.js ADDED
@@ -0,0 +1,841 @@
1
+ "use strict";
2
+ /**
3
+ * Utilities for hex, bytes, CSPRNG.
4
+ * @module
5
+ */
6
+ /*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */
7
+ Object.defineProperty(exports, "__esModule", { value: true });
8
+ exports.wrapCipher = exports.swap32IfBE = exports.byteSwap32 = exports.swap8IfBE = exports.byteSwap = exports.isLE = void 0;
9
+ exports.isBytes = isBytes;
10
+ exports.abool = abool;
11
+ exports.anumber = anumber;
12
+ exports.abytes = abytes;
13
+ exports.aexists = aexists;
14
+ exports.aoutput = aoutput;
15
+ exports.u8 = u8;
16
+ exports.u32 = u32;
17
+ exports.clean = clean;
18
+ exports.createView = createView;
19
+ exports.bytesToHex = bytesToHex;
20
+ exports.hexToBytes = hexToBytes;
21
+ exports.hexToNumber = hexToNumber;
22
+ exports.bytesToNumberBE = bytesToNumberBE;
23
+ exports.numberToBytesBE = numberToBytesBE;
24
+ exports.utf8ToBytes = utf8ToBytes;
25
+ exports.bytesToUtf8 = bytesToUtf8;
26
+ exports.overlapBytes = overlapBytes;
27
+ exports.complexOverlapBytes = complexOverlapBytes;
28
+ exports.concatBytes = concatBytes;
29
+ exports.checkOpts = checkOpts;
30
+ exports.equalBytes = equalBytes;
31
+ exports.wrapMacConstructor = wrapMacConstructor;
32
+ exports.getOutput = getOutput;
33
+ exports.u64Lengths = u64Lengths;
34
+ exports.isAligned32 = isAligned32;
35
+ exports.copyBytes = copyBytes;
36
+ exports.randomBytes = randomBytes;
37
+ exports.managedNonce = managedNonce;
38
+ /**
39
+ * Checks if something is Uint8Array. Be careful: nodejs Buffer will return true.
40
+ * @param a - Value to inspect.
41
+ * @returns `true` when the value is a Uint8Array view, including Node's `Buffer`.
42
+ * @example
43
+ * Guards a value before treating it as raw key material.
44
+ *
45
+ * ```ts
46
+ * isBytes(new Uint8Array());
47
+ * ```
48
+ */
49
+ function isBytes(a) {
50
+ // Plain `instanceof Uint8Array` is too strict for some Buffer / proxy /
51
+ // cross-realm cases. The fallback still requires a real ArrayBuffer view
52
+ // so plain JSON-deserialized `{ constructor: ... }`
53
+ // spoofing is rejected, and `BYTES_PER_ELEMENT === 1` keeps the fallback on byte-oriented views.
54
+ return (a instanceof Uint8Array ||
55
+ (ArrayBuffer.isView(a) &&
56
+ a.constructor.name === 'Uint8Array' &&
57
+ 'BYTES_PER_ELEMENT' in a &&
58
+ a.BYTES_PER_ELEMENT === 1));
59
+ }
60
+ /**
61
+ * Asserts something is boolean.
62
+ * @param b - Value to validate.
63
+ * @throws On wrong argument types. {@link TypeError}
64
+ * @example
65
+ * Validates a boolean option before branching on it.
66
+ *
67
+ * ```ts
68
+ * abool(true);
69
+ * ```
70
+ */
71
+ function abool(b) {
72
+ if (typeof b !== 'boolean')
73
+ throw new TypeError(`boolean expected, not ${b}`);
74
+ }
75
+ /**
76
+ * Asserts something is a non-negative safe integer.
77
+ * @param n - Value to validate.
78
+ * @throws On wrong argument types. {@link TypeError}
79
+ * @throws On wrong argument ranges or values. {@link RangeError}
80
+ * @example
81
+ * Validates a non-negative length or counter.
82
+ *
83
+ * ```ts
84
+ * anumber(1);
85
+ * ```
86
+ */
87
+ function anumber(n) {
88
+ if (typeof n !== 'number')
89
+ throw new TypeError('number expected, got ' + typeof n);
90
+ if (!Number.isSafeInteger(n) || n < 0)
91
+ throw new RangeError('positive integer expected, got ' + n);
92
+ }
93
+ /**
94
+ * Asserts something is Uint8Array.
95
+ * @param value - Value to validate.
96
+ * @param length - Expected byte length.
97
+ * @param title - Optional label used in error messages.
98
+ * @returns The validated byte array.
99
+ * On Node, `Buffer` is accepted too because it is a Uint8Array view.
100
+ * @throws On wrong argument types. {@link TypeError}
101
+ * @throws On wrong argument lengths. {@link RangeError}
102
+ * @example
103
+ * Validates a fixed-length nonce or key buffer.
104
+ *
105
+ * ```ts
106
+ * abytes(new Uint8Array([1, 2]), 2);
107
+ * ```
108
+ */
109
+ function abytes(value, length, title = '') {
110
+ const bytes = isBytes(value);
111
+ const len = value?.length;
112
+ const needsLen = length !== undefined;
113
+ if (!bytes || (needsLen && len !== length)) {
114
+ const prefix = title && `"${title}" `;
115
+ const ofLen = needsLen ? ` of length ${length}` : '';
116
+ const got = bytes ? `length=${len}` : `type=${typeof value}`;
117
+ const message = prefix + 'expected Uint8Array' + ofLen + ', got ' + got;
118
+ if (!bytes)
119
+ throw new TypeError(message);
120
+ throw new RangeError(message);
121
+ }
122
+ return value;
123
+ }
124
+ /**
125
+ * Asserts a hash- or MAC-like instance has not been destroyed or finished.
126
+ * @param instance - Stateful instance to validate.
127
+ * @param checkFinished - Whether to reject finished instances.
128
+ * When `false`, only `destroyed` is checked.
129
+ * @throws If the hash instance has already been destroyed or finalized. {@link Error}
130
+ * @example
131
+ * Guards against calling `update()` or `digest()` on a finished hash.
132
+ *
133
+ * ```ts
134
+ * aexists({ destroyed: false, finished: false });
135
+ * ```
136
+ */
137
+ function aexists(instance, checkFinished = true) {
138
+ if (instance.destroyed)
139
+ throw new Error('Hash instance has been destroyed');
140
+ if (checkFinished && instance.finished)
141
+ throw new Error('Hash#digest() has already been called');
142
+ }
143
+ /**
144
+ * Asserts output is a properly-sized byte array.
145
+ * @param out - Output buffer to validate.
146
+ * @param instance - Hash-like instance providing `outputLen`.
147
+ * This is the relaxed `digestInto()`-style contract: output must be at least `outputLen`,
148
+ * unlike one-shot cipher helpers elsewhere in the repo that often require exact lengths.
149
+ * @throws On wrong argument types. {@link TypeError}
150
+ * @param onlyAligned - Whether `out` must be 4-byte aligned for zero-allocation word views.
151
+ * @throws On wrong output buffer lengths. {@link RangeError}
152
+ * @throws On wrong output buffer alignment. {@link Error}
153
+ * @example
154
+ * Verifies that a caller-provided output buffer is large enough.
155
+ *
156
+ * ```ts
157
+ * aoutput(new Uint8Array(16), { outputLen: 16 });
158
+ * ```
159
+ */
160
+ function aoutput(out, instance, onlyAligned = false) {
161
+ abytes(out, undefined, 'output');
162
+ const min = instance.outputLen;
163
+ if (out.length < min) {
164
+ throw new RangeError('digestInto() expects output buffer of length at least ' + min);
165
+ }
166
+ if (onlyAligned && !isAligned32(out))
167
+ throw new Error('invalid output, must be aligned');
168
+ }
169
+ /**
170
+ * Casts a typed-array view to Uint8Array.
171
+ * @param arr - Typed-array view to reinterpret.
172
+ * @returns Uint8Array view over the same bytes.
173
+ * @example
174
+ * Views 32-bit words as raw bytes without copying.
175
+ *
176
+ * ```ts
177
+ * u8(new Uint32Array([1]));
178
+ * ```
179
+ */
180
+ function u8(arr) {
181
+ return new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);
182
+ }
183
+ /**
184
+ * Casts a typed-array view to Uint32Array.
185
+ * @param arr - Typed-array view to reinterpret.
186
+ * @returns Uint32Array view over the same bytes. Callers are expected to provide a
187
+ * 4-byte-aligned offset; trailing `1..3` bytes are silently dropped.
188
+ * @example
189
+ * Views a byte buffer as 32-bit words for block processing.
190
+ *
191
+ * ```ts
192
+ * u32(new Uint8Array(4));
193
+ * ```
194
+ */
195
+ function u32(arr) {
196
+ return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));
197
+ }
198
+ /**
199
+ * Zeroizes typed arrays in place.
200
+ * Warning: JS provides no guarantees.
201
+ * @param arrays - Arrays to wipe.
202
+ * @example
203
+ * Wipes a temporary key buffer after use.
204
+ *
205
+ * ```ts
206
+ * const bytes = new Uint8Array([1]);
207
+ * clean(bytes);
208
+ * ```
209
+ */
210
+ function clean(...arrays) {
211
+ for (let i = 0; i < arrays.length; i++) {
212
+ arrays[i].fill(0);
213
+ }
214
+ }
215
+ /**
216
+ * Creates a DataView for byte-level manipulation.
217
+ * @param arr - Typed-array view to wrap.
218
+ * @returns DataView over the same bytes.
219
+ * @example
220
+ * Creates an endian-aware view for length encoding.
221
+ *
222
+ * ```ts
223
+ * createView(new Uint8Array(4));
224
+ * ```
225
+ */
226
+ function createView(arr) {
227
+ return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
228
+ }
229
+ /**
230
+ * Whether the current platform is little-endian.
231
+ * Most are; some IBM systems are not.
232
+ */
233
+ exports.isLE = (() => new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44)();
234
+ /**
235
+ * Reverses byte order of one 32-bit word.
236
+ * @param word - Unsigned 32-bit word to swap.
237
+ * @returns The same word with bytes reversed.
238
+ * @example
239
+ * Swaps a big-endian word into little-endian byte order.
240
+ *
241
+ * ```ts
242
+ * byteSwap(0x11223344);
243
+ * ```
244
+ */
245
+ const byteSwap = (word) => ((word << 24) & 0xff000000) |
246
+ ((word << 8) & 0xff0000) |
247
+ ((word >>> 8) & 0xff00) |
248
+ ((word >>> 24) & 0xff);
249
+ exports.byteSwap = byteSwap;
250
+ /**
251
+ * Normalizes one 32-bit word to the little-endian representation expected by cipher cores.
252
+ * @param n - Unsigned 32-bit word to normalize.
253
+ * @returns Little-endian normalized word on big-endian hosts, else the input word unchanged.
254
+ * @example
255
+ * Normalizes a host-endian word before passing it into an ARX/AES core.
256
+ *
257
+ * ```ts
258
+ * swap8IfBE(0x11223344);
259
+ * ```
260
+ */
261
+ exports.swap8IfBE = exports.isLE
262
+ ? (n) => n
263
+ : (n) => (0, exports.byteSwap)(n) >>> 0;
264
+ /**
265
+ * Byte-swaps every word of a Uint32Array in place.
266
+ * @param arr - Uint32Array whose words should be swapped.
267
+ * @returns The same array after in-place byte swapping.
268
+ * @example
269
+ * Swaps every 32-bit word in a word-view buffer.
270
+ *
271
+ * ```ts
272
+ * byteSwap32(new Uint32Array([0x11223344]));
273
+ * ```
274
+ */
275
+ const byteSwap32 = (arr) => {
276
+ for (let i = 0; i < arr.length; i++)
277
+ arr[i] = (0, exports.byteSwap)(arr[i]);
278
+ return arr;
279
+ };
280
+ exports.byteSwap32 = byteSwap32;
281
+ /**
282
+ * Normalizes a Uint32Array view to the little-endian representation expected by cipher cores.
283
+ * @param u - Word view to normalize in place.
284
+ * @returns Little-endian normalized word view.
285
+ * @example
286
+ * Normalizes a word-view buffer before block processing.
287
+ *
288
+ * ```ts
289
+ * swap32IfBE(new Uint32Array([0x11223344]));
290
+ * ```
291
+ */
292
+ exports.swap32IfBE = exports.isLE
293
+ ? (u) => u
294
+ : exports.byteSwap32;
295
+ // Built-in hex conversion:
296
+ // {@link https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex | caniuse entry}
297
+ const hasHexBuiltin = /* @__PURE__ */ (() =>
298
+ // @ts-ignore
299
+ typeof Uint8Array.from([]).toHex === 'function' && typeof Uint8Array.fromHex === 'function')();
300
+ // Array where index 0xf0 (240) is mapped to string 'f0'
301
+ const hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0'));
302
+ /**
303
+ * Convert byte array to hex string. Uses built-in function, when available.
304
+ * @param bytes - Bytes to encode.
305
+ * @returns Lowercase hexadecimal string.
306
+ * @throws On wrong argument types. {@link TypeError}
307
+ * @example
308
+ * Formats ciphertext bytes for logs or test vectors.
309
+ *
310
+ * ```ts
311
+ * bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])); // 'cafe0123'
312
+ * ```
313
+ */
314
+ function bytesToHex(bytes) {
315
+ abytes(bytes);
316
+ // @ts-ignore
317
+ if (hasHexBuiltin)
318
+ return bytes.toHex();
319
+ // pre-caching improves the speed 6x
320
+ let hex = '';
321
+ for (let i = 0; i < bytes.length; i++) {
322
+ hex += hexes[bytes[i]];
323
+ }
324
+ return hex;
325
+ }
326
+ // We use optimized technique to convert hex string to byte array
327
+ const asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 };
328
+ function asciiToBase16(ch) {
329
+ if (ch >= asciis._0 && ch <= asciis._9)
330
+ return ch - asciis._0; // '2' => 50-48
331
+ if (ch >= asciis.A && ch <= asciis.F)
332
+ return ch - (asciis.A - 10); // 'B' => 66-(65-10)
333
+ if (ch >= asciis.a && ch <= asciis.f)
334
+ return ch - (asciis.a - 10); // 'b' => 98-(97-10)
335
+ return;
336
+ }
337
+ /**
338
+ * Convert hex string to byte array. Uses built-in function, when available.
339
+ * @param hex - Hexadecimal string to decode.
340
+ * @returns Decoded bytes.
341
+ * @throws On wrong argument types. {@link TypeError}
342
+ * @throws On malformed hexadecimal input. {@link RangeError}
343
+ * @example
344
+ * Parses a hex test vector into bytes.
345
+ *
346
+ * ```ts
347
+ * hexToBytes('cafe0123'); // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])
348
+ * ```
349
+ */
350
+ function hexToBytes(hex) {
351
+ if (typeof hex !== 'string')
352
+ throw new TypeError('hex string expected, got ' + typeof hex);
353
+ if (hasHexBuiltin) {
354
+ try {
355
+ return Uint8Array.fromHex(hex);
356
+ }
357
+ catch (error) {
358
+ if (error instanceof SyntaxError)
359
+ throw new RangeError(error.message);
360
+ throw error;
361
+ }
362
+ }
363
+ const hl = hex.length;
364
+ const al = hl / 2;
365
+ if (hl % 2)
366
+ throw new RangeError('hex string expected, got unpadded hex of length ' + hl);
367
+ const array = new Uint8Array(al);
368
+ for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {
369
+ const n1 = asciiToBase16(hex.charCodeAt(hi));
370
+ const n2 = asciiToBase16(hex.charCodeAt(hi + 1));
371
+ if (n1 === undefined || n2 === undefined) {
372
+ const char = hex[hi] + hex[hi + 1];
373
+ throw new RangeError('hex string expected, got non-hex character "' + char + '" at index ' + hi);
374
+ }
375
+ array[ai] = n1 * 16 + n2; // multiply first octet, e.g. 'a3' => 10*16+3 => 160 + 3 => 163
376
+ }
377
+ return array;
378
+ }
379
+ // Used in micro
380
+ /**
381
+ * Converts a big-endian hex string into bigint.
382
+ * @param hex - Hexadecimal string without `0x`.
383
+ * @returns Parsed bigint value. The empty string is treated as `0n`.
384
+ * @throws On wrong argument types. {@link TypeError}
385
+ * @example
386
+ * Parses a big-endian field element or counter from hex.
387
+ *
388
+ * ```ts
389
+ * hexToNumber('ff');
390
+ * ```
391
+ */
392
+ function hexToNumber(hex) {
393
+ if (typeof hex !== 'string')
394
+ throw new TypeError('hex string expected, got ' + typeof hex);
395
+ return BigInt(hex === '' ? '0' : '0x' + hex); // Big Endian
396
+ }
397
+ // Used in ff1
398
+ // BE: Big Endian, LE: Little Endian
399
+ /**
400
+ * Converts big-endian bytes into bigint.
401
+ * @param bytes - Big-endian bytes.
402
+ * @returns Parsed bigint value. Empty input is treated as `0n`.
403
+ * @throws On invalid byte input passed to the internal hex conversion. {@link TypeError}
404
+ * @example
405
+ * Reads a big-endian integer from serialized bytes.
406
+ *
407
+ * ```ts
408
+ * bytesToNumberBE(new Uint8Array([1, 0]));
409
+ * ```
410
+ */
411
+ function bytesToNumberBE(bytes) {
412
+ return hexToNumber(bytesToHex(bytes));
413
+ }
414
+ // Used in micro, ff1
415
+ /**
416
+ * Converts a number into big-endian bytes of fixed length.
417
+ * @param n - Number to encode.
418
+ * @param len - Output length in bytes.
419
+ * @returns Big-endian bytes padded to `len`.
420
+ * Validation is indirect through `hexToBytes(...)`, so negative values, `len = 0`,
421
+ * and values that do not fit surface through the downstream hex parser instead of a
422
+ * dedicated range guard here.
423
+ * @throws On wrong argument types. {@link TypeError}
424
+ * @throws If the requested output length cannot represent the encoded value. {@link RangeError}
425
+ * @example
426
+ * Encodes a counter as fixed-width big-endian bytes.
427
+ *
428
+ * ```ts
429
+ * numberToBytesBE(1, 2);
430
+ * ```
431
+ */
432
+ function numberToBytesBE(n, len) {
433
+ // Reject coercible non-numeric inputs before string/hex conversion changes behavior.
434
+ if (typeof n === 'number')
435
+ anumber(n);
436
+ else if (typeof n !== 'bigint')
437
+ throw new TypeError(`number or bigint expected, got ${typeof n}`);
438
+ anumber(len);
439
+ return hexToBytes(n.toString(16).padStart(len * 2, '0'));
440
+ }
441
+ /**
442
+ * Converts string to bytes using UTF8 encoding.
443
+ * @param str - String to encode.
444
+ * @returns UTF-8 bytes in a detached fresh Uint8Array copy.
445
+ * @throws On wrong argument types. {@link TypeError}
446
+ * @example
447
+ * Encodes application text before encryption or MACing.
448
+ *
449
+ * ```ts
450
+ * utf8ToBytes('abc'); // new Uint8Array([97, 98, 99])
451
+ * ```
452
+ */
453
+ function utf8ToBytes(str) {
454
+ if (typeof str !== 'string')
455
+ throw new TypeError('string expected');
456
+ return new Uint8Array(new TextEncoder().encode(str)); // {@link https://bugzil.la/1681809 | Firefox bug 1681809}
457
+ }
458
+ /**
459
+ * Converts bytes to string using UTF8 encoding.
460
+ * @param bytes - UTF-8 bytes.
461
+ * @returns Decoded string. Input validation is delegated to `TextDecoder`, and malformed
462
+ * UTF-8 is replacement-decoded instead of rejected.
463
+ * @example
464
+ * Decodes UTF-8 plaintext back into a string.
465
+ *
466
+ * ```ts
467
+ * bytesToUtf8(new Uint8Array([97, 98, 99])); // 'abc'
468
+ * ```
469
+ */
470
+ function bytesToUtf8(bytes) {
471
+ return new TextDecoder().decode(bytes);
472
+ }
473
+ /**
474
+ * Checks if two U8A use same underlying buffer and overlaps.
475
+ * This is invalid and can corrupt data.
476
+ * @param a - First byte view.
477
+ * @param b - Second byte view.
478
+ * @returns `true` when the views overlap in memory.
479
+ * @example
480
+ * Detects whether two slices alias the same backing buffer.
481
+ *
482
+ * ```ts
483
+ * overlapBytes(new Uint8Array(4), new Uint8Array(4));
484
+ * ```
485
+ */
486
+ function overlapBytes(a, b) {
487
+ // Zero-length views cannot overwrite anything, even if their offset sits inside another range.
488
+ if (!a.byteLength || !b.byteLength)
489
+ return false;
490
+ return (a.buffer === b.buffer && // best we can do, may fail with an obscure Proxy
491
+ a.byteOffset < b.byteOffset + b.byteLength && // a starts before b end
492
+ b.byteOffset < a.byteOffset + a.byteLength // b starts before a end
493
+ );
494
+ }
495
+ /**
496
+ * If input and output overlap and input starts before output, we will overwrite end of input before
497
+ * we start processing it, so this is not supported for most ciphers
498
+ * (except chacha/salsa, which were designed for this)
499
+ * @param input - Input bytes.
500
+ * @param output - Output bytes.
501
+ * @throws If the output view would overwrite unread input bytes. {@link Error}
502
+ * @example
503
+ * Rejects an in-place layout that would overwrite unread input bytes.
504
+ *
505
+ * ```ts
506
+ * complexOverlapBytes(new Uint8Array(4), new Uint8Array(4));
507
+ * ```
508
+ */
509
+ function complexOverlapBytes(input, output) {
510
+ // This is very cursed. It works somehow, but I'm completely unsure,
511
+ // reasoning about overlapping aligned windows is very hard.
512
+ if (overlapBytes(input, output) && input.byteOffset < output.byteOffset)
513
+ throw new Error('complex overlap of input and output is not supported');
514
+ }
515
+ /**
516
+ * Copies several Uint8Arrays into one.
517
+ * @param arrays - Byte arrays to concatenate.
518
+ * @returns Combined byte array.
519
+ * @throws On wrong argument types inside the byte-array list. {@link TypeError}
520
+ * @example
521
+ * Builds a `nonce || ciphertext` style buffer.
522
+ *
523
+ * ```ts
524
+ * concatBytes(new Uint8Array([1]), new Uint8Array([2]));
525
+ * ```
526
+ */
527
+ function concatBytes(...arrays) {
528
+ let sum = 0;
529
+ for (let i = 0; i < arrays.length; i++) {
530
+ const a = arrays[i];
531
+ abytes(a);
532
+ sum += a.length;
533
+ }
534
+ const res = new Uint8Array(sum);
535
+ for (let i = 0, pad = 0; i < arrays.length; i++) {
536
+ const a = arrays[i];
537
+ res.set(a, pad);
538
+ pad += a.length;
539
+ }
540
+ return res;
541
+ }
542
+ /**
543
+ * Merges user options into defaults.
544
+ * @param defaults - Default option values.
545
+ * @param opts - User-provided overrides.
546
+ * @returns Combined options object.
547
+ * The merge mutates `defaults` in place and returns the same object.
548
+ * @throws If options are missing or not an object. {@link Error}
549
+ * @example
550
+ * Applies user overrides to the default cipher options.
551
+ *
552
+ * ```ts
553
+ * checkOpts({ rounds: 20 }, { rounds: 8 });
554
+ * ```
555
+ */
556
+ function checkOpts(defaults, opts) {
557
+ if (opts == null || typeof opts !== 'object')
558
+ throw new Error('options must be defined');
559
+ const merged = Object.assign(defaults, opts);
560
+ return merged;
561
+ }
562
+ /**
563
+ * Compares two byte arrays in kinda constant time once lengths already match.
564
+ * @param a - First byte array.
565
+ * @param b - Second byte array.
566
+ * @returns `true` when the arrays contain the same bytes. Different lengths still return early.
567
+ * @example
568
+ * Compares an expected authentication tag with the received one.
569
+ *
570
+ * ```ts
571
+ * equalBytes(new Uint8Array([1]), new Uint8Array([1]));
572
+ * ```
573
+ */
574
+ function equalBytes(a, b) {
575
+ if (a.length !== b.length)
576
+ return false;
577
+ let diff = 0;
578
+ for (let i = 0; i < a.length; i++)
579
+ diff |= a[i] ^ b[i];
580
+ return diff === 0;
581
+ }
582
+ /**
583
+ * Wraps a keyed MAC constructor into a one-shot helper with `.create()`.
584
+ * @param keyLen - Valid probe-key length used to read static metadata once.
585
+ * The probe key is only used for `outputLen` / `blockLen`, so callers with several valid key sizes
586
+ * can pass any representative size as long as those values stay fixed.
587
+ * @param macCons - Keyed MAC constructor or factory.
588
+ * @param fromMsg - Optional adapter that derives extra constructor args from the one-shot message.
589
+ * @returns Callable MAC helper with `.create()`.
590
+ */
591
+ function wrapMacConstructor(keyLen, macCons, fromMsg) {
592
+ const mac = macCons;
593
+ const getArgs = (fromMsg || (() => []));
594
+ const macC = (msg, key) => mac(key, ...getArgs(msg))
595
+ .update(msg)
596
+ .digest();
597
+ const tmp = mac(new Uint8Array(keyLen), ...getArgs(new Uint8Array(0)));
598
+ macC.outputLen = tmp.outputLen;
599
+ macC.blockLen = tmp.blockLen;
600
+ macC.create = (key, ...args) => mac(key, ...args);
601
+ return macC;
602
+ }
603
+ /**
604
+ * Wraps a cipher: validates args, ensures encrypt() can only be called once.
605
+ * Used internally by the exported cipher constructors.
606
+ * Output-buffer support is inferred from the wrapped `encrypt` / `decrypt`
607
+ * arity (`fn.length === 2`), and tag-bearing constructors are expected to use
608
+ * `args[1]` for optional AAD.
609
+ * @__NO_SIDE_EFFECTS__
610
+ * @param params - Static cipher metadata. See {@link CipherParams}.
611
+ * @param constructor - Cipher constructor.
612
+ * @returns Wrapped constructor with validation.
613
+ */
614
+ const wrapCipher = (params, constructor) => {
615
+ function wrappedCipher(key, ...args) {
616
+ // Validate key
617
+ abytes(key, undefined, 'key');
618
+ // Validate nonce if nonceLength is present
619
+ if (params.nonceLength !== undefined) {
620
+ const nonce = args[0];
621
+ abytes(nonce, params.varSizeNonce ? undefined : params.nonceLength, 'nonce');
622
+ }
623
+ // Validate AAD if tagLength present
624
+ const tagl = params.tagLength;
625
+ if (tagl && args[1] !== undefined)
626
+ abytes(args[1], undefined, 'AAD');
627
+ const cipher = constructor(key, ...args);
628
+ const checkOutput = (fnLength, output) => {
629
+ if (output !== undefined) {
630
+ if (fnLength !== 2)
631
+ throw new Error('cipher output not supported');
632
+ abytes(output, undefined, 'output');
633
+ }
634
+ };
635
+ // Create wrapped cipher with validation and single-use encryption
636
+ let called = false;
637
+ const wrCipher = {
638
+ encrypt(data, output) {
639
+ if (called)
640
+ throw new Error('cannot encrypt() twice with same key + nonce');
641
+ called = true;
642
+ abytes(data);
643
+ checkOutput(cipher.encrypt.length, output);
644
+ return cipher.encrypt(data, output);
645
+ },
646
+ decrypt(data, output) {
647
+ abytes(data);
648
+ if (tagl && data.length < tagl)
649
+ throw new Error('"ciphertext" expected length bigger than tagLength=' + tagl);
650
+ checkOutput(cipher.decrypt.length, output);
651
+ return cipher.decrypt(data, output);
652
+ },
653
+ };
654
+ return wrCipher;
655
+ }
656
+ Object.assign(wrappedCipher, params);
657
+ return wrappedCipher;
658
+ };
659
+ exports.wrapCipher = wrapCipher;
660
+ /**
661
+ * By default, returns u8a of length.
662
+ * When out is available, it checks it for validity and uses it.
663
+ * @param expectedLength - Required output length.
664
+ * @param out - Optional destination buffer.
665
+ * @param onlyAligned - Whether `out` must be 4-byte aligned.
666
+ * @returns Output buffer ready for writing.
667
+ * @throws On wrong argument types. {@link TypeError}
668
+ * @throws If the provided output buffer has the wrong size or alignment. {@link Error}
669
+ * @example
670
+ * Reuses a caller-provided output buffer when lengths match.
671
+ *
672
+ * ```ts
673
+ * getOutput(16, new Uint8Array(16));
674
+ * ```
675
+ */
676
+ function getOutput(expectedLength, out, onlyAligned = true) {
677
+ if (out === undefined)
678
+ return new Uint8Array(expectedLength);
679
+ // Keep Buffer/cross-realm Uint8Array support here instead of trusting a shape-compatible object.
680
+ abytes(out, undefined, 'output');
681
+ if (out.length !== expectedLength)
682
+ throw new Error('"output" expected Uint8Array of length ' + expectedLength + ', got: ' + out.length);
683
+ if (onlyAligned && !isAligned32(out))
684
+ throw new Error('invalid output, must be aligned');
685
+ return out;
686
+ }
687
+ /**
688
+ * Encodes data and AAD bit lengths into a 16-byte buffer.
689
+ * @param dataLength - Data length in bits.
690
+ * @param aadLength - AAD length in bits.
691
+ * The serialized block is still `aadLength || dataLength`, matching GCM/Poly1305
692
+ * conventions even though the helper parameter order is `(dataLength, aadLength)`.
693
+ * @param isLE - Whether to encode lengths as little-endian.
694
+ * @returns 16-byte length block.
695
+ * @throws On wrong argument types passed to the endian validator. {@link TypeError}
696
+ * @throws On wrong argument ranges or values. {@link RangeError}
697
+ * @example
698
+ * Builds the length block appended by GCM and Poly1305.
699
+ *
700
+ * ```ts
701
+ * u64Lengths(16, 8, true);
702
+ * ```
703
+ */
704
+ function u64Lengths(dataLength, aadLength, isLE) {
705
+ // Reject coercible non-number lengths like '10' and true before BigInt(...) accepts them.
706
+ anumber(dataLength);
707
+ anumber(aadLength);
708
+ abool(isLE);
709
+ const num = new Uint8Array(16);
710
+ const view = createView(num);
711
+ view.setBigUint64(0, BigInt(aadLength), isLE);
712
+ view.setBigUint64(8, BigInt(dataLength), isLE);
713
+ return num;
714
+ }
715
+ /**
716
+ * Checks whether a byte array is aligned to a 4-byte offset.
717
+ * @param bytes - Byte array to inspect.
718
+ * @returns `true` when the view is 4-byte aligned.
719
+ * @example
720
+ * Checks whether a buffer can be safely viewed as Uint32Array.
721
+ *
722
+ * ```ts
723
+ * isAligned32(new Uint8Array(4));
724
+ * ```
725
+ */
726
+ function isAligned32(bytes) {
727
+ return bytes.byteOffset % 4 === 0;
728
+ }
729
+ /**
730
+ * Copies bytes into a new Uint8Array.
731
+ * @param bytes - Bytes to copy.
732
+ * @returns Copied byte array.
733
+ * @throws On wrong argument types. {@link TypeError}
734
+ * @example
735
+ * Copies input into an aligned Uint8Array before block processing.
736
+ *
737
+ * ```ts
738
+ * copyBytes(new Uint8Array([1, 2]));
739
+ * ```
740
+ */
741
+ function copyBytes(bytes) {
742
+ // `Uint8Array.from(...)` would also accept arrays / other typed arrays. Keep this helper strict
743
+ // because callers use it at byte-validation boundaries before mutating the detached copy.
744
+ return Uint8Array.from(abytes(bytes));
745
+ }
746
+ /**
747
+ * Cryptographically secure PRNG.
748
+ * Uses internal OS-level `crypto.getRandomValues`.
749
+ * @param bytesLength - Number of bytes to produce.
750
+ * Validation is delegated to `Uint8Array(bytesLength)` and `getRandomValues`, so
751
+ * non-integers, negative lengths, and oversize requests surface backend/runtime errors.
752
+ * @returns Random byte array.
753
+ * @throws On wrong argument types. {@link TypeError}
754
+ * @throws On wrong argument ranges or values. {@link RangeError}
755
+ * @throws If the runtime does not expose `crypto.getRandomValues`. {@link Error}
756
+ * @example
757
+ * Generates a fresh nonce or key.
758
+ *
759
+ * ```ts
760
+ * randomBytes(16);
761
+ * ```
762
+ */
763
+ function randomBytes(bytesLength = 32) {
764
+ // Validate upfront so fractional / coercible lengths do not silently
765
+ // truncate through Uint8Array().
766
+ anumber(bytesLength);
767
+ const cr = typeof globalThis === 'object' ? globalThis.crypto : null;
768
+ if (typeof cr?.getRandomValues !== 'function')
769
+ throw new Error('crypto.getRandomValues must be defined');
770
+ return cr.getRandomValues(new Uint8Array(bytesLength));
771
+ }
772
+ /**
773
+ * Uses CSPRNG for nonce, nonce injected in ciphertext.
774
+ * For `encrypt`, a `nonceBytes`-length buffer is fetched from CSPRNG and
775
+ * prepended to encrypted ciphertext. For `decrypt`, first `nonceBytes` of ciphertext
776
+ * are treated as nonce. The wrapper always allocates a fresh `nonce || ciphertext`
777
+ * buffer on encrypt and intentionally does not support caller-provided destination buffers.
778
+ * Too-short decrypt inputs are split into short/empty nonce views and then delegated
779
+ * to the wrapped cipher instead of being rejected here first.
780
+ *
781
+ * NOTE: Under the same key, using random nonces (e.g. `managedNonce`) with AES-GCM and ChaCha
782
+ * should be limited to `2**23` (8M) messages to get a collision chance of
783
+ * `2**-50`. Stretching to `2**32` (4B) messages would raise that chance to
784
+ * `2**-33`, still negligible but creeping up.
785
+ * @param fn - Cipher constructor that expects a nonce.
786
+ * @param randomBytes_ - Random-byte source used for nonce generation.
787
+ * @returns Cipher constructor that prepends the nonce to ciphertext.
788
+ * @throws On wrong argument types. {@link TypeError}
789
+ * @throws On invalid nonce lengths observed at wrapper construction or use. {@link RangeError}
790
+ * @example
791
+ * Prepends a fresh random nonce to every ciphertext.
792
+ *
793
+ * ```ts
794
+ * import { gcm } from './aes';
795
+ * import { managedNonce, randomBytes } from './utils';
796
+ * const wrapped = managedNonce(gcm);
797
+ * const key = randomBytes(16);
798
+ * const ciphertext = wrapped(key).encrypt(new Uint8Array([1, 2, 3]));
799
+ * wrapped(key).decrypt(ciphertext);
800
+ * ```
801
+ */
802
+ function managedNonce(fn, randomBytes_ = randomBytes) {
803
+ const { nonceLength } = fn;
804
+ anumber(nonceLength);
805
+ const addNonce = (nonce, ciphertext, plaintext) => {
806
+ const out = concatBytes(nonce, ciphertext);
807
+ // Wrapped ciphers may alias caller plaintext on encrypt(); never zero
808
+ // caller-owned buffers here.
809
+ if (!overlapBytes(plaintext, ciphertext))
810
+ ciphertext.fill(0);
811
+ return out;
812
+ };
813
+ // NOTE: we cannot support DST here, it would be mistake:
814
+ // - we don't know how much dst length cipher requires
815
+ // - nonce may unalign dst and break everything
816
+ // - we create new u8a anyway (concatBytes)
817
+ // - previously we passed all args to cipher, but that was mistake!
818
+ const res = ((key, ...args) => ({
819
+ encrypt(plaintext) {
820
+ abytes(plaintext);
821
+ const nonce = randomBytes_(nonceLength);
822
+ const encrypted = fn(key, nonce, ...args).encrypt(plaintext);
823
+ // @ts-ignore
824
+ if (encrypted instanceof Promise)
825
+ return encrypted.then((ct) => addNonce(nonce, ct, plaintext));
826
+ return addNonce(nonce, encrypted, plaintext);
827
+ },
828
+ decrypt(ciphertext) {
829
+ abytes(ciphertext);
830
+ const nonce = ciphertext.subarray(0, nonceLength);
831
+ const decrypted = ciphertext.subarray(nonceLength);
832
+ return fn(key, nonce, ...args).decrypt(decrypted);
833
+ },
834
+ }));
835
+ // Auto-nonce wrappers still preserve the wrapped payload geometry.
836
+ if ('blockSize' in fn)
837
+ res.blockSize = fn.blockSize;
838
+ if ('tagLength' in fn)
839
+ res.tagLength = fn.tagLength;
840
+ return res;
841
+ }