@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/aes.d.ts ADDED
@@ -0,0 +1,461 @@
1
+ import { type Cipher, type CipherWithOutput, type CMac, type IHash2, type PRG, type TArg, type TRet, type Uint8ArrayBuffer } from './utils';
2
+ /**
3
+ * Increments a counter block with wrap around.
4
+ * AES call sites here currently use the big-endian branch, but the helper supports both layouts.
5
+ * NIST SP 800-38A Appendix B.1 and SP 800-38D §6.2 increment the
6
+ * least-significant/rightmost bits.
7
+ * `isLE=false` matches that standard counter-block layout, while `isLE=true`
8
+ * is a generic extension for non-AES callers.
9
+ * The implementation keeps a 32-bit bitwise carry path, so `carry` is capped at `0xffffff00`;
10
+ * larger values throw instead of silently overflowing before the next-byte propagation step.
11
+ */
12
+ declare const incBytes: (data: TArg<Uint8Array>, isLE: boolean, carry?: number) => void;
13
+ /** Forward AES key expansion used across ECB/CBC/CTR/GCM/CMAC/KW-style paths. */
14
+ declare function expandKeyLE(key: TArg<Uint8Array>): TRet<Uint32Array>;
15
+ declare function expandKeyDecLE(key: TArg<Uint8Array>): TRet<Uint32Array>;
16
+ declare function encrypt(xk: TArg<Uint32Array>, s0: number, s1: number, s2: number, s3: number): {
17
+ s0: number;
18
+ s1: number;
19
+ s2: number;
20
+ s3: number;
21
+ };
22
+ declare function decrypt(xk: TArg<Uint32Array>, s0: number, s1: number, s2: number, s3: number): {
23
+ s0: number;
24
+ s1: number;
25
+ s2: number;
26
+ s3: number;
27
+ };
28
+ declare function ctrCounter(xk: TArg<Uint32Array>, nonce: TArg<Uint8Array>, src: TArg<Uint8Array>, dst?: TArg<Uint8Array>): TRet<Uint8Array>;
29
+ declare function ctr32(xk: TArg<Uint32Array>, isLE: boolean, nonce: TArg<Uint8Array>, src: TArg<Uint8Array>, dst?: TArg<Uint8Array>): TRet<Uint8Array>;
30
+ /**
31
+ * **CTR** (Counter Mode): turns a block cipher into a stream cipher using a
32
+ * full 16-byte counter block.
33
+ * Efficient and parallelizable. Requires a unique nonce per encryption. Unauthenticated: needs MAC.
34
+ * @param key - AES key bytes.
35
+ * @param nonce - 16-byte counter block, incremented as a full AES block.
36
+ * @returns Cipher instance with `encrypt()` and `decrypt()`.
37
+ * @example
38
+ * Encrypts a short payload with a fresh AES key and counter block.
39
+ *
40
+ * ```ts
41
+ * import { ctr } from './aes';
42
+ * import { randomBytes } from './utils';
43
+ * const key = randomBytes(16);
44
+ * const nonce = randomBytes(16);
45
+ * const cipher = ctr(key, nonce);
46
+ * cipher.encrypt(new Uint8Array([1, 2, 3]));
47
+ * ```
48
+ */
49
+ export declare const ctr: TRet<((key: TArg<Uint8Array>, nonce: TArg<Uint8Array>) => CipherWithOutput) & {
50
+ blockSize: number;
51
+ nonceLength: number;
52
+ }>;
53
+ /** Options for ECB and CBC. */
54
+ export type BlockOpts = {
55
+ /** Disable the library's PKCS#7 padding/unpadding layer and require exact-block inputs. */
56
+ disablePadding?: boolean;
57
+ };
58
+ /**
59
+ * **ECB** (Electronic Codebook): Deterministic encryption; identical plaintext blocks yield
60
+ * identical ciphertexts. Not secure due to pattern leakage.
61
+ * See {@link https://words.filippo.io/the-ecb-penguin/ | the AES Penguin}.
62
+ * @param key - AES key bytes.
63
+ * @param opts - Padding options. See {@link BlockOpts}.
64
+ * @returns Cipher instance with `encrypt()` and `decrypt()`.
65
+ * @example
66
+ * Shows the basic ECB encrypt call shape with a fresh key; avoid ECB in new designs.
67
+ *
68
+ * ```ts
69
+ * import { ecb } from './aes';
70
+ * import { randomBytes } from './utils';
71
+ * const key = randomBytes(16);
72
+ * const cipher = ecb(key);
73
+ * cipher.encrypt(new Uint8Array([1, 2, 3]));
74
+ * ```
75
+ */
76
+ export declare const ecb: TRet<((key: TArg<Uint8Array>, opts?: BlockOpts) => CipherWithOutput) & {
77
+ blockSize: number;
78
+ }>;
79
+ /**
80
+ * **CBC** (Cipher Block Chaining): Each plaintext block is XORed with the
81
+ * previous block of ciphertext before encryption.
82
+ * Hard to use: requires proper padding and an unpredictable IV. Unauthenticated: needs MAC.
83
+ * @param key - AES key bytes.
84
+ * @param iv - 16-byte unpredictable initialization vector.
85
+ * @param opts - Padding options. See {@link BlockOpts}.
86
+ * @returns Cipher instance with `encrypt()` and `decrypt()`.
87
+ * @example
88
+ * Encrypts a padded message with a fresh key and 16-byte IV.
89
+ *
90
+ * ```ts
91
+ * import { cbc } from './aes';
92
+ * import { randomBytes } from './utils';
93
+ * const key = randomBytes(16);
94
+ * const iv = randomBytes(16);
95
+ * const cipher = cbc(key, iv);
96
+ * cipher.encrypt(new Uint8Array([1, 2, 3]));
97
+ * ```
98
+ */
99
+ export declare const cbc: TRet<((key: TArg<Uint8Array>, iv: TArg<Uint8Array>, opts?: BlockOpts) => CipherWithOutput) & {
100
+ blockSize: number;
101
+ nonceLength: number;
102
+ }>;
103
+ /**
104
+ * CFB (CFB-128): Cipher Feedback Mode with 128-bit segments. The input for the
105
+ * block cipher is the previous cipher output.
106
+ * Unauthenticated: needs MAC.
107
+ * @param key - AES key bytes.
108
+ * @param iv - 16-byte unpredictable initialization vector.
109
+ * @returns Cipher instance with `encrypt()` and `decrypt()`.
110
+ * @example
111
+ * Encrypts a short message with feedback mode and a fresh key/IV pair.
112
+ *
113
+ * ```ts
114
+ * import { cfb } from './aes';
115
+ * import { randomBytes } from './utils';
116
+ * const key = randomBytes(16);
117
+ * const iv = randomBytes(16);
118
+ * const cipher = cfb(key, iv);
119
+ * cipher.encrypt(new Uint8Array([1, 2, 3]));
120
+ * ```
121
+ */
122
+ export declare const cfb: TRet<((key: TArg<Uint8Array>, iv: TArg<Uint8Array>) => CipherWithOutput) & {
123
+ blockSize: number;
124
+ nonceLength: number;
125
+ }>;
126
+ /**
127
+ * **GCM** (Galois/Counter Mode): Combines CTR mode with polynomial MAC. Efficient and widely used.
128
+ * Not perfect:
129
+ * a) conservative key wear-out is `2**32` (4B) msgs.
130
+ * b) key wear-out under random nonces is even smaller: `2**23` (8M) messages for `2**-50` chance.
131
+ * c) MAC can be forged: see Poly1305 documentation.
132
+ * @param key - AES key bytes.
133
+ * @param nonce - Nonce bytes (12 recommended, minimum 8; other lengths use GHASH J0 derivation).
134
+ * @param AAD - Additional authenticated data.
135
+ * @returns AEAD cipher instance with a fixed 16-byte tag.
136
+ * @example
137
+ * Encrypts and authenticates plaintext with a fresh key and 12-byte nonce.
138
+ *
139
+ * ```ts
140
+ * import { gcm } from './aes';
141
+ * import { randomBytes } from './utils';
142
+ * const key = randomBytes(16);
143
+ * const nonce = randomBytes(12);
144
+ * const cipher = gcm(key, nonce);
145
+ * cipher.encrypt(new Uint8Array([1, 2, 3]));
146
+ * ```
147
+ */
148
+ export declare const gcm: TRet<((key: TArg<Uint8Array>, nonce: TArg<Uint8Array>, AAD?: TArg<Uint8Array>) => Cipher) & {
149
+ blockSize: number;
150
+ nonceLength: number;
151
+ tagLength: number;
152
+ varSizeNonce: true;
153
+ }>;
154
+ /**
155
+ * **SIV** (Synthetic IV): GCM with nonce-misuse resistance.
156
+ * Repeating nonces reveal only the fact plaintexts are identical.
157
+ * Also suffers from GCM issues: key wear-out limits & MAC forging.
158
+ * See {@link https://www.rfc-editor.org/rfc/rfc8452 | RFC 8452}.
159
+ * RFC 8452 defines 16-byte and 32-byte AES keys for this mode.
160
+ * This implementation also accepts 24-byte AES-192 keys as a local
161
+ * extension; see the inline comment next to `validateKeyLength(key)` below
162
+ * for the exact scope note.
163
+ * @param key - AES key bytes.
164
+ * @param nonce - 12-byte nonce.
165
+ * @param AAD - Additional authenticated data.
166
+ * @returns AEAD cipher instance.
167
+ * @example
168
+ * Encrypts and authenticates plaintext with a fresh key and nonce, while tolerating reuse.
169
+ *
170
+ * ```ts
171
+ * import { gcmsiv } from './aes';
172
+ * import { randomBytes } from './utils';
173
+ * const key = randomBytes(16);
174
+ * const nonce = randomBytes(12);
175
+ * const cipher = gcmsiv(key, nonce);
176
+ * cipher.encrypt(new Uint8Array([1, 2, 3]));
177
+ * ```
178
+ */
179
+ export declare const gcmsiv: TRet<((key: TArg<Uint8Array>, nonce: TArg<Uint8Array>, AAD?: TArg<Uint8Array>) => Cipher) & {
180
+ blockSize: number;
181
+ nonceLength: number;
182
+ tagLength: number;
183
+ varSizeNonce: true;
184
+ }>;
185
+ declare function encryptBlock(xk: TArg<Uint32Array>, block: TArg<Uint8Array>): TRet<Uint8Array>;
186
+ declare function decryptBlock(xk: TArg<Uint32Array>, block: TArg<Uint8Array>): TRet<Uint8Array>;
187
+ /**
188
+ * AES-KW (key-wrap). Injects static IV into plaintext, adds counter, encrypts 6 times.
189
+ * Reduces block size from 16 to 8 bytes.
190
+ * Plaintext must be a non-empty multiple of 8 bytes with minimum 16 bytes.
191
+ * 8-byte inputs use aeskwp.
192
+ * Wrapped ciphertext must be a multiple of 8 bytes with minimum 24 bytes.
193
+ * For padded version, use aeskwp.
194
+ * See {@link https://www.rfc-editor.org/rfc/rfc3394/ | RFC 3394} and
195
+ * {@link https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-38F.pdf | NIST SP 800-38F}.
196
+ * @param kek - AES key-encryption key.
197
+ * @returns Key-wrap cipher instance.
198
+ * As with other `wrapCipher(...)` wrappers, `encrypt()` is single-use per
199
+ * instance.
200
+ * @example
201
+ * Wraps a 128-bit content-encryption key with a fresh key-encryption key.
202
+ *
203
+ * ```ts
204
+ * import { aeskw } from './aes';
205
+ * import { randomBytes } from './utils';
206
+ * const kek = randomBytes(16);
207
+ * const cek = randomBytes(16);
208
+ * const wrap = aeskw(kek);
209
+ * wrap.encrypt(cek);
210
+ * ```
211
+ */
212
+ export declare const aeskw: TRet<((kek: TArg<Uint8Array>) => Cipher) & {
213
+ blockSize: number;
214
+ }>;
215
+ /**
216
+ * AES-KW, but with padding and allows random keys.
217
+ * Uses the RFC 5649 alternative initial value; the second u32 stores the
218
+ * 32-bit MLI in network order.
219
+ * Wrapped ciphertext must be at least 16 bytes; malformed lengths are
220
+ * rejected during AIV/padding checks.
221
+ * See {@link https://www.rfc-editor.org/rfc/rfc5649 | RFC 5649}.
222
+ * @param kek - AES key-encryption key.
223
+ * @returns Padded key-wrap cipher instance.
224
+ * @example
225
+ * Wraps a short key blob using the padded variant and a fresh key-encryption key.
226
+ *
227
+ * ```ts
228
+ * import { aeskwp } from './aes';
229
+ * import { randomBytes } from './utils';
230
+ * const kek = randomBytes(16);
231
+ * const wrap = aeskwp(kek);
232
+ * wrap.encrypt(new Uint8Array([1, 2, 3]));
233
+ * ```
234
+ */
235
+ export declare const aeskwp: TRet<((kek: TArg<Uint8Array>) => Cipher) & {
236
+ blockSize: number;
237
+ }>;
238
+ declare class _AesCtrDRBG implements PRG {
239
+ readonly blockLen: number;
240
+ private key;
241
+ private nonce;
242
+ private state;
243
+ private reseedCnt;
244
+ constructor(keyLen: number, seed: TArg<Uint8Array>, personalization?: TArg<Uint8Array>);
245
+ private update;
246
+ addEntropy(seed: TArg<Uint8Array>, info?: TArg<Uint8Array>): void;
247
+ randomBytes(len: number, info?: TArg<Uint8Array>): TRet<Uint8Array>;
248
+ clean(): void;
249
+ }
250
+ /**
251
+ * Factory for AES-CTR DRBG instances.
252
+ * @param seed - Initial entropy input.
253
+ * @param personalization - Optional personalization string mixed into the state.
254
+ * @returns Seeded AES-CTR DRBG instance.
255
+ */
256
+ export type AesCtrDrbg = (seed: TArg<Uint8Array>, personalization?: TArg<Uint8Array>) => TRet<_AesCtrDRBG>;
257
+ /**
258
+ * AES-CTR DRBG 128-bit - CSPRNG (cryptographically secure pseudorandom number generator).
259
+ * It's best to limit usage to non-production, non-critical cases: for example, test-only.
260
+ * @param seed - Initial 32-byte entropy input.
261
+ * @param personalization - Optional personalization string.
262
+ * @returns Seeded DRBG instance. The concrete methods also accept optional additional-input bytes.
263
+ * @example
264
+ * Seeds the test-only AES-CTR DRBG from fresh entropy and reads bytes from it.
265
+ *
266
+ * ```ts
267
+ * import { rngAesCtrDrbg128 } from './aes';
268
+ * import { randomBytes } from './utils';
269
+ * const seed = randomBytes(32);
270
+ * const prg = rngAesCtrDrbg128(seed);
271
+ * prg.randomBytes(8);
272
+ * ```
273
+ */
274
+ export declare const rngAesCtrDrbg128: TRet<AesCtrDrbg>;
275
+ /**
276
+ * AES-CTR DRBG 256-bit - CSPRNG (cryptographically secure pseudorandom number generator).
277
+ * It's best to limit usage to non-production, non-critical cases: for example, test-only.
278
+ * @param seed - Initial 48-byte entropy input.
279
+ * @param personalization - Optional personalization string.
280
+ * @returns Seeded DRBG instance. The concrete methods also accept optional additional-input bytes.
281
+ * @example
282
+ * Seeds the test-only AES-CTR DRBG from fresh entropy and reads bytes from it.
283
+ *
284
+ * ```ts
285
+ * import { rngAesCtrDrbg256 } from './aes';
286
+ * import { randomBytes } from './utils';
287
+ * const seed = randomBytes(48);
288
+ * const prg = rngAesCtrDrbg256(seed);
289
+ * prg.randomBytes(8);
290
+ * ```
291
+ */
292
+ export declare const rngAesCtrDrbg256: TRet<AesCtrDrbg>;
293
+ /**
294
+ * Left-shift by one bit and conditionally XOR with 0x87:
295
+ * ```
296
+ * if MSB(L) is equal to 0
297
+ * then K1 := L << 1;
298
+ * else K1 := (L << 1) XOR const_Rb;
299
+ * ```
300
+ *
301
+ * Specs:
302
+ * {@link https://www.rfc-editor.org/rfc/rfc4493.html#section-2.3 | RFC 4493 Section 2.3},
303
+ * {@link https://datatracker.ietf.org/doc/html/rfc5297.html#section-2.3 | RFC 5297 Section 2.3}
304
+ *
305
+ * @returns modified `block` (for chaining)
306
+ */
307
+ declare function dbl<T extends Uint8Array>(block: T): T;
308
+ /**
309
+ * `a XOR b`, running in-place on `a`.
310
+ * @param a left operand and output
311
+ * @param b right operand
312
+ * @returns `a` (for chaining)
313
+ */
314
+ declare function xorBlock<T extends TArg<Uint8Array>>(a: T, b: TArg<Uint8Array>): T;
315
+ /**
316
+ * xorend as defined in
317
+ * {@link https://datatracker.ietf.org/doc/html/rfc5297.html#section-2.1 | RFC 5297 Section 2.1}.
318
+ *
319
+ * ```
320
+ * leftmost(A, len(A)-len(B)) || (rightmost(A, len(B)) xor B)
321
+ * ```
322
+ *
323
+ * Mutates `a` in place so the left prefix stays untouched and only the
324
+ * rightmost `len(B)` bytes are xored with `b`.
325
+ */
326
+ declare function xorend<T extends TArg<Uint8Array>>(a: T, b: TArg<Uint8Array>): T;
327
+ /**
328
+ * Internal CMAC class.
329
+ */
330
+ declare class _CMAC implements IHash2 {
331
+ readonly blockLen: number;
332
+ readonly outputLen: number;
333
+ private buffer;
334
+ private pos;
335
+ private finished;
336
+ private destroyed;
337
+ private k1;
338
+ private k2;
339
+ private x;
340
+ private xk;
341
+ constructor(key: TArg<Uint8Array>);
342
+ private process;
343
+ update(data: TArg<Uint8Array>): this;
344
+ digestInto(out: TArg<Uint8Array>): void;
345
+ digest(): Uint8ArrayBuffer;
346
+ destroy(): void;
347
+ }
348
+ /**
349
+ * AES-CMAC (Cipher-based Message Authentication Code).
350
+ * Specs: {@link https://www.rfc-editor.org/rfc/rfc4493.html | RFC 4493}.
351
+ * @param msg - Message bytes to authenticate.
352
+ * @param key - AES key bytes.
353
+ * @returns 16-byte authentication tag. `cmac.create(...)` follows the same incremental MAC shape as
354
+ * the other keyed helpers in this repo, including `blockLen`,
355
+ * `outputLen`, `digestInto()` and `destroy()`.
356
+ * @example
357
+ * Authenticates a message with AES-CMAC and a fresh key.
358
+ *
359
+ * ```ts
360
+ * import { cmac } from './aes';
361
+ * import { randomBytes } from './utils';
362
+ * const key = randomBytes(16);
363
+ * cmac(new Uint8Array(), key);
364
+ * ```
365
+ */
366
+ export declare const cmac: TRet<CMac<_CMAC>>;
367
+ /**
368
+ * S2V (Synthetic Initialization Vector) function as described in
369
+ * {@link https://datatracker.ietf.org/doc/html/rfc5297.html#section-2.4 | RFC 5297 Section 2.4}.
370
+ *
371
+ * ```
372
+ * S2V(K, S1, ..., Sn) {
373
+ * if n = 0 then
374
+ * return V = AES-CMAC(K, <one>)
375
+ * fi
376
+ * D = AES-CMAC(K, <zero>)
377
+ * for i = 1 to n-1 do
378
+ * D = dbl(D) xor AES-CMAC(K, Si)
379
+ * done
380
+ * if len(Sn) >= 128 then
381
+ * T = Sn xorend D
382
+ * else
383
+ * T = dbl(D) xor pad(Sn)
384
+ * fi
385
+ * return V = AES-CMAC(K, T)
386
+ * }
387
+ * ```
388
+ *
389
+ * S2V takes a key and a vector of strings S1, S2, ..., Sn and returns a 128-bit string.
390
+ * The S2V function is used to generate a synthetic IV for AES-SIV.
391
+ *
392
+ * @param key - AES key (128, 192, or 256 bits)
393
+ * @param strings - Array of byte arrays to process
394
+ * @returns 128-bit synthetic IV
395
+ */
396
+ declare function s2v(key: TArg<Uint8Array>, strings: TArg<Uint8Array[]>): TRet<Uint8Array>;
397
+ /**
398
+ * Use `gcmsiv` or `aessiv`.
399
+ * @returns Never; always throws with the migration hint.
400
+ * @throws If called; `siv()` is a removed v1 alias. {@link Error}
401
+ * @example
402
+ * `siv()` was removed in v2; use `gcmsiv()` for nonce-based SIV instead.
403
+ *
404
+ * ```ts
405
+ * import { gcmsiv } from './aes';
406
+ * import { randomBytes } from './utils';
407
+ * const key = randomBytes(16);
408
+ * const nonce = randomBytes(12);
409
+ * const cipher = gcmsiv(key, nonce);
410
+ * cipher.encrypt(new Uint8Array([1, 2, 3]));
411
+ * ```
412
+ */
413
+ export declare const siv: () => never;
414
+ /**
415
+ * **SIV**: Synthetic Initialization Vector (SIV) Authenticated Encryption
416
+ * Nonce is derived from the plaintext and AAD using the S2V function.
417
+ * Supports at most 126 AAD components. RFC 5297 nonce-based use is expressed by
418
+ * passing the nonce as the final AAD component before the plaintext.
419
+ * See {@link https://datatracker.ietf.org/doc/html/rfc5297.html | RFC 5297}.
420
+ * @param key - 32-byte, 48-byte, or 64-byte key.
421
+ * @param AAD - Additional authenticated data chunks (up to 126).
422
+ * @returns AEAD cipher instance.
423
+ * @example
424
+ * Authenticates and encrypts plaintext with a fresh key without requiring unique nonces.
425
+ *
426
+ * ```ts
427
+ * import { aessiv } from './aes';
428
+ * import { randomBytes } from './utils';
429
+ * const key = randomBytes(32);
430
+ * const cipher = aessiv(key);
431
+ * cipher.encrypt(new Uint8Array([1, 2, 3]));
432
+ * ```
433
+ */
434
+ export declare const aessiv: TRet<((key: TArg<Uint8Array>, ...AAD: TArg<Uint8Array[]>) => Cipher) & {
435
+ blockSize: number;
436
+ tagLength: number;
437
+ }>;
438
+ /**
439
+ * Unsafe low-level internal methods. May change at any time.
440
+ * Callers are expected to use reviewed expanded-key outputs, pass mutable and
441
+ * aligned 16-byte blocks where required, and treat several helpers as in-place
442
+ * mutations of their input buffers or counters.
443
+ */
444
+ export declare const unsafe: {
445
+ expandKeyLE: typeof expandKeyLE;
446
+ expandKeyDecLE: typeof expandKeyDecLE;
447
+ encrypt: typeof encrypt;
448
+ decrypt: typeof decrypt;
449
+ encryptBlock: typeof encryptBlock;
450
+ decryptBlock: typeof decryptBlock;
451
+ ctrCounter: typeof ctrCounter;
452
+ ctr32: typeof ctr32;
453
+ dbl: typeof dbl;
454
+ xorBlock: typeof xorBlock;
455
+ xorend: typeof xorend;
456
+ s2v: typeof s2v;
457
+ };
458
+ export declare const __TESTS: {
459
+ incBytes: typeof incBytes;
460
+ };
461
+ export {};