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