@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.d.ts ADDED
@@ -0,0 +1,716 @@
1
+ /**
2
+ * Utilities for hex, bytes, CSPRNG.
3
+ * @module
4
+ */
5
+ /*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */
6
+ /**
7
+ * Bytes API type helpers for old + new TypeScript.
8
+ *
9
+ * TS 5.6 has `Uint8Array`, while TS 5.9+ made it generic `Uint8Array<ArrayBuffer>`.
10
+ * We can't use specific return type, because TS 5.6 will error.
11
+ * We can't use generic return type, because most TS 5.9 software will expect specific type.
12
+ *
13
+ * Maps typed-array input leaves to broad forms.
14
+ * These are compatibility adapters, not ownership guarantees.
15
+ *
16
+ * - `TArg` keeps byte inputs broad.
17
+ * - `TRet` marks byte outputs for TS 5.6 and TS 5.9+ compatibility.
18
+ */
19
+ export type TypedArg<T> = T extends BigInt64Array ? BigInt64Array : T extends BigUint64Array ? BigUint64Array : T extends Float32Array ? Float32Array : T extends Float64Array ? Float64Array : T extends Int16Array ? Int16Array : T extends Int32Array ? Int32Array : T extends Int8Array ? Int8Array : T extends Uint16Array ? Uint16Array : T extends Uint32Array ? Uint32Array : T extends Uint8ClampedArray ? Uint8ClampedArray : T extends Uint8Array ? Uint8Array : never;
20
+ /** Maps typed-array output leaves to narrow TS-compatible forms. */
21
+ export type TypedRet<T> = T extends BigInt64Array ? ReturnType<typeof BigInt64Array.of> : T extends BigUint64Array ? ReturnType<typeof BigUint64Array.of> : T extends Float32Array ? ReturnType<typeof Float32Array.of> : T extends Float64Array ? ReturnType<typeof Float64Array.of> : T extends Int16Array ? ReturnType<typeof Int16Array.of> : T extends Int32Array ? ReturnType<typeof Int32Array.of> : T extends Int8Array ? ReturnType<typeof Int8Array.of> : T extends Uint16Array ? ReturnType<typeof Uint16Array.of> : T extends Uint32Array ? ReturnType<typeof Uint32Array.of> : T extends Uint8ClampedArray ? ReturnType<typeof Uint8ClampedArray.of> : T extends Uint8Array ? ReturnType<typeof Uint8Array.of> : never;
22
+ /** Recursively adapts byte-carrying API input types. See {@link TypedArg}. */
23
+ export type TArg<T> = T | ([TypedArg<T>] extends [never] ? T extends (...args: infer A) => infer R ? ((...args: {
24
+ [K in keyof A]: TRet<A[K]>;
25
+ }) => TArg<R>) & {
26
+ [K in keyof T]: T[K] extends (...args: any) => any ? T[K] : TArg<T[K]>;
27
+ } : T extends [infer A, ...infer R] ? [TArg<A>, ...{
28
+ [K in keyof R]: TArg<R[K]>;
29
+ }] : T extends readonly [infer A, ...infer R] ? readonly [TArg<A>, ...{
30
+ [K in keyof R]: TArg<R[K]>;
31
+ }] : T extends (infer A)[] ? TArg<A>[] : T extends readonly (infer A)[] ? readonly TArg<A>[] : T extends Promise<infer A> ? Promise<TArg<A>> : T extends object ? {
32
+ [K in keyof T]: TArg<T[K]>;
33
+ } : T : TypedArg<T>);
34
+ /** Recursively adapts byte-carrying API output types. See {@link TypedArg}. */
35
+ export type TRet<T> = T extends unknown ? T & ([TypedRet<T>] extends [never] ? T extends (...args: infer A) => infer R ? ((...args: {
36
+ [K in keyof A]: TArg<A[K]>;
37
+ }) => TRet<R>) & {
38
+ [K in keyof T]: T[K] extends (...args: any) => any ? T[K] : TRet<T[K]>;
39
+ } : T extends [infer A, ...infer R] ? [TRet<A>, ...{
40
+ [K in keyof R]: TRet<R[K]>;
41
+ }] : T extends readonly [infer A, ...infer R] ? readonly [TRet<A>, ...{
42
+ [K in keyof R]: TRet<R[K]>;
43
+ }] : T extends (infer A)[] ? TRet<A>[] : T extends readonly (infer A)[] ? readonly TRet<A>[] : T extends Promise<infer A> ? Promise<TRet<A>> : T extends object ? {
44
+ [K in keyof T]: TRet<T[K]>;
45
+ } : T : TypedRet<T>) : never;
46
+ /**
47
+ * Checks if something is Uint8Array. Be careful: nodejs Buffer will return true.
48
+ * @param a - Value to inspect.
49
+ * @returns `true` when the value is a Uint8Array view, including Node's `Buffer`.
50
+ * @example
51
+ * Guards a value before treating it as raw key material.
52
+ *
53
+ * ```ts
54
+ * isBytes(new Uint8Array());
55
+ * ```
56
+ */
57
+ export declare function isBytes(a: unknown): a is Uint8Array;
58
+ /**
59
+ * Asserts something is boolean.
60
+ * @param b - Value to validate.
61
+ * @throws On wrong argument types. {@link TypeError}
62
+ * @example
63
+ * Validates a boolean option before branching on it.
64
+ *
65
+ * ```ts
66
+ * abool(true);
67
+ * ```
68
+ */
69
+ export declare function abool(b: boolean): void;
70
+ /**
71
+ * Asserts something is a non-negative safe integer.
72
+ * @param n - Value to validate.
73
+ * @throws On wrong argument types. {@link TypeError}
74
+ * @throws On wrong argument ranges or values. {@link RangeError}
75
+ * @example
76
+ * Validates a non-negative length or counter.
77
+ *
78
+ * ```ts
79
+ * anumber(1);
80
+ * ```
81
+ */
82
+ export declare function anumber(n: number): void;
83
+ /**
84
+ * Asserts something is Uint8Array.
85
+ * @param value - Value to validate.
86
+ * @param length - Expected byte length.
87
+ * @param title - Optional label used in error messages.
88
+ * @returns The validated byte array.
89
+ * On Node, `Buffer` is accepted too because it is a Uint8Array view.
90
+ * @throws On wrong argument types. {@link TypeError}
91
+ * @throws On wrong argument lengths. {@link RangeError}
92
+ * @example
93
+ * Validates a fixed-length nonce or key buffer.
94
+ *
95
+ * ```ts
96
+ * abytes(new Uint8Array([1, 2]), 2);
97
+ * ```
98
+ */
99
+ export declare function abytes(value: TArg<Uint8Array>, length?: number, title?: string): TRet<Uint8Array>;
100
+ /**
101
+ * Asserts a hash- or MAC-like instance has not been destroyed or finished.
102
+ * @param instance - Stateful instance to validate.
103
+ * @param checkFinished - Whether to reject finished instances.
104
+ * When `false`, only `destroyed` is checked.
105
+ * @throws If the hash instance has already been destroyed or finalized. {@link Error}
106
+ * @example
107
+ * Guards against calling `update()` or `digest()` on a finished hash.
108
+ *
109
+ * ```ts
110
+ * aexists({ destroyed: false, finished: false });
111
+ * ```
112
+ */
113
+ export declare function aexists(instance: any, checkFinished?: boolean): void;
114
+ /**
115
+ * Asserts output is a properly-sized byte array.
116
+ * @param out - Output buffer to validate.
117
+ * @param instance - Hash-like instance providing `outputLen`.
118
+ * This is the relaxed `digestInto()`-style contract: output must be at least `outputLen`,
119
+ * unlike one-shot cipher helpers elsewhere in the repo that often require exact lengths.
120
+ * @throws On wrong argument types. {@link TypeError}
121
+ * @param onlyAligned - Whether `out` must be 4-byte aligned for zero-allocation word views.
122
+ * @throws On wrong output buffer lengths. {@link RangeError}
123
+ * @throws On wrong output buffer alignment. {@link Error}
124
+ * @example
125
+ * Verifies that a caller-provided output buffer is large enough.
126
+ *
127
+ * ```ts
128
+ * aoutput(new Uint8Array(16), { outputLen: 16 });
129
+ * ```
130
+ */
131
+ export declare function aoutput(out: any, instance: any, onlyAligned?: boolean): void;
132
+ /** One-shot hash helper with `.create()`. */
133
+ export type IHash = {
134
+ (data: string | TArg<Uint8Array>): TRet<Uint8Array>;
135
+ /** Input block size in bytes. */
136
+ blockLen: number;
137
+ /** Digest size in bytes. */
138
+ outputLen: number;
139
+ /** Creates a fresh incremental hash instance of the same algorithm. */
140
+ create: any;
141
+ };
142
+ /** One-shot MAC helper with `.create()`. */
143
+ export type CMac<H extends IHash2 = IHash2, A extends any[] = []> = {
144
+ (msg: TArg<Uint8Array>, key: TArg<Uint8Array>): TRet<Uint8Array>;
145
+ /** Input block size in bytes. */
146
+ blockLen: number;
147
+ /** Digest size in bytes. */
148
+ outputLen: number;
149
+ /**
150
+ * Creates a fresh incremental MAC instance of the same algorithm.
151
+ * @param key - MAC key bytes.
152
+ * @param args - Additional constructor arguments, when the MAC wrapper needs them.
153
+ * @returns Fresh incremental MAC instance.
154
+ */
155
+ create(key: TArg<Uint8Array>, ...args: A): H;
156
+ };
157
+ /** Generic type encompassing 8/16/32-bit typed arrays, but not 64-bit. */
158
+ export type TypedArray = Int8Array | Uint8ClampedArray | Uint8Array | Uint16Array | Int16Array | Uint32Array | Int32Array;
159
+ /**
160
+ * Casts a typed-array view to Uint8Array.
161
+ * @param arr - Typed-array view to reinterpret.
162
+ * @returns Uint8Array view over the same bytes.
163
+ * @example
164
+ * Views 32-bit words as raw bytes without copying.
165
+ *
166
+ * ```ts
167
+ * u8(new Uint32Array([1]));
168
+ * ```
169
+ */
170
+ export declare function u8(arr: TArg<TypedArray>): TRet<Uint8Array>;
171
+ /**
172
+ * Casts a typed-array view to Uint32Array.
173
+ * @param arr - Typed-array view to reinterpret.
174
+ * @returns Uint32Array view over the same bytes. Callers are expected to provide a
175
+ * 4-byte-aligned offset; trailing `1..3` bytes are silently dropped.
176
+ * @example
177
+ * Views a byte buffer as 32-bit words for block processing.
178
+ *
179
+ * ```ts
180
+ * u32(new Uint8Array(4));
181
+ * ```
182
+ */
183
+ export declare function u32(arr: TArg<TypedArray>): TRet<Uint32Array>;
184
+ /**
185
+ * Zeroizes typed arrays in place.
186
+ * Warning: JS provides no guarantees.
187
+ * @param arrays - Arrays to wipe.
188
+ * @example
189
+ * Wipes a temporary key buffer after use.
190
+ *
191
+ * ```ts
192
+ * const bytes = new Uint8Array([1]);
193
+ * clean(bytes);
194
+ * ```
195
+ */
196
+ export declare function clean(...arrays: TArg<TypedArray[]>): void;
197
+ /**
198
+ * Creates a DataView for byte-level manipulation.
199
+ * @param arr - Typed-array view to wrap.
200
+ * @returns DataView over the same bytes.
201
+ * @example
202
+ * Creates an endian-aware view for length encoding.
203
+ *
204
+ * ```ts
205
+ * createView(new Uint8Array(4));
206
+ * ```
207
+ */
208
+ export declare function createView(arr: TArg<TypedArray>): DataView;
209
+ /**
210
+ * Whether the current platform is little-endian.
211
+ * Most are; some IBM systems are not.
212
+ */
213
+ export declare const isLE: boolean;
214
+ /**
215
+ * Reverses byte order of one 32-bit word.
216
+ * @param word - Unsigned 32-bit word to swap.
217
+ * @returns The same word with bytes reversed.
218
+ * @example
219
+ * Swaps a big-endian word into little-endian byte order.
220
+ *
221
+ * ```ts
222
+ * byteSwap(0x11223344);
223
+ * ```
224
+ */
225
+ export declare const byteSwap: (word: number) => number;
226
+ /**
227
+ * Normalizes one 32-bit word to the little-endian representation expected by cipher cores.
228
+ * @param n - Unsigned 32-bit word to normalize.
229
+ * @returns Little-endian normalized word on big-endian hosts, else the input word unchanged.
230
+ * @example
231
+ * Normalizes a host-endian word before passing it into an ARX/AES core.
232
+ *
233
+ * ```ts
234
+ * swap8IfBE(0x11223344);
235
+ * ```
236
+ */
237
+ export declare const swap8IfBE: (n: number) => number;
238
+ /**
239
+ * Byte-swaps every word of a Uint32Array in place.
240
+ * @param arr - Uint32Array whose words should be swapped.
241
+ * @returns The same array after in-place byte swapping.
242
+ * @example
243
+ * Swaps every 32-bit word in a word-view buffer.
244
+ *
245
+ * ```ts
246
+ * byteSwap32(new Uint32Array([0x11223344]));
247
+ * ```
248
+ */
249
+ export declare const byteSwap32: (arr: TArg<Uint32Array>) => TRet<Uint32Array>;
250
+ /**
251
+ * Normalizes a Uint32Array view to the little-endian representation expected by cipher cores.
252
+ * @param u - Word view to normalize in place.
253
+ * @returns Little-endian normalized word view.
254
+ * @example
255
+ * Normalizes a word-view buffer before block processing.
256
+ *
257
+ * ```ts
258
+ * swap32IfBE(new Uint32Array([0x11223344]));
259
+ * ```
260
+ */
261
+ export declare const swap32IfBE: (u: TArg<Uint32Array>) => TRet<Uint32Array>;
262
+ /**
263
+ * Convert byte array to hex string. Uses built-in function, when available.
264
+ * @param bytes - Bytes to encode.
265
+ * @returns Lowercase hexadecimal string.
266
+ * @throws On wrong argument types. {@link TypeError}
267
+ * @example
268
+ * Formats ciphertext bytes for logs or test vectors.
269
+ *
270
+ * ```ts
271
+ * bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])); // 'cafe0123'
272
+ * ```
273
+ */
274
+ export declare function bytesToHex(bytes: TArg<Uint8Array>): string;
275
+ /**
276
+ * Convert hex string to byte array. Uses built-in function, when available.
277
+ * @param hex - Hexadecimal string to decode.
278
+ * @returns Decoded bytes.
279
+ * @throws On wrong argument types. {@link TypeError}
280
+ * @throws On malformed hexadecimal input. {@link RangeError}
281
+ * @example
282
+ * Parses a hex test vector into bytes.
283
+ *
284
+ * ```ts
285
+ * hexToBytes('cafe0123'); // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])
286
+ * ```
287
+ */
288
+ export declare function hexToBytes(hex: string): TRet<Uint8Array>;
289
+ /**
290
+ * Converts a big-endian hex string into bigint.
291
+ * @param hex - Hexadecimal string without `0x`.
292
+ * @returns Parsed bigint value. The empty string is treated as `0n`.
293
+ * @throws On wrong argument types. {@link TypeError}
294
+ * @example
295
+ * Parses a big-endian field element or counter from hex.
296
+ *
297
+ * ```ts
298
+ * hexToNumber('ff');
299
+ * ```
300
+ */
301
+ export declare function hexToNumber(hex: string): bigint;
302
+ /**
303
+ * Converts big-endian bytes into bigint.
304
+ * @param bytes - Big-endian bytes.
305
+ * @returns Parsed bigint value. Empty input is treated as `0n`.
306
+ * @throws On invalid byte input passed to the internal hex conversion. {@link TypeError}
307
+ * @example
308
+ * Reads a big-endian integer from serialized bytes.
309
+ *
310
+ * ```ts
311
+ * bytesToNumberBE(new Uint8Array([1, 0]));
312
+ * ```
313
+ */
314
+ export declare function bytesToNumberBE(bytes: TArg<Uint8Array>): bigint;
315
+ /**
316
+ * Converts a number into big-endian bytes of fixed length.
317
+ * @param n - Number to encode.
318
+ * @param len - Output length in bytes.
319
+ * @returns Big-endian bytes padded to `len`.
320
+ * Validation is indirect through `hexToBytes(...)`, so negative values, `len = 0`,
321
+ * and values that do not fit surface through the downstream hex parser instead of a
322
+ * dedicated range guard here.
323
+ * @throws On wrong argument types. {@link TypeError}
324
+ * @throws If the requested output length cannot represent the encoded value. {@link RangeError}
325
+ * @example
326
+ * Encodes a counter as fixed-width big-endian bytes.
327
+ *
328
+ * ```ts
329
+ * numberToBytesBE(1, 2);
330
+ * ```
331
+ */
332
+ export declare function numberToBytesBE(n: number | bigint, len: number): TRet<Uint8Array>;
333
+ /**
334
+ * Converts string to bytes using UTF8 encoding.
335
+ * @param str - String to encode.
336
+ * @returns UTF-8 bytes in a detached fresh Uint8Array copy.
337
+ * @throws On wrong argument types. {@link TypeError}
338
+ * @example
339
+ * Encodes application text before encryption or MACing.
340
+ *
341
+ * ```ts
342
+ * utf8ToBytes('abc'); // new Uint8Array([97, 98, 99])
343
+ * ```
344
+ */
345
+ export declare function utf8ToBytes(str: string): TRet<Uint8Array>;
346
+ /**
347
+ * Converts bytes to string using UTF8 encoding.
348
+ * @param bytes - UTF-8 bytes.
349
+ * @returns Decoded string. Input validation is delegated to `TextDecoder`, and malformed
350
+ * UTF-8 is replacement-decoded instead of rejected.
351
+ * @example
352
+ * Decodes UTF-8 plaintext back into a string.
353
+ *
354
+ * ```ts
355
+ * bytesToUtf8(new Uint8Array([97, 98, 99])); // 'abc'
356
+ * ```
357
+ */
358
+ export declare function bytesToUtf8(bytes: TArg<Uint8Array>): string;
359
+ /**
360
+ * Checks if two U8A use same underlying buffer and overlaps.
361
+ * This is invalid and can corrupt data.
362
+ * @param a - First byte view.
363
+ * @param b - Second byte view.
364
+ * @returns `true` when the views overlap in memory.
365
+ * @example
366
+ * Detects whether two slices alias the same backing buffer.
367
+ *
368
+ * ```ts
369
+ * overlapBytes(new Uint8Array(4), new Uint8Array(4));
370
+ * ```
371
+ */
372
+ export declare function overlapBytes(a: TArg<Uint8Array>, b: TArg<Uint8Array>): boolean;
373
+ /**
374
+ * If input and output overlap and input starts before output, we will overwrite end of input before
375
+ * we start processing it, so this is not supported for most ciphers
376
+ * (except chacha/salsa, which were designed for this)
377
+ * @param input - Input bytes.
378
+ * @param output - Output bytes.
379
+ * @throws If the output view would overwrite unread input bytes. {@link Error}
380
+ * @example
381
+ * Rejects an in-place layout that would overwrite unread input bytes.
382
+ *
383
+ * ```ts
384
+ * complexOverlapBytes(new Uint8Array(4), new Uint8Array(4));
385
+ * ```
386
+ */
387
+ export declare function complexOverlapBytes(input: TArg<Uint8Array>, output: TArg<Uint8Array>): void;
388
+ /**
389
+ * Copies several Uint8Arrays into one.
390
+ * @param arrays - Byte arrays to concatenate.
391
+ * @returns Combined byte array.
392
+ * @throws On wrong argument types inside the byte-array list. {@link TypeError}
393
+ * @example
394
+ * Builds a `nonce || ciphertext` style buffer.
395
+ *
396
+ * ```ts
397
+ * concatBytes(new Uint8Array([1]), new Uint8Array([2]));
398
+ * ```
399
+ */
400
+ export declare function concatBytes(...arrays: TArg<Uint8Array[]>): TRet<Uint8Array>;
401
+ type EmptyObj = {};
402
+ /**
403
+ * Merges user options into defaults.
404
+ * @param defaults - Default option values.
405
+ * @param opts - User-provided overrides.
406
+ * @returns Combined options object.
407
+ * The merge mutates `defaults` in place and returns the same object.
408
+ * @throws If options are missing or not an object. {@link Error}
409
+ * @example
410
+ * Applies user overrides to the default cipher options.
411
+ *
412
+ * ```ts
413
+ * checkOpts({ rounds: 20 }, { rounds: 8 });
414
+ * ```
415
+ */
416
+ export declare function checkOpts<T1 extends EmptyObj, T2 extends EmptyObj>(defaults: T1, opts: T2): T1 & T2;
417
+ /**
418
+ * Compares two byte arrays in kinda constant time once lengths already match.
419
+ * @param a - First byte array.
420
+ * @param b - Second byte array.
421
+ * @returns `true` when the arrays contain the same bytes. Different lengths still return early.
422
+ * @example
423
+ * Compares an expected authentication tag with the received one.
424
+ *
425
+ * ```ts
426
+ * equalBytes(new Uint8Array([1]), new Uint8Array([1]));
427
+ * ```
428
+ */
429
+ export declare function equalBytes(a: TArg<Uint8Array>, b: TArg<Uint8Array>): boolean;
430
+ /** Incremental hash interface used internally. */
431
+ export interface IHash2 {
432
+ /** Bytes processed per compression block. */
433
+ blockLen: number;
434
+ /** Bytes produced by the final digest. */
435
+ outputLen: number;
436
+ /**
437
+ * Absorbs one more chunk into the hash state.
438
+ * @param buf - Data chunk to hash.
439
+ * @returns The same hash instance for chaining.
440
+ */
441
+ update(buf: string | TArg<Uint8Array>): this;
442
+ /**
443
+ * Writes the final digest into a caller-provided buffer.
444
+ * @param buf - Destination buffer for the digest bytes.
445
+ * @returns Nothing. Implementations write into `buf` in place.
446
+ */
447
+ digestInto(buf: TArg<Uint8Array>): void;
448
+ /**
449
+ * Finalizes the hash and returns a fresh digest buffer.
450
+ * @returns Digest bytes.
451
+ */
452
+ digest(): TRet<Uint8Array>;
453
+ /**
454
+ * Resets internal state. Makes Hash instance unusable.
455
+ * Reset is impossible for keyed hashes if key is consumed into state. If digest is not consumed
456
+ * by user, they will need to manually call `destroy()` when zeroing is necessary.
457
+ */
458
+ destroy(): void;
459
+ }
460
+ /**
461
+ * Wraps a keyed MAC constructor into a one-shot helper with `.create()`.
462
+ * @param keyLen - Valid probe-key length used to read static metadata once.
463
+ * The probe key is only used for `outputLen` / `blockLen`, so callers with several valid key sizes
464
+ * can pass any representative size as long as those values stay fixed.
465
+ * @param macCons - Keyed MAC constructor or factory.
466
+ * @param fromMsg - Optional adapter that derives extra constructor args from the one-shot message.
467
+ * @returns Callable MAC helper with `.create()`.
468
+ */
469
+ export declare function wrapMacConstructor<H extends IHash2, A extends any[] = []>(keyLen: number, macCons: TArg<(key: Uint8Array, ...args: A) => H>, fromMsg?: TArg<(msg: Uint8Array) => A>): TRet<CMac<H, A>>;
470
+ /** Sync cipher: takes byte array and returns byte array. */
471
+ export type Cipher = {
472
+ /**
473
+ * Encrypts plaintext bytes.
474
+ * @param plaintext - Data to encrypt.
475
+ * @returns Ciphertext bytes.
476
+ */
477
+ encrypt(plaintext: TArg<Uint8Array>): TRet<Uint8Array>;
478
+ /**
479
+ * Decrypts ciphertext bytes.
480
+ * @param ciphertext - Data to decrypt.
481
+ * @returns Plaintext bytes.
482
+ */
483
+ decrypt(ciphertext: TArg<Uint8Array>): TRet<Uint8Array>;
484
+ };
485
+ /** Async cipher e.g. from built-in WebCrypto. */
486
+ export type AsyncCipher = {
487
+ /**
488
+ * Encrypts plaintext bytes.
489
+ * @param plaintext - Data to encrypt.
490
+ * @returns Promise resolving to ciphertext bytes.
491
+ */
492
+ encrypt(plaintext: TArg<Uint8Array>): Promise<TRet<Uint8Array>>;
493
+ /**
494
+ * Decrypts ciphertext bytes.
495
+ * @param ciphertext - Data to decrypt.
496
+ * @returns Promise resolving to plaintext bytes.
497
+ */
498
+ decrypt(ciphertext: TArg<Uint8Array>): Promise<TRet<Uint8Array>>;
499
+ };
500
+ /** Cipher with `output` argument which can optimize by doing 1 less allocation. */
501
+ export type CipherWithOutput = Cipher & {
502
+ /**
503
+ * Encrypts plaintext bytes into an optional caller-provided buffer.
504
+ * @param plaintext - Data to encrypt.
505
+ * @param output - Optional destination buffer.
506
+ * @returns Ciphertext bytes.
507
+ */
508
+ encrypt(plaintext: TArg<Uint8Array>, output?: TArg<Uint8Array>): TRet<Uint8Array>;
509
+ /**
510
+ * Decrypts ciphertext bytes into an optional caller-provided buffer.
511
+ * @param ciphertext - Data to decrypt.
512
+ * @param output - Optional destination buffer.
513
+ * @returns Plaintext bytes.
514
+ */
515
+ decrypt(ciphertext: TArg<Uint8Array>, output?: TArg<Uint8Array>): TRet<Uint8Array>;
516
+ };
517
+ /**
518
+ * Params are outside of return type, so it is accessible before calling constructor.
519
+ * If function support multiple nonceLength's, we return the best one.
520
+ */
521
+ export type CipherParams = {
522
+ /** Cipher block size in bytes. */
523
+ blockSize: number;
524
+ /** Nonce length in bytes when the cipher uses a fixed nonce size. */
525
+ nonceLength?: number;
526
+ /** Authentication-tag length in bytes for AEAD modes. */
527
+ tagLength?: number;
528
+ /** Whether nonce length is variable at runtime. */
529
+ varSizeNonce?: boolean;
530
+ };
531
+ /**
532
+ * ARX AEAD cipher, like salsa or chacha.
533
+ * @param key - Secret key bytes.
534
+ * @param nonce - Nonce bytes.
535
+ * @param AAD - Optional associated data.
536
+ * @returns Cipher instance with caller-managed output buffers.
537
+ */
538
+ export type ARXCipher = ((key: TArg<Uint8Array>, nonce: TArg<Uint8Array>, AAD?: TArg<Uint8Array>) => CipherWithOutput) & {
539
+ blockSize: number;
540
+ nonceLength: number;
541
+ tagLength: number;
542
+ };
543
+ /**
544
+ * Cipher constructor signature.
545
+ * @param key - Secret key bytes.
546
+ * @param args - Additional constructor arguments, such as nonce or IV.
547
+ * @returns Cipher instance.
548
+ */
549
+ export type CipherCons<T extends any[]> = (key: TArg<Uint8Array>, ...args: T) => Cipher;
550
+ /**
551
+ * Wraps a cipher: validates args, ensures encrypt() can only be called once.
552
+ * Used internally by the exported cipher constructors.
553
+ * Output-buffer support is inferred from the wrapped `encrypt` / `decrypt`
554
+ * arity (`fn.length === 2`), and tag-bearing constructors are expected to use
555
+ * `args[1]` for optional AAD.
556
+ * @__NO_SIDE_EFFECTS__
557
+ * @param params - Static cipher metadata. See {@link CipherParams}.
558
+ * @param constructor - Cipher constructor.
559
+ * @returns Wrapped constructor with validation.
560
+ */
561
+ export declare const wrapCipher: <C extends CipherCons<any>, P extends CipherParams>(params: P, constructor: C) => C & P;
562
+ /**
563
+ * Represents a Salsa or ChaCha xor stream.
564
+ * @param key - Secret key bytes.
565
+ * @param nonce - Nonce bytes.
566
+ * @param data - Input bytes to xor with the keystream.
567
+ * @param output - Optional destination buffer.
568
+ * @param counter - Optional starting block counter.
569
+ * @returns Output bytes.
570
+ */
571
+ export type XorStream = (key: TArg<Uint8Array>, nonce: TArg<Uint8Array>, data: TArg<Uint8Array>, output?: TArg<Uint8Array>, counter?: number) => TRet<Uint8Array>;
572
+ /**
573
+ * By default, returns u8a of length.
574
+ * When out is available, it checks it for validity and uses it.
575
+ * @param expectedLength - Required output length.
576
+ * @param out - Optional destination buffer.
577
+ * @param onlyAligned - Whether `out` must be 4-byte aligned.
578
+ * @returns Output buffer ready for writing.
579
+ * @throws On wrong argument types. {@link TypeError}
580
+ * @throws If the provided output buffer has the wrong size or alignment. {@link Error}
581
+ * @example
582
+ * Reuses a caller-provided output buffer when lengths match.
583
+ *
584
+ * ```ts
585
+ * getOutput(16, new Uint8Array(16));
586
+ * ```
587
+ */
588
+ export declare function getOutput(expectedLength: number, out?: TArg<Uint8Array>, onlyAligned?: boolean): TRet<Uint8Array>;
589
+ /**
590
+ * Encodes data and AAD bit lengths into a 16-byte buffer.
591
+ * @param dataLength - Data length in bits.
592
+ * @param aadLength - AAD length in bits.
593
+ * The serialized block is still `aadLength || dataLength`, matching GCM/Poly1305
594
+ * conventions even though the helper parameter order is `(dataLength, aadLength)`.
595
+ * @param isLE - Whether to encode lengths as little-endian.
596
+ * @returns 16-byte length block.
597
+ * @throws On wrong argument types passed to the endian validator. {@link TypeError}
598
+ * @throws On wrong argument ranges or values. {@link RangeError}
599
+ * @example
600
+ * Builds the length block appended by GCM and Poly1305.
601
+ *
602
+ * ```ts
603
+ * u64Lengths(16, 8, true);
604
+ * ```
605
+ */
606
+ export declare function u64Lengths(dataLength: number, aadLength: number, isLE: boolean): TRet<Uint8Array>;
607
+ /**
608
+ * Checks whether a byte array is aligned to a 4-byte offset.
609
+ * @param bytes - Byte array to inspect.
610
+ * @returns `true` when the view is 4-byte aligned.
611
+ * @example
612
+ * Checks whether a buffer can be safely viewed as Uint32Array.
613
+ *
614
+ * ```ts
615
+ * isAligned32(new Uint8Array(4));
616
+ * ```
617
+ */
618
+ export declare function isAligned32(bytes: TArg<Uint8Array>): boolean;
619
+ /**
620
+ * Copies bytes into a new Uint8Array.
621
+ * @param bytes - Bytes to copy.
622
+ * @returns Copied byte array.
623
+ * @throws On wrong argument types. {@link TypeError}
624
+ * @example
625
+ * Copies input into an aligned Uint8Array before block processing.
626
+ *
627
+ * ```ts
628
+ * copyBytes(new Uint8Array([1, 2]));
629
+ * ```
630
+ */
631
+ export declare function copyBytes(bytes: TArg<Uint8Array>): TRet<Uint8Array>;
632
+ /**
633
+ * Cryptographically secure PRNG.
634
+ * Uses internal OS-level `crypto.getRandomValues`.
635
+ * @param bytesLength - Number of bytes to produce.
636
+ * Validation is delegated to `Uint8Array(bytesLength)` and `getRandomValues`, so
637
+ * non-integers, negative lengths, and oversize requests surface backend/runtime errors.
638
+ * @returns Random byte array.
639
+ * @throws On wrong argument types. {@link TypeError}
640
+ * @throws On wrong argument ranges or values. {@link RangeError}
641
+ * @throws If the runtime does not expose `crypto.getRandomValues`. {@link Error}
642
+ * @example
643
+ * Generates a fresh nonce or key.
644
+ *
645
+ * ```ts
646
+ * randomBytes(16);
647
+ * ```
648
+ */
649
+ export declare function randomBytes(bytesLength?: number): TRet<Uint8Array>;
650
+ /**
651
+ * The pseudorandom number generator doesn't wipe current state:
652
+ * instead, it generates new one based on previous state + entropy.
653
+ * Not reseed/rekey, since AES CTR DRBG does rekey on each randomBytes,
654
+ * which is in fact `reseed`, since it changes counter too.
655
+ */
656
+ export interface PRG {
657
+ /**
658
+ * Mixes fresh entropy into the current generator state.
659
+ * @param seed - Entropy bytes to absorb.
660
+ */
661
+ addEntropy(seed: TArg<Uint8Array>): void;
662
+ /**
663
+ * Produces a requested number of pseudorandom bytes.
664
+ * @param bytesLength - Number of bytes to generate.
665
+ * @returns Random byte array.
666
+ */
667
+ randomBytes(bytesLength: number): TRet<Uint8Array>;
668
+ /** Destroys the generator state. */
669
+ clean(): void;
670
+ }
671
+ /** Removes the nonce argument from a cipher constructor type. */
672
+ export type RemoveNonce<T extends (...args: any) => any> = T extends (arg0: any, arg1: any, ...rest: infer R) => infer Ret ? (key: TArg<Uint8Array>, ...args: R) => Ret : never;
673
+ /**
674
+ * Cipher constructor that requires a nonce argument.
675
+ * @param key - Secret key bytes.
676
+ * @param nonce - Nonce bytes.
677
+ * @param args - Additional cipher-specific arguments.
678
+ * @returns Cipher instance.
679
+ */
680
+ export type CipherWithNonce = ((key: TArg<Uint8Array>, nonce: TArg<Uint8Array>, ...args: any[]) => Cipher | AsyncCipher) & {
681
+ nonceLength: number;
682
+ };
683
+ /**
684
+ * Uses CSPRNG for nonce, nonce injected in ciphertext.
685
+ * For `encrypt`, a `nonceBytes`-length buffer is fetched from CSPRNG and
686
+ * prepended to encrypted ciphertext. For `decrypt`, first `nonceBytes` of ciphertext
687
+ * are treated as nonce. The wrapper always allocates a fresh `nonce || ciphertext`
688
+ * buffer on encrypt and intentionally does not support caller-provided destination buffers.
689
+ * Too-short decrypt inputs are split into short/empty nonce views and then delegated
690
+ * to the wrapped cipher instead of being rejected here first.
691
+ *
692
+ * NOTE: Under the same key, using random nonces (e.g. `managedNonce`) with AES-GCM and ChaCha
693
+ * should be limited to `2**23` (8M) messages to get a collision chance of
694
+ * `2**-50`. Stretching to `2**32` (4B) messages would raise that chance to
695
+ * `2**-33`, still negligible but creeping up.
696
+ * @param fn - Cipher constructor that expects a nonce.
697
+ * @param randomBytes_ - Random-byte source used for nonce generation.
698
+ * @returns Cipher constructor that prepends the nonce to ciphertext.
699
+ * @throws On wrong argument types. {@link TypeError}
700
+ * @throws On invalid nonce lengths observed at wrapper construction or use. {@link RangeError}
701
+ * @example
702
+ * Prepends a fresh random nonce to every ciphertext.
703
+ *
704
+ * ```ts
705
+ * import { gcm } from './aes';
706
+ * import { managedNonce, randomBytes } from './utils';
707
+ * const wrapped = managedNonce(gcm);
708
+ * const key = randomBytes(16);
709
+ * const ciphertext = wrapped(key).encrypt(new Uint8Array([1, 2, 3]));
710
+ * wrapped(key).decrypt(ciphertext);
711
+ * ```
712
+ */
713
+ export declare function managedNonce<T extends CipherWithNonce>(fn: T, randomBytes_?: typeof randomBytes): TRet<RemoveNonce<T>>;
714
+ /** `Uint8Array.of()` return type helper for TS 5.9. */
715
+ export type Uint8ArrayBuffer = TRet<Uint8Array>;
716
+ export {};