@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/aes.js ADDED
@@ -0,0 +1,1764 @@
1
+ /**
2
+ * {@link https://en.wikipedia.org/wiki/Advanced_Encryption_Standard | AES}
3
+ * a.k.a. Advanced Encryption Standard
4
+ * is a variant of Rijndael block cipher, standardized by NIST in 2001.
5
+ * We provide the fastest available pure JS implementation.
6
+ *
7
+ * `cipher = encrypt(block, key)`
8
+ *
9
+ * Data is split into 128-bit blocks.
10
+ * Encrypted in 10/12/14 rounds (128/192/256 bits). In every round:
11
+ * 1. **S-box**, table substitution
12
+ * 2. **Shift rows**, cyclic shift left of all rows of data array
13
+ * 3. **Mix columns**, multiplying every column by fixed polynomial
14
+ * 4. **Add round key**, round_key xor i-th column of array
15
+ *
16
+ * Check out
17
+ * {@link https://csrc.nist.gov/files/pubs/fips/197/final/docs/fips-197.pdf | FIPS-197},
18
+ * {@link https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-38G.pdf | NIST 800-38G},
19
+ * and {@link https://csrc.nist.gov/csrc/media/projects/cryptographic-standards-and-guidelines/documents/aes-development/rijndael-ammended.pdf | original proposal}.
20
+ * @module
21
+ */
22
+ import { ghash, polyval } from './_polyval';
23
+ // prettier-ignore
24
+ import { abytes, anumber, aoutput, byteSwap, clean, complexOverlapBytes, concatBytes, copyBytes, createView, equalBytes, getOutput, isAligned32, isLE, overlapBytes, swap32IfBE, swap8IfBE, u32, u64Lengths, u8, wrapCipher, wrapMacConstructor } from './utils';
25
+ const BLOCK_SIZE = 16;
26
+ // AES operates on 16-byte blocks, i.e. 4 32-bit words.
27
+ const BLOCK_SIZE32 = 4;
28
+ // Shared zero block (`0^128`) used by GCM's `H = CIPH_K(0^128)` / J0 scratch
29
+ // and by CMAC / SIV helpers; callers take `.slice()` before mutating it.
30
+ const EMPTY_BLOCK = /* @__PURE__ */ new Uint8Array(BLOCK_SIZE);
31
+ // RFC 5297 §2.1 / §2.4: S2V uses `<one> = 0^127 || 1` for the `n = 0` special case.
32
+ const ONE_BLOCK = /* @__PURE__ */ Uint8Array.from([
33
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01,
34
+ ]);
35
+ const POLY = 0x11b; // 1 + x + x**3 + x**4 + x**8
36
+ // Validates plain AES key sizes only; AES-SIV's doubled-key contract is checked elsewhere.
37
+ function validateKeyLength(key) {
38
+ if (![16, 24, 32].includes(key.length))
39
+ throw new Error('"aes key" expected Uint8Array of length 16/24/32, got length=' + key.length);
40
+ }
41
+ // TODO: remove multiplication, binary ops only
42
+ // Doubles one GF(2^8) field element; callers are expected to stay in byte range.
43
+ // FIPS 197 upd1 §4.3 equation (4.5): XTIMES(b) left-shifts by one and, when
44
+ // b7=1, reduces by m(x); using POLY=0x11b here yields the same byte result
45
+ // as XORing with {1b} after the shift.
46
+ function mul2(n) {
47
+ return (n << 1) ^ (POLY & -(n >> 7));
48
+ }
49
+ // Shift-and-add multiplication in GF(2^8); callers are expected to pass byte values.
50
+ // FIPS 197 upd1 §4.3 equation (4.7): general products are XORs of repeated
51
+ // XTIMES() multiples, e.g. {57}•{13} = {57}⊕{ae}⊕{07}.
52
+ function mul(a, b) {
53
+ let res = 0;
54
+ for (; b > 0; b >>= 1) {
55
+ // Usual shift-and-add step in GF(2^8), not a scalar-multiplication ladder.
56
+ res ^= a & -(b & 1); // if (b&1) res ^=a (but const-time).
57
+ a = mul2(a); // a = 2*a
58
+ }
59
+ return res;
60
+ }
61
+ /**
62
+ * Increments a counter block with wrap around.
63
+ * AES call sites here currently use the big-endian branch, but the helper supports both layouts.
64
+ * NIST SP 800-38A Appendix B.1 and SP 800-38D §6.2 increment the
65
+ * least-significant/rightmost bits.
66
+ * `isLE=false` matches that standard counter-block layout, while `isLE=true`
67
+ * is a generic extension for non-AES callers.
68
+ * The implementation keeps a 32-bit bitwise carry path, so `carry` is capped at `0xffffff00`;
69
+ * larger values throw instead of silently overflowing before the next-byte propagation step.
70
+ */
71
+ // Keep the helper explicitly typed so `--isolatedDeclarations` can expose it
72
+ // through the test-only `__TESTS` export without inference errors.
73
+ const incBytes = (data, isLE, carry = 1) => {
74
+ // Keep `carry + byte <= 0xffffffff` so the `| 0` / `>>> 8` path below
75
+ // never truncates a real carry bit.
76
+ if (!Number.isSafeInteger(carry) || carry > 0xffffff00)
77
+ throw new Error('incBytes: wrong carry ' + carry);
78
+ abytes(data);
79
+ for (let i = 0; i < data.length; i++) {
80
+ const pos = !isLE ? data.length - 1 - i : i;
81
+ carry = (carry + (data[pos] & 0xff)) | 0;
82
+ data[pos] = carry & 0xff;
83
+ carry >>>= 8;
84
+ }
85
+ };
86
+ // AES S-box is generated using finite field inversion,
87
+ // an affine transform, and xor of a constant 0x63.
88
+ const sbox = /* @__PURE__ */ (() => {
89
+ const t = new Uint8Array(256);
90
+ // Repeated multiplication by {03} walks all 255 nonzero field elements
91
+ // once, so t[255 - i] is the multiplicative inverse of t[i] for the
92
+ // affine step.
93
+ for (let i = 0, x = 1; i < 256; i++, x ^= mul2(x))
94
+ t[i] = x;
95
+ const box = new Uint8Array(256);
96
+ // FIPS 197 upd1 §5.1.1: SBOX({00}) = {63} because the inverse step leaves
97
+ // {00} at {00}, then the affine transform xors in c = {63}.
98
+ box[0] = 0x63;
99
+ for (let i = 0; i < 255; i++) {
100
+ let x = t[255 - i];
101
+ x |= x << 8;
102
+ box[t[i]] = (x ^ (x >> 4) ^ (x >> 5) ^ (x >> 6) ^ (x >> 7) ^ 0x63) & 0xff;
103
+ }
104
+ clean(t);
105
+ return box;
106
+ })();
107
+ // FIPS 197 upd1 §5.3.2: INVSBOX() is derived from SBOX() by swapping input
108
+ // and output roles (Table 6).
109
+ // `indexOf` is only used once at module init, so the quadratic setup cost stays off hot paths.
110
+ const invSbox = /* @__PURE__ */ sbox.map((_, j) => sbox.indexOf(j));
111
+ // FIPS 197 upd1 §5.2: ROTWORD([a0,a1,a2,a3]) = [a1,a2,a3,a0]; with this LE
112
+ // word packing that is a right rotate by 8 bits.
113
+ const rotr32_8 = (n) => (n << 24) | (n >>> 8);
114
+ // LE T-table helper: rotates one precomputed word by one byte so T1/T2/T3
115
+ // reuse T0's substitution/mix result in the other byte lanes.
116
+ const rotl32_8 = (n) => (n << 8) | (n >>> 24);
117
+ // T-table is optimization suggested in 5.2 of original proposal (missed from FIPS-197). Changes:
118
+ // - LE instead of BE
119
+ // - bigger tables: T0 and T1 are merged into T01 table and T2 & T3 into T23;
120
+ // so index is u16, instead of u8. This speeds up things, unexpectedly
121
+ function genTtable(sbox, fn) {
122
+ if (sbox.length !== 256)
123
+ throw new Error('Wrong sbox length');
124
+ const T0 = new Uint32Array(256).map((_, j) => fn(sbox[j]));
125
+ const T1 = T0.map(rotl32_8);
126
+ const T2 = T1.map(rotl32_8);
127
+ const T3 = T2.map(rotl32_8);
128
+ // Pre-xor adjacent lanes so apply0123/applySbox can fetch two substituted
129
+ // byte lanes per lookup in the LE round layout.
130
+ const T01 = new Uint32Array(256 * 256);
131
+ const T23 = new Uint32Array(256 * 256);
132
+ const sbox2 = new Uint16Array(256 * 256);
133
+ for (let i = 0; i < 256; i++) {
134
+ for (let j = 0; j < 256; j++) {
135
+ const idx = i * 256 + j;
136
+ T01[idx] = T0[i] ^ T1[j];
137
+ T23[idx] = T2[i] ^ T3[j];
138
+ sbox2[idx] = (sbox[i] << 8) | sbox[j];
139
+ }
140
+ }
141
+ return { sbox, sbox2, T0, T1, T2, T3, T01, T23 };
142
+ }
143
+ // Forward round precompute: the packed word stores the MIXCOLUMNS row
144
+ // [{02},{01},{01},{03}] in LE byte-lane order, and the returned `sbox2`
145
+ // is also reused by key expansion and the final round.
146
+ const tableEncoding = /* @__PURE__ */ genTtable(sbox, (s) => (mul(s, 3) << 24) | (s << 16) | (s << 8) | mul(s, 2));
147
+ // Inverse round precompute: the packed word stores the INVMIXCOLUMNS row
148
+ // [{0e},{09},{0d},{0b}] in LE byte-lane order, and the tables are reused
149
+ // by decrypt() and expandKeyDecLE().
150
+ const tableDecoding = /* @__PURE__ */ genTtable(invSbox, (s) => (mul(s, 11) << 24) | (mul(s, 13) << 16) | (mul(s, 9) << 8) | mul(s, 14));
151
+ // FIPS 197 upd1 §5.2 Table 5: left-most bytes of Rcon[j] = x^(j-1), generated by repeated XTIMES().
152
+ const xPowers = /* @__PURE__ */ (() => {
153
+ const p = new Uint8Array(16);
154
+ for (let i = 0, x = 1; i < 16; i++, x = mul2(x))
155
+ p[i] = x;
156
+ return p;
157
+ })();
158
+ /** Forward AES key expansion used across ECB/CBC/CTR/GCM/CMAC/KW-style paths. */
159
+ function expandKeyLE(key) {
160
+ abytes(key);
161
+ const len = key.length;
162
+ validateKeyLength(key);
163
+ const { sbox2 } = tableEncoding;
164
+ const toClean = [];
165
+ // Copy on BE or misaligned inputs so the LE word normalization below never
166
+ // mutates caller key bytes in place.
167
+ if (!isLE || !isAligned32(key))
168
+ toClean.push((key = copyBytes(key)));
169
+ const k32 = swap32IfBE(u32(key));
170
+ const Nk = k32.length;
171
+ // `applySbox` normally reads one byte lane from each argument; repeating
172
+ // `n` across all four lanes turns it into SUBWORD(n).
173
+ const subByte = (n) => applySbox(sbox2, n, n, n, n);
174
+ // AES key sizes are 16/24/32 bytes, so len + 28 yields the 44/52/60
175
+ // schedule words from FIPS 197 §5.2 / Table 3.
176
+ const xk = new Uint32Array(len + 28); // expanded key
177
+ xk.set(k32);
178
+ // 4.3.1 Key expansion
179
+ for (let i = Nk; i < xk.length; i++) {
180
+ let t = xk[i - 1];
181
+ if (i % Nk === 0)
182
+ t = subByte(rotr32_8(t)) ^ xPowers[i / Nk - 1];
183
+ else if (Nk > 6 && i % Nk === 4)
184
+ t = subByte(t);
185
+ xk[i] = xk[i - Nk] ^ t;
186
+ }
187
+ clean(...toClean);
188
+ return xk;
189
+ }
190
+ function expandKeyDecLE(key) {
191
+ const encKey = expandKeyLE(key);
192
+ const xk = encKey.slice();
193
+ const Nk = encKey.length;
194
+ const { sbox2 } = tableEncoding;
195
+ const { T0, T1, T2, T3 } = tableDecoding;
196
+ // Local decrypt() walks round keys forward from xk[0], so reverse the
197
+ // encryption round-key blocks first before applying the equivalent-inverse
198
+ // middle-round transform.
199
+ for (let i = 0; i < Nk; i += 4) {
200
+ for (let j = 0; j < 4; j++)
201
+ xk[i + j] = encKey[Nk - i - 4 + j];
202
+ }
203
+ clean(encKey);
204
+ // Apply InvMixColumn to the reversed round keys using the same LE sbox2
205
+ // packing as the forward path.
206
+ // apply InvMixColumn except first & last round
207
+ for (let i = 4; i < Nk - 4; i++) {
208
+ const x = xk[i];
209
+ const w = applySbox(sbox2, x, x, x, x);
210
+ xk[i] = T0[w & 0xff] ^ T1[(w >>> 8) & 0xff] ^ T2[(w >>> 16) & 0xff] ^ T3[w >>> 24];
211
+ }
212
+ return xk;
213
+ }
214
+ // Apply tables
215
+ function apply0123(T01, T23, s0, s1, s2, s3) {
216
+ // `T01` takes the low byte lane from `s0` plus the next lane from `s1`;
217
+ // `T23` does the same for `s2`/`s3`.
218
+ // Equivalent to `T0[s0&0xff] ^ T1[(s1>>>8)&0xff] ^ T2[(s2>>>16)&0xff] ^
219
+ // T3[s3>>>24]`, but with two merged-table fetches.
220
+ return (T01[((s0 << 8) & 0xff00) | ((s1 >>> 8) & 0xff)] ^
221
+ T23[((s2 >>> 8) & 0xff00) | ((s3 >>> 24) & 0xff)]);
222
+ }
223
+ function applySbox(sbox2, s0, s1, s2, s3) {
224
+ // `sbox2` packs two substituted byte lanes at a time in the same LE
225
+ // layout used by the round code.
226
+ // Equivalent to `SBOX(byte0(s0)) | SBOX(byte1(s1))<<8 |
227
+ // SBOX(byte2(s2))<<16 | SBOX(byte3(s3))<<24`.
228
+ return (sbox2[(s0 & 0xff) | (s1 & 0xff00)] |
229
+ (sbox2[((s2 >>> 16) & 0xff) | ((s3 >>> 16) & 0xff00)] << 16));
230
+ }
231
+ function encrypt(xk, s0, s1, s2, s3) {
232
+ const { sbox2, T01, T23 } = tableEncoding;
233
+ let k = 0;
234
+ ((s0 ^= xk[k++]), (s1 ^= xk[k++]), (s2 ^= xk[k++]), (s3 ^= xk[k++]));
235
+ // `xk` has Nr+1 round-key blocks, so after the initial AddRoundKey and the
236
+ // final S-box-only round there are Nr-1 full table/MixColumns rounds left.
237
+ const rounds = xk.length / 4 - 2;
238
+ for (let i = 0; i < rounds; i++) {
239
+ const t0 = xk[k++] ^ apply0123(T01, T23, s0, s1, s2, s3);
240
+ const t1 = xk[k++] ^ apply0123(T01, T23, s1, s2, s3, s0);
241
+ const t2 = xk[k++] ^ apply0123(T01, T23, s2, s3, s0, s1);
242
+ const t3 = xk[k++] ^ apply0123(T01, T23, s3, s0, s1, s2);
243
+ ((s0 = t0), (s1 = t1), (s2 = t2), (s3 = t3));
244
+ }
245
+ // last round (without mixcolumns, so using SBOX2 table)
246
+ const t0 = xk[k++] ^ applySbox(sbox2, s0, s1, s2, s3);
247
+ const t1 = xk[k++] ^ applySbox(sbox2, s1, s2, s3, s0);
248
+ const t2 = xk[k++] ^ applySbox(sbox2, s2, s3, s0, s1);
249
+ const t3 = xk[k++] ^ applySbox(sbox2, s3, s0, s1, s2);
250
+ return { s0: t0, s1: t1, s2: t2, s3: t3 };
251
+ }
252
+ // Can't be merged with encrypt: arg positions for apply0123 / applySbox are different
253
+ function decrypt(xk, s0, s1, s2, s3) {
254
+ const { sbox2, T01, T23 } = tableDecoding;
255
+ let k = 0;
256
+ ((s0 ^= xk[k++]), (s1 ^= xk[k++]), (s2 ^= xk[k++]), (s3 ^= xk[k++]));
257
+ // With `expandKeyDecLE()` the round keys are already reversed and middle
258
+ // rounds are InvMixColumns-adjusted, so this loop follows the equivalent
259
+ // inverse cipher order directly.
260
+ const rounds = xk.length / 4 - 2;
261
+ for (let i = 0; i < rounds; i++) {
262
+ const t0 = xk[k++] ^ apply0123(T01, T23, s0, s3, s2, s1);
263
+ const t1 = xk[k++] ^ apply0123(T01, T23, s1, s0, s3, s2);
264
+ const t2 = xk[k++] ^ apply0123(T01, T23, s2, s1, s0, s3);
265
+ const t3 = xk[k++] ^ apply0123(T01, T23, s3, s2, s1, s0);
266
+ ((s0 = t0), (s1 = t1), (s2 = t2), (s3 = t3));
267
+ }
268
+ // Final equivalent-inverse round omits InvMixColumns, so use inverse
269
+ // S-box lanes in InvShiftRows order.
270
+ const t0 = xk[k++] ^ applySbox(sbox2, s0, s3, s2, s1);
271
+ const t1 = xk[k++] ^ applySbox(sbox2, s1, s0, s3, s2);
272
+ const t2 = xk[k++] ^ applySbox(sbox2, s2, s1, s0, s3);
273
+ const t3 = xk[k++] ^ applySbox(sbox2, s3, s2, s1, s0);
274
+ return { s0: t0, s1: t1, s2: t2, s3: t3 };
275
+ }
276
+ function ctrCounter(xk, nonce, src, dst) {
277
+ abytes(nonce, BLOCK_SIZE, 'nonce');
278
+ abytes(src);
279
+ const srcLen = src.length;
280
+ dst = getOutput(srcLen, dst);
281
+ complexOverlapBytes(src, dst);
282
+ // Internal helper: mutate `nonce` in place as the live counter block so
283
+ // each encrypted block uses the next CTR value.
284
+ const ctr = nonce;
285
+ const c32 = u32(ctr);
286
+ const src32 = u32(src);
287
+ const dst32 = u32(dst);
288
+ // Fill block (empty, ctr=0)
289
+ let { s0, s1, s2, s3 } = encrypt(xk, swap8IfBE(c32[0]), swap8IfBE(c32[1]), swap8IfBE(c32[2]), swap8IfBE(c32[3]));
290
+ // process blocks
291
+ for (let i = 0; i + 4 <= src32.length; i += 4) {
292
+ dst32[i + 0] = src32[i + 0] ^ swap8IfBE(s0);
293
+ dst32[i + 1] = src32[i + 1] ^ swap8IfBE(s1);
294
+ dst32[i + 2] = src32[i + 2] ^ swap8IfBE(s2);
295
+ dst32[i + 3] = src32[i + 3] ^ swap8IfBE(s3);
296
+ incBytes(ctr, false, 1); // Full 128 bit counter with wrap around
297
+ ({ s0, s1, s2, s3 } = encrypt(xk, swap8IfBE(c32[0]), swap8IfBE(c32[1]), swap8IfBE(c32[2]), swap8IfBE(c32[3])));
298
+ }
299
+ // NIST SP 800-38A CTR mode uses the leading `u` bits of the next output
300
+ // block for the final short block.
301
+ // It's possible to handle > u32 fast, but is it worth it?
302
+ const start = BLOCK_SIZE * Math.floor(src32.length / BLOCK_SIZE32);
303
+ if (start < srcLen) {
304
+ const b32 = new Uint32Array([s0, s1, s2, s3]);
305
+ swap32IfBE(b32);
306
+ const buf = u8(b32);
307
+ for (let i = start, pos = 0; i < srcLen; i++, pos++)
308
+ dst[i] = src[i] ^ buf[pos];
309
+ clean(b32);
310
+ }
311
+ // Unsafe mutable-counter API only advances whole blocks. Callers that want to
312
+ // resume after consuming part of this block must re-run from the same counter
313
+ // with left-padding and strip the already-consumed prefix themselves.
314
+ return dst;
315
+ }
316
+ // AES CTR with overflowing 32 bit counter
317
+ // It's possible to do 32le significantly simpler (and probably faster) by using u32.
318
+ // But, we need both, and perf bottleneck is in ghash anyway.
319
+ // Unsafe 32-bit CTR helper: mutates `nonce` in place, expects aligned `src`/`dst`,
320
+ // and uses `isLE` to choose which 32-bit counter word is incremented.
321
+ function ctr32(xk, isLE, nonce, src, dst) {
322
+ abytes(nonce, BLOCK_SIZE, 'nonce');
323
+ abytes(src);
324
+ dst = getOutput(src.length, dst);
325
+ const ctr = nonce; // write new value to nonce, so it can be re-used
326
+ const c32 = u32(ctr);
327
+ const view = createView(ctr);
328
+ const src32 = u32(src);
329
+ const dst32 = u32(dst);
330
+ // NIST SP 800-38D GCTR increments the rightmost 32 bits of J0, while
331
+ // RFC 8452 AES-GCM-SIV increments the first 32 bits as a little-endian u32.
332
+ const ctrPos = isLE ? 0 : 12;
333
+ const srcLen = src.length;
334
+ // Fill block (empty, ctr=0)
335
+ let ctrNum = view.getUint32(ctrPos, isLE); // read current counter value
336
+ let { s0, s1, s2, s3 } = encrypt(xk, swap8IfBE(c32[0]), swap8IfBE(c32[1]), swap8IfBE(c32[2]), swap8IfBE(c32[3]));
337
+ // process blocks
338
+ for (let i = 0; i + 4 <= src32.length; i += 4) {
339
+ dst32[i + 0] = src32[i + 0] ^ swap8IfBE(s0);
340
+ dst32[i + 1] = src32[i + 1] ^ swap8IfBE(s1);
341
+ dst32[i + 2] = src32[i + 2] ^ swap8IfBE(s2);
342
+ dst32[i + 3] = src32[i + 3] ^ swap8IfBE(s3);
343
+ ctrNum = (ctrNum + 1) >>> 0; // u32 wrap
344
+ view.setUint32(ctrPos, ctrNum, isLE);
345
+ ({ s0, s1, s2, s3 } = encrypt(xk, swap8IfBE(c32[0]), swap8IfBE(c32[1]), swap8IfBE(c32[2]), swap8IfBE(c32[3])));
346
+ }
347
+ // leftovers (less than a block)
348
+ const start = BLOCK_SIZE * Math.floor(src32.length / BLOCK_SIZE32);
349
+ if (start < srcLen) {
350
+ const b32 = new Uint32Array([s0, s1, s2, s3]);
351
+ swap32IfBE(b32);
352
+ const buf = u8(b32);
353
+ for (let i = start, pos = 0; i < srcLen; i++, pos++)
354
+ dst[i] = src[i] ^ buf[pos];
355
+ clean(b32);
356
+ }
357
+ // Same unsafe contract as ctrCounter(): only full blocks advance the stored
358
+ // mutable counter state; partial-block continuation is caller-managed.
359
+ return dst;
360
+ }
361
+ /**
362
+ * **CTR** (Counter Mode): turns a block cipher into a stream cipher using a
363
+ * full 16-byte counter block.
364
+ * Efficient and parallelizable. Requires a unique nonce per encryption. Unauthenticated: needs MAC.
365
+ * @param key - AES key bytes.
366
+ * @param nonce - 16-byte counter block, incremented as a full AES block.
367
+ * @returns Cipher instance with `encrypt()` and `decrypt()`.
368
+ * @example
369
+ * Encrypts a short payload with a fresh AES key and counter block.
370
+ *
371
+ * ```ts
372
+ * import { ctr } from './aes';
373
+ * import { randomBytes } from './utils';
374
+ * const key = randomBytes(16);
375
+ * const nonce = randomBytes(16);
376
+ * const cipher = ctr(key, nonce);
377
+ * cipher.encrypt(new Uint8Array([1, 2, 3]));
378
+ * ```
379
+ */
380
+ export const ctr = /* @__PURE__ */ wrapCipher({ blockSize: 16, nonceLength: 16 }, function aesctr(key, nonce) {
381
+ function processCtr(buf, dst) {
382
+ abytes(buf);
383
+ if (dst !== undefined) {
384
+ abytes(dst);
385
+ // Optional output buffers must stay 4-byte aligned because
386
+ // ctrCounter() reinterprets them as Uint32Array words.
387
+ if (!isAligned32(dst))
388
+ throw new Error('unaligned destination');
389
+ }
390
+ const xk = expandKeyLE(key);
391
+ // Public CTR keeps caller nonce bytes immutable even though ctrCounter()
392
+ // advances the live 16-byte counter block in place.
393
+ const n = copyBytes(nonce); // align + avoid changing
394
+ const toClean = [xk, n];
395
+ if (!isAligned32(buf))
396
+ toClean.push((buf = copyBytes(buf)));
397
+ const out = ctrCounter(xk, n, buf, dst);
398
+ clean(...toClean);
399
+ return out;
400
+ }
401
+ return {
402
+ encrypt: (plaintext, dst) => processCtr(plaintext, dst),
403
+ decrypt: (ciphertext, dst) => processCtr(ciphertext, dst),
404
+ };
405
+ });
406
+ function validateBlockDecrypt(data) {
407
+ abytes(data);
408
+ // ECB/CBC decryption always consumes whole ciphertext blocks; PKCS#7/CMS
409
+ // padding, when enabled, is removed only after decrypting the final block.
410
+ if (data.length % BLOCK_SIZE !== 0) {
411
+ throw new Error('aes-(cbc/ecb).decrypt ciphertext should consist of blocks with size ' + BLOCK_SIZE);
412
+ }
413
+ }
414
+ // ECB/CBC core modes operate on whole blocks; `pkcs5` enables the library's
415
+ // PKCS#7/CMS-compatible final-block padding convenience before encryption.
416
+ function validateBlockEncrypt(plaintext, pkcs5, dst) {
417
+ abytes(plaintext);
418
+ let outLen = plaintext.length;
419
+ const remaining = outLen % BLOCK_SIZE;
420
+ if (!pkcs5 && remaining !== 0)
421
+ throw new Error('aec/(cbc-ecb): unpadded plaintext with disabled padding');
422
+ if (pkcs5) {
423
+ let left = BLOCK_SIZE - remaining;
424
+ // RFC 5652 pads even already-aligned inputs, so a full extra block is
425
+ // appended when the plaintext length is already a multiple of 16 bytes.
426
+ if (!left)
427
+ left = BLOCK_SIZE; // if no bytes left, create empty padding block
428
+ outLen = outLen + left;
429
+ }
430
+ dst = getOutput(outLen, dst);
431
+ complexOverlapBytes(plaintext, dst);
432
+ // Copy on BE or misaligned inputs so u32()/swap32IfBE() normalization never
433
+ // mutates caller plaintext bytes in place before ECB/CBC processing.
434
+ if (!isLE || !isAligned32(plaintext))
435
+ plaintext = copyBytes(plaintext);
436
+ const b = u32(plaintext);
437
+ swap32IfBE(b);
438
+ const o = u32(dst);
439
+ return { b, o, out: dst };
440
+ }
441
+ // `pkcs5` is the historical option name; for AES's 16-byte block this is the
442
+ // generic PKCS#7/CMS-style block-padding rule on decrypt.
443
+ function validatePKCS(data, pkcs5) {
444
+ if (!pkcs5)
445
+ return data;
446
+ const len = data.length;
447
+ // RFC 5652 pads even empty / already-aligned inputs, so a valid padded
448
+ // ECB/CBC ciphertext is never empty when PKCS#7/CMS unpadding is enabled.
449
+ // AES-CBC/ECB ciphertext should be full blocks before unpadding
450
+ if (len === 0)
451
+ throw new Error('aes/pkcs7: empty ciphertext not allowed');
452
+ const lastByte = data[len - 1];
453
+ let valid = 1;
454
+ valid &= ((lastByte - 1) >>> 31) ^ 1; // pad >= 1
455
+ valid &= ((16 - lastByte) >>> 31) ^ 1; // pad <= 16
456
+ // Check exactly 16 tail bytes in constant-shape loop
457
+ // For i < pad: byte must equal pad
458
+ // For i >= pad: ignore byte
459
+ for (let i = 0; i < 16; i++) {
460
+ // const b = data[len - 1 - i];
461
+ const shouldCheck = (i - lastByte) >>> 31; // 1 if i < pad else 0
462
+ const eq = (data[len - 1 - i] ^ lastByte) === 0 ? 1 : 0; // 1 if equal
463
+ valid &= eq | (shouldCheck ^ 1); // pass if equal OR not checked
464
+ }
465
+ // if (invalidLen) throw new Error('aes/pkcs7: ciphertext length must be multiple of 16');
466
+ if (!valid)
467
+ throw new Error('aes/pkcs7: wrong padding');
468
+ return data.subarray(0, len - lastByte);
469
+ }
470
+ // ECB/CBC callers only pass the final short block here, so `left.length` is
471
+ // 0..15 and the helper always emits exactly one padded 16-byte block.
472
+ function padPCKS(left) {
473
+ const tmp = new Uint8Array(16);
474
+ const tmp32 = u32(tmp);
475
+ tmp.set(left);
476
+ const paddingByte = BLOCK_SIZE - left.length;
477
+ // RFC 5652 §6.3 fills the whole suffix with the padding length byte:
478
+ // e.g. `aa 0f..0f` for a 1-byte tail, or `10..10` for a full extra block.
479
+ for (let i = BLOCK_SIZE - paddingByte; i < BLOCK_SIZE; i++)
480
+ tmp[i] = paddingByte;
481
+ return tmp32;
482
+ }
483
+ /**
484
+ * **ECB** (Electronic Codebook): Deterministic encryption; identical plaintext blocks yield
485
+ * identical ciphertexts. Not secure due to pattern leakage.
486
+ * See {@link https://words.filippo.io/the-ecb-penguin/ | the AES Penguin}.
487
+ * @param key - AES key bytes.
488
+ * @param opts - Padding options. See {@link BlockOpts}.
489
+ * @returns Cipher instance with `encrypt()` and `decrypt()`.
490
+ * @example
491
+ * Shows the basic ECB encrypt call shape with a fresh key; avoid ECB in new designs.
492
+ *
493
+ * ```ts
494
+ * import { ecb } from './aes';
495
+ * import { randomBytes } from './utils';
496
+ * const key = randomBytes(16);
497
+ * const cipher = ecb(key);
498
+ * cipher.encrypt(new Uint8Array([1, 2, 3]));
499
+ * ```
500
+ */
501
+ export const ecb = /* @__PURE__ */ wrapCipher({ blockSize: 16 }, function aesecb(key, opts = {}) {
502
+ const pkcs5 = !opts.disablePadding;
503
+ return {
504
+ encrypt(plaintext, dst) {
505
+ const { b, o, out: _out } = validateBlockEncrypt(plaintext, pkcs5, dst);
506
+ const xk = expandKeyLE(key);
507
+ let i = 0;
508
+ for (; i + 4 <= b.length;) {
509
+ const { s0, s1, s2, s3 } = encrypt(xk, b[i + 0], b[i + 1], b[i + 2], b[i + 3]);
510
+ ((o[i++] = s0), (o[i++] = s1), (o[i++] = s2), (o[i++] = s3));
511
+ }
512
+ if (pkcs5) {
513
+ const tmp32 = padPCKS(plaintext.subarray(i * 4));
514
+ swap32IfBE(tmp32);
515
+ const { s0, s1, s2, s3 } = encrypt(xk, tmp32[0], tmp32[1], tmp32[2], tmp32[3]);
516
+ ((o[i++] = s0), (o[i++] = s1), (o[i++] = s2), (o[i++] = s3));
517
+ }
518
+ swap32IfBE(o);
519
+ clean(xk);
520
+ return _out;
521
+ },
522
+ decrypt(ciphertext, dst) {
523
+ validateBlockDecrypt(ciphertext);
524
+ const xk = expandKeyDecLE(key);
525
+ dst = getOutput(ciphertext.length, dst);
526
+ const toClean = [xk];
527
+ complexOverlapBytes(ciphertext, dst);
528
+ // Copy on BE or misaligned ciphertext so u32()/swap32IfBE()
529
+ // normalization never mutates caller bytes in place before decrypt().
530
+ if (!isLE || !isAligned32(ciphertext))
531
+ toClean.push((ciphertext = copyBytes(ciphertext)));
532
+ const b = u32(ciphertext);
533
+ const o = u32(dst);
534
+ swap32IfBE(b);
535
+ for (let i = 0; i + 4 <= b.length;) {
536
+ const { s0, s1, s2, s3 } = decrypt(xk, b[i + 0], b[i + 1], b[i + 2], b[i + 3]);
537
+ ((o[i++] = s0), (o[i++] = s1), (o[i++] = s2), (o[i++] = s3));
538
+ }
539
+ swap32IfBE(o);
540
+ clean(...toClean);
541
+ return validatePKCS(dst, pkcs5);
542
+ },
543
+ };
544
+ });
545
+ /**
546
+ * **CBC** (Cipher Block Chaining): Each plaintext block is XORed with the
547
+ * previous block of ciphertext before encryption.
548
+ * Hard to use: requires proper padding and an unpredictable IV. Unauthenticated: needs MAC.
549
+ * @param key - AES key bytes.
550
+ * @param iv - 16-byte unpredictable initialization vector.
551
+ * @param opts - Padding options. See {@link BlockOpts}.
552
+ * @returns Cipher instance with `encrypt()` and `decrypt()`.
553
+ * @example
554
+ * Encrypts a padded message with a fresh key and 16-byte IV.
555
+ *
556
+ * ```ts
557
+ * import { cbc } from './aes';
558
+ * import { randomBytes } from './utils';
559
+ * const key = randomBytes(16);
560
+ * const iv = randomBytes(16);
561
+ * const cipher = cbc(key, iv);
562
+ * cipher.encrypt(new Uint8Array([1, 2, 3]));
563
+ * ```
564
+ */
565
+ export const cbc = /* @__PURE__ */ wrapCipher({ blockSize: 16, nonceLength: 16 }, function aescbc(key, iv, opts = {}) {
566
+ const pkcs5 = !opts.disablePadding;
567
+ return {
568
+ encrypt(plaintext, dst) {
569
+ const xk = expandKeyLE(key);
570
+ const { b, o, out: _out } = validateBlockEncrypt(plaintext, pkcs5, dst);
571
+ let _iv = iv;
572
+ const toClean = [xk];
573
+ // Copy on BE or misaligned inputs so IV normalization and the mutable
574
+ // local chaining state never write back into caller IV bytes.
575
+ if (!isLE || !isAligned32(_iv))
576
+ toClean.push((_iv = copyBytes(_iv)));
577
+ const n32 = u32(_iv);
578
+ swap32IfBE(n32);
579
+ // prettier-ignore
580
+ let s0 = n32[0], s1 = n32[1], s2 = n32[2], s3 = n32[3];
581
+ let i = 0;
582
+ for (; i + 4 <= b.length;) {
583
+ ((s0 ^= b[i + 0]), (s1 ^= b[i + 1]), (s2 ^= b[i + 2]), (s3 ^= b[i + 3]));
584
+ ({ s0, s1, s2, s3 } = encrypt(xk, s0, s1, s2, s3));
585
+ ((o[i++] = s0), (o[i++] = s1), (o[i++] = s2), (o[i++] = s3));
586
+ }
587
+ if (pkcs5) {
588
+ const tmp32 = padPCKS(plaintext.subarray(i * 4));
589
+ swap32IfBE(tmp32);
590
+ ((s0 ^= tmp32[0]), (s1 ^= tmp32[1]), (s2 ^= tmp32[2]), (s3 ^= tmp32[3]));
591
+ ({ s0, s1, s2, s3 } = encrypt(xk, s0, s1, s2, s3));
592
+ ((o[i++] = s0), (o[i++] = s1), (o[i++] = s2), (o[i++] = s3));
593
+ }
594
+ swap32IfBE(o);
595
+ clean(...toClean);
596
+ return _out;
597
+ },
598
+ decrypt(ciphertext, dst) {
599
+ validateBlockDecrypt(ciphertext);
600
+ const xk = expandKeyDecLE(key);
601
+ let _iv = iv;
602
+ const toClean = [xk];
603
+ // Copy on BE or misaligned inputs so IV normalization and the mutable
604
+ // local chaining state never write back into caller IV bytes.
605
+ if (!isLE || !isAligned32(_iv))
606
+ toClean.push((_iv = copyBytes(_iv)));
607
+ const n32 = u32(_iv);
608
+ swap32IfBE(n32);
609
+ dst = getOutput(ciphertext.length, dst);
610
+ complexOverlapBytes(ciphertext, dst);
611
+ // Copy on BE or misaligned ciphertext so u32()/swap32IfBE()
612
+ // normalization never mutates caller bytes in place before decrypt().
613
+ if (!isLE || !isAligned32(ciphertext))
614
+ toClean.push((ciphertext = copyBytes(ciphertext)));
615
+ const b = u32(ciphertext);
616
+ const o = u32(dst);
617
+ swap32IfBE(b);
618
+ // prettier-ignore
619
+ let s0 = n32[0], s1 = n32[1], s2 = n32[2], s3 = n32[3];
620
+ for (let i = 0; i + 4 <= b.length;) {
621
+ // prettier-ignore
622
+ const ps0 = s0, ps1 = s1, ps2 = s2, ps3 = s3;
623
+ ((s0 = b[i + 0]), (s1 = b[i + 1]), (s2 = b[i + 2]), (s3 = b[i + 3]));
624
+ const { s0: o0, s1: o1, s2: o2, s3: o3 } = decrypt(xk, s0, s1, s2, s3);
625
+ ((o[i++] = o0 ^ ps0), (o[i++] = o1 ^ ps1), (o[i++] = o2 ^ ps2), (o[i++] = o3 ^ ps3));
626
+ }
627
+ swap32IfBE(o);
628
+ clean(...toClean);
629
+ return validatePKCS(dst, pkcs5);
630
+ },
631
+ };
632
+ });
633
+ /**
634
+ * CFB (CFB-128): Cipher Feedback Mode with 128-bit segments. The input for the
635
+ * block cipher is the previous cipher output.
636
+ * Unauthenticated: needs MAC.
637
+ * @param key - AES key bytes.
638
+ * @param iv - 16-byte unpredictable initialization vector.
639
+ * @returns Cipher instance with `encrypt()` and `decrypt()`.
640
+ * @example
641
+ * Encrypts a short message with feedback mode and a fresh key/IV pair.
642
+ *
643
+ * ```ts
644
+ * import { cfb } from './aes';
645
+ * import { randomBytes } from './utils';
646
+ * const key = randomBytes(16);
647
+ * const iv = randomBytes(16);
648
+ * const cipher = cfb(key, iv);
649
+ * cipher.encrypt(new Uint8Array([1, 2, 3]));
650
+ * ```
651
+ */
652
+ export const cfb = /* @__PURE__ */ wrapCipher({ blockSize: 16, nonceLength: 16 }, function aescfb(key, iv) {
653
+ function processCfb(src, isEncrypt, dst) {
654
+ abytes(src);
655
+ const srcLen = src.length;
656
+ dst = getOutput(srcLen, dst);
657
+ // CFB feeds back previous ciphertext, so overlapping src/dst could
658
+ // overwrite bytes that are still needed as the next feedback block.
659
+ if (overlapBytes(src, dst))
660
+ throw new Error('overlapping src and dst not supported.');
661
+ const xk = expandKeyLE(key);
662
+ let _iv = iv;
663
+ const toClean = [xk];
664
+ // Copy on BE or misaligned inputs so u32()/swap32IfBE() normalization
665
+ // never mutates caller IV/src bytes in place before CFB processing.
666
+ if (!isLE || !isAligned32(_iv))
667
+ toClean.push((_iv = copyBytes(_iv)));
668
+ if (!isLE || !isAligned32(src))
669
+ toClean.push((src = copyBytes(src)));
670
+ const src32 = u32(src);
671
+ const dst32 = u32(dst);
672
+ // NIST SP 800-38A §6.3 feeds back the previous ciphertext segment in
673
+ // both directions: encrypt reuses freshly written dst words, decrypt
674
+ // reuses the source ciphertext words.
675
+ const next32 = isEncrypt ? dst32 : src32;
676
+ const n32 = u32(_iv);
677
+ swap32IfBE(src32);
678
+ swap32IfBE(n32);
679
+ // prettier-ignore
680
+ let s0 = n32[0], s1 = n32[1], s2 = n32[2], s3 = n32[3];
681
+ for (let i = 0; i + 4 <= src32.length;) {
682
+ const { s0: e0, s1: e1, s2: e2, s3: e3 } = encrypt(xk, s0, s1, s2, s3);
683
+ dst32[i + 0] = src32[i + 0] ^ e0;
684
+ dst32[i + 1] = src32[i + 1] ^ e1;
685
+ dst32[i + 2] = src32[i + 2] ^ e2;
686
+ dst32[i + 3] = src32[i + 3] ^ e3;
687
+ ((s0 = next32[i++]), (s1 = next32[i++]), (s2 = next32[i++]), (s3 = next32[i++]));
688
+ }
689
+ // leftovers (less than block)
690
+ const start = BLOCK_SIZE * Math.floor(src32.length / BLOCK_SIZE32);
691
+ if (start < srcLen) {
692
+ // Byte-oriented API: for a final short tail, reuse the next CFB-128
693
+ // output block and XOR only the needed prefix. RFC 3826 §3.1.3 /
694
+ // §3.1.4 describes the same no-padding rule at bit granularity for a
695
+ // final r<=128 segment.
696
+ ({ s0, s1, s2, s3 } = encrypt(xk, s0, s1, s2, s3));
697
+ const tmp = new Uint32Array([s0, s1, s2, s3]);
698
+ swap32IfBE(tmp);
699
+ const buf = u8(tmp);
700
+ for (let i = start, pos = 0; i < srcLen; i++, pos++)
701
+ dst[i] = src[i] ^ buf[pos];
702
+ clean(buf);
703
+ }
704
+ swap32IfBE(dst32);
705
+ clean(...toClean);
706
+ return dst;
707
+ }
708
+ return {
709
+ encrypt: (plaintext, dst) => processCfb(plaintext, true, dst),
710
+ decrypt: (ciphertext, dst) => processCfb(ciphertext, false, dst),
711
+ };
712
+ });
713
+ // TODO: merge with chacha, however gcm has bitLen while chacha has byteLen
714
+ // `data` is the payload covered by the polynomial MAC: ciphertext for GCM,
715
+ // plaintext for GCM-SIV. Keep AAD/data/length as separate updates because
716
+ // GHASH/POLYVAL pad each call to block boundaries, so the chunks must match the
717
+ // spec-defined segments instead of arbitrary concatenation boundaries.
718
+ function computeTag(fn, isLE, key, data, AAD) {
719
+ const aadLength = AAD ? AAD.length : 0;
720
+ const h = fn.create(key, data.length + aadLength);
721
+ if (AAD)
722
+ h.update(AAD);
723
+ // u64Lengths() takes (dataBits, aadBits) but still serializes the final
724
+ // block as len(AAD) || len(data), matching both GCM and GCM-SIV.
725
+ const num = u64Lengths(8 * data.length, 8 * aadLength, isLE);
726
+ h.update(data);
727
+ h.update(num);
728
+ const res = h.digest();
729
+ clean(num);
730
+ return res;
731
+ }
732
+ /**
733
+ * **GCM** (Galois/Counter Mode): Combines CTR mode with polynomial MAC. Efficient and widely used.
734
+ * Not perfect:
735
+ * a) conservative key wear-out is `2**32` (4B) msgs.
736
+ * b) key wear-out under random nonces is even smaller: `2**23` (8M) messages for `2**-50` chance.
737
+ * c) MAC can be forged: see Poly1305 documentation.
738
+ * @param key - AES key bytes.
739
+ * @param nonce - Nonce bytes (12 recommended, minimum 8; other lengths use GHASH J0 derivation).
740
+ * @param AAD - Additional authenticated data.
741
+ * @returns AEAD cipher instance with a fixed 16-byte tag.
742
+ * @example
743
+ * Encrypts and authenticates plaintext with a fresh key and 12-byte nonce.
744
+ *
745
+ * ```ts
746
+ * import { gcm } from './aes';
747
+ * import { randomBytes } from './utils';
748
+ * const key = randomBytes(16);
749
+ * const nonce = randomBytes(12);
750
+ * const cipher = gcm(key, nonce);
751
+ * cipher.encrypt(new Uint8Array([1, 2, 3]));
752
+ * ```
753
+ */
754
+ export const gcm = /* @__PURE__ */ wrapCipher({ blockSize: 16, nonceLength: 12, tagLength: 16, varSizeNonce: true }, function aesgcm(key, nonce, AAD) {
755
+ // SP 800-38D lets implementations narrow supported IV lengths.
756
+ // This wrapper intentionally requires at least 8 bytes; OpenSSL accepts shorter IVs too.
757
+ // 12-byte nonces take the fast path; other allowed lengths use GHASH to derive J0.
758
+ if (nonce.length < 8)
759
+ throw new Error('aes/gcm: invalid nonce length');
760
+ const tagLength = 16;
761
+ function _computeTag(authKey, tagMask, data) {
762
+ const tag = computeTag(ghash, false, authKey, data, AAD);
763
+ for (let i = 0; i < tagMask.length; i++)
764
+ tag[i] ^= tagMask[i];
765
+ return tag;
766
+ }
767
+ function deriveKeys() {
768
+ const xk = expandKeyLE(key);
769
+ const authKey = EMPTY_BLOCK.slice();
770
+ const counter = EMPTY_BLOCK.slice();
771
+ ctr32(xk, false, counter, counter, authKey);
772
+ // NIST 800-38d, page 15: different behavior for 96-bit and non-96-bit nonces
773
+ if (nonce.length === 12) {
774
+ counter.set(nonce);
775
+ }
776
+ else {
777
+ const nonceLen = EMPTY_BLOCK.slice();
778
+ const view = createView(nonceLen);
779
+ view.setBigUint64(8, BigInt(nonce.length * 8), false);
780
+ // GHASH.update() pads each call to 16 bytes, so
781
+ // update(nonce).update(nonceLen) realizes
782
+ // IV || 0^s || 0^64 || [len(IV)]_64 for non-96-bit nonces.
783
+ // ghash(nonce || u64be(0) || u64be(nonceLen*8))
784
+ const g = ghash.create(authKey).update(nonce).update(nonceLen);
785
+ g.digestInto(counter); // digestInto doesn't trigger '.destroy'
786
+ g.destroy();
787
+ }
788
+ // GCTR_K(J0, 0^128) = E_K(J0); reusing ctr32() here extracts that tag
789
+ // mask and leaves `counter` advanced to inc32(J0) for payload GCTR.
790
+ const tagMask = ctr32(xk, false, counter, EMPTY_BLOCK);
791
+ return { xk, authKey, counter, tagMask };
792
+ }
793
+ return {
794
+ encrypt(plaintext) {
795
+ const { xk, authKey, counter, tagMask } = deriveKeys();
796
+ const out = new Uint8Array(plaintext.length + tagLength);
797
+ const toClean = [xk, authKey, counter, tagMask];
798
+ if (!isAligned32(plaintext))
799
+ toClean.push((plaintext = copyBytes(plaintext)));
800
+ ctr32(xk, false, counter, plaintext, out.subarray(0, plaintext.length));
801
+ const tag = _computeTag(authKey, tagMask, out.subarray(0, out.length - tagLength));
802
+ toClean.push(tag);
803
+ out.set(tag, plaintext.length);
804
+ clean(...toClean);
805
+ return out;
806
+ },
807
+ decrypt(ciphertext) {
808
+ const { xk, authKey, counter, tagMask } = deriveKeys();
809
+ const toClean = [xk, authKey, tagMask, counter];
810
+ if (!isAligned32(ciphertext))
811
+ toClean.push((ciphertext = copyBytes(ciphertext)));
812
+ const data = ciphertext.subarray(0, -tagLength);
813
+ const passedTag = ciphertext.subarray(-tagLength);
814
+ const tag = _computeTag(authKey, tagMask, data);
815
+ toClean.push(tag);
816
+ // NIST SP 800-38D §7.2 permits equivalent step orderings; verify the
817
+ // tag before CTR so unauthenticated plaintext is never materialized.
818
+ if (!equalBytes(tag, passedTag)) {
819
+ clean(...toClean);
820
+ throw new Error('aes/gcm: invalid ghash tag');
821
+ }
822
+ const out = ctr32(xk, false, counter, data);
823
+ clean(...toClean);
824
+ return out;
825
+ },
826
+ };
827
+ });
828
+ const limit = (name, min, max) => (value) => {
829
+ // Current AES-SIV/GCM-SIV callers pass protocol limits from RFC 8452 / RFC 5297,
830
+ // not arbitrary library-preference bounds.
831
+ // Callers feed Uint8Array.length values here, so safe-integer rejection
832
+ // does not exclude any representable input even when an RFC bound is larger.
833
+ if (!Number.isSafeInteger(value) || min > value || value > max) {
834
+ const minmax = '[' + min + '..' + max + ']';
835
+ throw new Error('' + name + ': expected value in range ' + minmax + ', got ' + value);
836
+ }
837
+ };
838
+ /**
839
+ * **SIV** (Synthetic IV): GCM with nonce-misuse resistance.
840
+ * Repeating nonces reveal only the fact plaintexts are identical.
841
+ * Also suffers from GCM issues: key wear-out limits & MAC forging.
842
+ * See {@link https://www.rfc-editor.org/rfc/rfc8452 | RFC 8452}.
843
+ * RFC 8452 defines 16-byte and 32-byte AES keys for this mode.
844
+ * This implementation also accepts 24-byte AES-192 keys as a local
845
+ * extension; see the inline comment next to `validateKeyLength(key)` below
846
+ * for the exact scope note.
847
+ * @param key - AES key bytes.
848
+ * @param nonce - 12-byte nonce.
849
+ * @param AAD - Additional authenticated data.
850
+ * @returns AEAD cipher instance.
851
+ * @example
852
+ * Encrypts and authenticates plaintext with a fresh key and nonce, while tolerating reuse.
853
+ *
854
+ * ```ts
855
+ * import { gcmsiv } from './aes';
856
+ * import { randomBytes } from './utils';
857
+ * const key = randomBytes(16);
858
+ * const nonce = randomBytes(12);
859
+ * const cipher = gcmsiv(key, nonce);
860
+ * cipher.encrypt(new Uint8Array([1, 2, 3]));
861
+ * ```
862
+ */
863
+ export const gcmsiv = /* @__PURE__ */ wrapCipher({ blockSize: 16, nonceLength: 12, tagLength: 16, varSizeNonce: true }, function aessiv(key, nonce, AAD) {
864
+ const tagLength = 16;
865
+ // From RFC 8452: Section 6
866
+ const AAD_LIMIT = limit('AAD', 0, 2 ** 36);
867
+ const PLAIN_LIMIT = limit('plaintext', 0, 2 ** 36);
868
+ const NONCE_LIMIT = limit('nonce', 12, 12);
869
+ const CIPHER_LIMIT = limit('ciphertext', 16, 2 ** 36 + 16);
870
+ abytes(key);
871
+ // RFC 8452 only standardizes 16-byte and 32-byte key-generating keys.
872
+ // The accepted 24-byte path is a local AES-192 extension outside the RFC-defined AEADs.
873
+ validateKeyLength(key);
874
+ NONCE_LIMIT(nonce.length);
875
+ if (AAD !== undefined)
876
+ AAD_LIMIT(AAD.length);
877
+ function deriveKeys() {
878
+ const xk = expandKeyLE(key);
879
+ const encKey = new Uint8Array(key.length);
880
+ const authKey = new Uint8Array(16);
881
+ const toClean = [xk, encKey];
882
+ let _nonce = nonce;
883
+ // Copy on BE or misaligned nonce so u32()/swap32IfBE() normalization
884
+ // never mutates caller nonce bytes before RFC 8452 key derivation.
885
+ if (!isLE || !isAligned32(_nonce))
886
+ toClean.push((_nonce = copyBytes(_nonce)));
887
+ const n32 = u32(_nonce);
888
+ swap32IfBE(n32);
889
+ // prettier-ignore
890
+ let s0 = 0, s1 = n32[0], s2 = n32[1], s3 = n32[2];
891
+ let counter = 0;
892
+ for (const derivedKey of [authKey, encKey].map(u32)) {
893
+ const d32 = u32(derivedKey);
894
+ for (let i = 0; i < d32.length; i += 2) {
895
+ // aes(u32le(0) || nonce)[:8] || aes(u32le(1) || nonce)[:8] ...
896
+ const { s0: o0, s1: o1 } = encrypt(xk, s0, s1, s2, s3);
897
+ d32[i + 0] = o0;
898
+ d32[i + 1] = o1;
899
+ s0 = ++counter; // increment counter inside state
900
+ }
901
+ swap32IfBE(d32);
902
+ }
903
+ const res = { authKey, encKey: expandKeyLE(encKey) };
904
+ // Cleanup
905
+ clean(...toClean);
906
+ return res;
907
+ }
908
+ function _computeTag(encKey, authKey, data) {
909
+ const tag = computeTag(polyval, true, authKey, data, AAD);
910
+ // Compute the expected tag by XORing S_s and the nonce, clearing the
911
+ // most significant bit of the last byte and encrypting with the
912
+ // message-encryption key.
913
+ for (let i = 0; i < 12; i++)
914
+ tag[i] ^= nonce[i];
915
+ tag[15] &= 0x7f; // Clear the highest bit
916
+ // encrypt tag as block
917
+ const t32 = u32(tag);
918
+ swap32IfBE(t32);
919
+ // prettier-ignore
920
+ let s0 = t32[0], s1 = t32[1], s2 = t32[2], s3 = t32[3];
921
+ ({ s0, s1, s2, s3 } = encrypt(encKey, s0, s1, s2, s3));
922
+ ((t32[0] = s0), (t32[1] = s1), (t32[2] = s2), (t32[3] = s3));
923
+ swap32IfBE(t32);
924
+ return tag;
925
+ }
926
+ // actual decrypt/encrypt of message.
927
+ function processSiv(encKey, tag, input) {
928
+ let block = copyBytes(tag);
929
+ // RFC 8452 §4 / §5 use the tag with the highest bit of the last byte
930
+ // forced to one as the initial AES-CTR counter block.
931
+ block[15] |= 0x80; // Force highest bit
932
+ const res = ctr32(encKey, true, block, input);
933
+ // Cleanup
934
+ clean(block);
935
+ return res;
936
+ }
937
+ return {
938
+ encrypt(plaintext) {
939
+ PLAIN_LIMIT(plaintext.length);
940
+ const { encKey, authKey } = deriveKeys();
941
+ const tag = _computeTag(encKey, authKey, plaintext);
942
+ const toClean = [encKey, authKey, tag];
943
+ if (!isAligned32(plaintext))
944
+ toClean.push((plaintext = copyBytes(plaintext)));
945
+ const out = new Uint8Array(plaintext.length + tagLength);
946
+ out.set(tag, plaintext.length);
947
+ out.set(processSiv(encKey, tag, plaintext));
948
+ // Cleanup
949
+ clean(...toClean);
950
+ return out;
951
+ },
952
+ decrypt(ciphertext) {
953
+ CIPHER_LIMIT(ciphertext.length);
954
+ const tag = ciphertext.subarray(-tagLength);
955
+ const { encKey, authKey } = deriveKeys();
956
+ const toClean = [encKey, authKey];
957
+ if (!isAligned32(ciphertext))
958
+ toClean.push((ciphertext = copyBytes(ciphertext)));
959
+ const plaintext = processSiv(encKey, tag, ciphertext.subarray(0, -tagLength));
960
+ const expectedTag = _computeTag(encKey, authKey, plaintext);
961
+ toClean.push(expectedTag);
962
+ // RFC 8452 §5: plaintext is unauthenticated here and MUST NOT be
963
+ // returned until the expected-tag check completes successfully.
964
+ if (!equalBytes(tag, expectedTag)) {
965
+ clean(...toClean);
966
+ throw new Error('invalid polyval tag');
967
+ }
968
+ // Cleanup
969
+ clean(...toClean);
970
+ return plaintext;
971
+ },
972
+ };
973
+ });
974
+ function isBytes32(a) {
975
+ // Plain `instanceof Uint32Array` is too strict for cross-realm expanded-key views.
976
+ // This is only a best-effort unsafe-export guard, not a provenance proof for `expandKeyLE`.
977
+ return (a instanceof Uint32Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint32Array'));
978
+ }
979
+ // Unsafe single-block helpers: mutate `block` in place and require its 16-byte
980
+ // Uint8Array view to be 4-byte aligned because `u32(block)` reinterprets it.
981
+ function encryptBlock(xk, block) {
982
+ abytes(block, 16, 'block');
983
+ if (!isBytes32(xk))
984
+ throw new Error('_encryptBlock accepts result of expandKeyLE');
985
+ const b32 = u32(block);
986
+ swap32IfBE(b32);
987
+ let { s0, s1, s2, s3 } = encrypt(xk, b32[0], b32[1], b32[2], b32[3]);
988
+ ((b32[0] = s0), (b32[1] = s1), (b32[2] = s2), (b32[3] = s3));
989
+ swap32IfBE(b32);
990
+ return block;
991
+ }
992
+ function decryptBlock(xk, block) {
993
+ abytes(block, 16, 'block');
994
+ if (!isBytes32(xk))
995
+ throw new Error('_decryptBlock accepts result of expandKeyLE');
996
+ const b32 = u32(block);
997
+ swap32IfBE(b32);
998
+ let { s0, s1, s2, s3 } = decrypt(xk, b32[0], b32[1], b32[2], b32[3]);
999
+ ((b32[0] = s0), (b32[1] = s1), (b32[2] = s2), (b32[3] = s3));
1000
+ swap32IfBE(b32);
1001
+ return block;
1002
+ }
1003
+ /**
1004
+ * AES-W (base for AESKW/AESKWP).
1005
+ * Specs:
1006
+ * {@link https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-38F.pdf | SP800-38F},
1007
+ * {@link https://www.rfc-editor.org/rfc/rfc3394 | RFC 3394},
1008
+ * {@link https://www.rfc-editor.org/rfc/rfc5649 | RFC 5649}.
1009
+ * Shared core mutates `out` in place; callers are responsible for prepending
1010
+ * the right IV/AIV and checking the recovered value after decrypt.
1011
+ */
1012
+ const AESW = {
1013
+ /*
1014
+ High-level pseudocode:
1015
+ ```
1016
+ A: u64 = IV
1017
+ out = []
1018
+ for (let i=0, ctr = 0; i<6; i++) {
1019
+ for (const chunk of chunks(plaintext, 8)) {
1020
+ A ^= swapEndianess(ctr++)
1021
+ [A, res] = chunks(encrypt(A || chunk), 8);
1022
+ out ||= res
1023
+ }
1024
+ }
1025
+ out = A || out
1026
+ ```
1027
+ Decrypt is the same, but reversed.
1028
+ */
1029
+ encrypt(kek, out) {
1030
+ // Current implementation keeps RFC 3394/5649 `t` in a u32-shaped counter,
1031
+ // so the shared core caps plaintext below 4 GiB even though the specs allow more.
1032
+ if (out.length >= 2 ** 32)
1033
+ throw new Error('plaintext should be less than 4gb');
1034
+ const xk = expandKeyLE(kek);
1035
+ // 16-byte `S = A || P[1]` is the RFC 5649 KWP special case for n=1;
1036
+ // KW callers never reach it because KW requires at least two plaintext semiblocks.
1037
+ if (out.length === 16)
1038
+ encryptBlock(xk, out);
1039
+ else {
1040
+ const o32 = u32(out);
1041
+ swap32IfBE(o32);
1042
+ // prettier-ignore
1043
+ let a0 = o32[0], a1 = o32[1]; // A
1044
+ for (let j = 0, ctr = 1; j < 6; j++) {
1045
+ for (let pos = 2; pos < o32.length; pos += 2, ctr++) {
1046
+ const { s0, s1, s2, s3 } = encrypt(xk, a0, a1, o32[pos], o32[pos + 1]);
1047
+ // A = MSB(64, B) ^ t where t = (n*j)+i. Under the 32-bit length cap
1048
+ // above, `t` fits in the low half of `[t]_64`, so xor only the low
1049
+ // 32 bits of A after converting `ctr` to network order.
1050
+ ((a0 = s0), (a1 = s1 ^ byteSwap(ctr)), (o32[pos] = s2), (o32[pos + 1] = s3));
1051
+ }
1052
+ }
1053
+ ((o32[0] = a0), (o32[1] = a1)); // out = A || out
1054
+ swap32IfBE(o32);
1055
+ }
1056
+ xk.fill(0);
1057
+ },
1058
+ decrypt(kek, out) {
1059
+ // Same implementation cap on the recovered plaintext length after
1060
+ // removing the 8-byte A/IV prefix.
1061
+ if (out.length - 8 >= 2 ** 32)
1062
+ throw new Error('ciphertext should be less than 4gb');
1063
+ const xk = expandKeyDecLE(kek);
1064
+ const chunks = out.length / 8 - 1; // first chunk is IV
1065
+ // `n = 2` semiblocks is the RFC 5649 KWP special case; KW ciphertexts
1066
+ // always have at least three semiblocks and therefore use the W^-1 loop.
1067
+ if (chunks === 1)
1068
+ decryptBlock(xk, out);
1069
+ else {
1070
+ const o32 = u32(out);
1071
+ swap32IfBE(o32);
1072
+ // prettier-ignore
1073
+ let a0 = o32[0], a1 = o32[1]; // A
1074
+ for (let j = 0, ctr = chunks * 6; j < 6; j++) {
1075
+ for (let pos = chunks * 2; pos >= 1; pos -= 2, ctr--) {
1076
+ a1 ^= byteSwap(ctr);
1077
+ const { s0, s1, s2, s3 } = decrypt(xk, a0, a1, o32[pos], o32[pos + 1]);
1078
+ ((a0 = s0), (a1 = s1), (o32[pos] = s2), (o32[pos + 1] = s3));
1079
+ }
1080
+ }
1081
+ ((o32[0] = a0), (o32[1] = a1));
1082
+ swap32IfBE(o32);
1083
+ }
1084
+ xk.fill(0);
1085
+ },
1086
+ };
1087
+ // RFC 3394 §2.2.3.1 / NIST SP 800-38F Algorithm 3 / Algorithm 4: KW prepends
1088
+ // the default 64-bit ICV1 and unwrap must verify the same value.
1089
+ const AESKW_IV = /* @__PURE__ */ new Uint8Array(8).fill(0xa6); // A6A6A6A6A6A6A6A6
1090
+ /**
1091
+ * AES-KW (key-wrap). Injects static IV into plaintext, adds counter, encrypts 6 times.
1092
+ * Reduces block size from 16 to 8 bytes.
1093
+ * Plaintext must be a non-empty multiple of 8 bytes with minimum 16 bytes.
1094
+ * 8-byte inputs use aeskwp.
1095
+ * Wrapped ciphertext must be a multiple of 8 bytes with minimum 24 bytes.
1096
+ * For padded version, use aeskwp.
1097
+ * See {@link https://www.rfc-editor.org/rfc/rfc3394/ | RFC 3394} and
1098
+ * {@link https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-38F.pdf | NIST SP 800-38F}.
1099
+ * @param kek - AES key-encryption key.
1100
+ * @returns Key-wrap cipher instance.
1101
+ * As with other `wrapCipher(...)` wrappers, `encrypt()` is single-use per
1102
+ * instance.
1103
+ * @example
1104
+ * Wraps a 128-bit content-encryption key with a fresh key-encryption key.
1105
+ *
1106
+ * ```ts
1107
+ * import { aeskw } from './aes';
1108
+ * import { randomBytes } from './utils';
1109
+ * const kek = randomBytes(16);
1110
+ * const cek = randomBytes(16);
1111
+ * const wrap = aeskw(kek);
1112
+ * wrap.encrypt(cek);
1113
+ * ```
1114
+ */
1115
+ export const aeskw = /* @__PURE__ */ wrapCipher({ blockSize: 8 }, (kek) => ({
1116
+ encrypt(plaintext) {
1117
+ if (!plaintext.length || plaintext.length % 8 !== 0)
1118
+ throw new Error('invalid plaintext length');
1119
+ // RFC 3394 / NIST SP 800-38F define KW only for >=2 plaintext
1120
+ // semiblocks; the 1-semiblock case belongs to RFC 5649 KWP.
1121
+ if (plaintext.length === 8)
1122
+ throw new Error('8-byte keys not allowed in AESKW, use AESKWP instead');
1123
+ const out = concatBytes(AESKW_IV, plaintext);
1124
+ AESW.encrypt(kek, out);
1125
+ return out;
1126
+ },
1127
+ decrypt(ciphertext) {
1128
+ // ciphertext must be at least 24 bytes and a multiple of 8 bytes
1129
+ // 24 because should have at least two block (1 iv + 2).
1130
+ // Replace with 16 to enable '8-byte keys'
1131
+ if (ciphertext.length % 8 !== 0 || ciphertext.length < 3 * 8)
1132
+ throw new Error('invalid ciphertext length');
1133
+ // AESW.decrypt() mutates its buffer in place, so keep caller ciphertext
1134
+ // immutable across the unwrap, ICV1 check, and IV scrubbing below.
1135
+ const out = copyBytes(ciphertext);
1136
+ AESW.decrypt(kek, out);
1137
+ if (!equalBytes(out.subarray(0, 8), AESKW_IV))
1138
+ throw new Error('integrity check failed');
1139
+ out.subarray(0, 8).fill(0); // ciphertext.subarray(0, 8) === IV, but we clean it anyway
1140
+ return out.subarray(8);
1141
+ },
1142
+ }));
1143
+ /*
1144
+ We don't support 8-byte keys. The rabbit hole:
1145
+
1146
+ - Wycheproof says: "NIST SP 800-38F does not define the wrapping of 8 byte keys.
1147
+ RFC 3394 Section 2 on the other hand specifies that 8 byte keys are wrapped
1148
+ by directly encrypting one block with AES."
1149
+ - {@link https://github.com/C2SP/wycheproof/blob/master/doc/key_wrap.md | Wycheproof key-wrap note}
1150
+ - "RFC 3394 specifies in Section 2, that the input for the key wrap
1151
+ algorithm must be at least two blocks and otherwise the constant
1152
+ field and key are simply encrypted with ECB as a single block"
1153
+ - What RFC 3394 actually says (in Section 2):
1154
+ - "Before being wrapped, the key data is parsed into n blocks of 64 bits.
1155
+ The only restriction the key wrap algorithm places on n is that n be
1156
+ at least two"
1157
+ - "For key data with length less than or equal to 64 bits, the constant
1158
+ field used in this specification and the key data form a single
1159
+ 128-bit codebook input making this key wrap unnecessary."
1160
+ - Which means "assert(n >= 2)" and "use something else for 8 byte keys"
1161
+ - NIST SP800-38F actually prohibits 8-byte in "5.3.1 Mandatory Limits".
1162
+ It states that plaintext for KW should be "2 to 2^54 -1 semiblocks".
1163
+ - So, where does "directly encrypt single block with AES" come from?
1164
+ - Not RFC 3394. Pseudocode of key wrap in 2.2 explicitly uses
1165
+ loop of 6 for any code path
1166
+ - There is a weird W3C spec:
1167
+ {@link https://www.w3.org/TR/2002/REC-xmlenc-core-20021210/Overview.html#kw-aes128 | XML Encryption AES key-wrap section}
1168
+ - This spec is outdated, as admitted by Wycheproof authors
1169
+ - There is RFC 5649 for padded key wrap, which is padding construction on
1170
+ top of AESKW. In '4.1.2' it says: "If the padded plaintext contains exactly
1171
+ eight octets, then prepend the AIV as defined in Section 3 above to P[1] and
1172
+ encrypt the resulting 128-bit block using AES in ECB mode [Modes] with key
1173
+ K (the KEK). In this case, the output is two 64-bit blocks C[0] and C[1]:"
1174
+ - Browser subtle crypto is actually crashes on wrapping keys less than 16 bytes:
1175
+ `Error: error:1C8000E6:Provider routines::invalid input length]
1176
+ { opensslErrorStack: [ 'error:030000BD:digital envelope routines::update error' ]`
1177
+
1178
+ In the end, seems like a bug in Wycheproof.
1179
+ The 8-byte check can be easily disabled inside of AES_W.
1180
+ */
1181
+ // RFC 5649 §3 / NIST SP 800-38F Algorithm 5 / Algorithm 6: KWP uses ICV2 as
1182
+ // the high 32 bits of the AIV; the low 32 bits carry the MLI in network order.
1183
+ const AESKWP_IV = 0xa65959a6; // single u32le value
1184
+ /**
1185
+ * AES-KW, but with padding and allows random keys.
1186
+ * Uses the RFC 5649 alternative initial value; the second u32 stores the
1187
+ * 32-bit MLI in network order.
1188
+ * Wrapped ciphertext must be at least 16 bytes; malformed lengths are
1189
+ * rejected during AIV/padding checks.
1190
+ * See {@link https://www.rfc-editor.org/rfc/rfc5649 | RFC 5649}.
1191
+ * @param kek - AES key-encryption key.
1192
+ * @returns Padded key-wrap cipher instance.
1193
+ * @example
1194
+ * Wraps a short key blob using the padded variant and a fresh key-encryption key.
1195
+ *
1196
+ * ```ts
1197
+ * import { aeskwp } from './aes';
1198
+ * import { randomBytes } from './utils';
1199
+ * const kek = randomBytes(16);
1200
+ * const wrap = aeskwp(kek);
1201
+ * wrap.encrypt(new Uint8Array([1, 2, 3]));
1202
+ * ```
1203
+ */
1204
+ export const aeskwp = /* @__PURE__ */ wrapCipher({ blockSize: 8 }, (kek) => ({
1205
+ encrypt(plaintext) {
1206
+ if (!plaintext.length)
1207
+ throw new Error('invalid plaintext length');
1208
+ const padded = Math.ceil(plaintext.length / 8) * 8;
1209
+ const out = new Uint8Array(8 + padded);
1210
+ out.set(plaintext, 8);
1211
+ const out32 = u32(out);
1212
+ out32[0] = swap8IfBE(AESKWP_IV);
1213
+ // RFC 5649 §3: the low 32 bits of the AIV carry the octet-length MLI in
1214
+ // network order, even though this buffer is addressed through LE u32s.
1215
+ out32[1] = swap8IfBE(byteSwap(plaintext.length));
1216
+ AESW.encrypt(kek, out);
1217
+ return out;
1218
+ },
1219
+ decrypt(ciphertext) {
1220
+ // 16 because should have at least one block
1221
+ if (ciphertext.length < 16)
1222
+ throw new Error('invalid ciphertext length');
1223
+ // AESW.decrypt() mutates its buffer in place, so keep caller ciphertext
1224
+ // immutable across the unwrap, AIV checks, and IV scrubbing below.
1225
+ const out = copyBytes(ciphertext);
1226
+ const o32 = u32(out);
1227
+ AESW.decrypt(kek, out);
1228
+ const len = byteSwap(swap8IfBE(o32[1])) >>> 0;
1229
+ const padded = Math.ceil(len / 8) * 8;
1230
+ if (swap8IfBE(o32[0]) !== AESKWP_IV || out.length - 8 !== padded)
1231
+ throw new Error('integrity check failed');
1232
+ // RFC 5649 §3 / NIST SP 800-38F Algorithm 6: recovered padding length
1233
+ // must be in [0,7], and every recovered pad octet must be zero.
1234
+ for (let i = len; i < padded; i++)
1235
+ if (out[8 + i] !== 0)
1236
+ throw new Error('integrity check failed');
1237
+ out.subarray(0, 8).fill(0); // ciphertext.subarray(0, 8) === IV, but we clean it anyway
1238
+ return out.subarray(8, 8 + len);
1239
+ },
1240
+ }));
1241
+ class _AesCtrDRBG {
1242
+ blockLen;
1243
+ key;
1244
+ nonce;
1245
+ state;
1246
+ reseedCnt;
1247
+ constructor(keyLen, seed, personalization) {
1248
+ this.blockLen = ctr.blockSize;
1249
+ const keyLenBytes = keyLen / 8;
1250
+ const nonceLen = 16;
1251
+ // Store the full seedlen state as key || V so CTR_DRBG_Update-style steps
1252
+ // can rewrite the entire internal state in place.
1253
+ this.state = new Uint8Array(keyLenBytes + nonceLen);
1254
+ this.key = this.state.subarray(0, keyLenBytes);
1255
+ this.nonce = this.state.subarray(keyLenBytes, keyLenBytes + nonceLen);
1256
+ this.reseedCnt = 1;
1257
+ // Keep the stored counter one step ahead of SP 800-90A's formal V so
1258
+ // ctr(key, nonce) uses the next counter block directly.
1259
+ incBytes(this.nonce, false, 1);
1260
+ this.addEntropy(seed, personalization);
1261
+ }
1262
+ update(data) {
1263
+ // cannot re-use state here, because we will wipe current key
1264
+ ctr(this.key, this.nonce).encrypt(new Uint8Array(this.state.length), this.state);
1265
+ if (data) {
1266
+ abytes(data);
1267
+ // CTR_DRBG without a derivation function pads shorter additional_input
1268
+ // with zeros to seedlen, so XOR only the provided prefix here.
1269
+ for (let i = 0; i < data.length; i++)
1270
+ this.state[i] ^= data[i];
1271
+ }
1272
+ // Keep storing V+1 so the next ctr(key, nonce) call starts from the
1273
+ // spec's post-update counter state.
1274
+ incBytes(this.nonce, false, 1);
1275
+ }
1276
+ // Optional `info` is additional input XORed into the reseed block and is
1277
+ // limited to the internal state width.
1278
+ addEntropy(seed, info) {
1279
+ abytes(seed, this.state.length, 'seed');
1280
+ // Copy caller entropy before XORing in personalization/additional input,
1281
+ // then wipe the mixed seed material after CTR_DRBG_Update consumes it.
1282
+ const _seed = seed.slice();
1283
+ if (info) {
1284
+ abytes(info);
1285
+ if (info.length > _seed.length)
1286
+ throw new Error('info length is too big');
1287
+ for (let i = 0; i < info.length; i++)
1288
+ _seed[i] ^= info[i];
1289
+ }
1290
+ this.update(_seed);
1291
+ _seed.fill(0);
1292
+ this.reseedCnt = 1;
1293
+ }
1294
+ // Optional `info` is additional input for the pre/post-update steps; bytes
1295
+ // SP 800-90A Rev. 1 CTR_DRBG without a derivation function limits
1296
+ // additional_input to seedlen, which is exactly this internal state width.
1297
+ randomBytes(len, info) {
1298
+ anumber(len);
1299
+ // SP 800-90A Table 3 caps AES CTR_DRBG requests at 2^16 bits = 65536 bytes.
1300
+ if (len > 2 ** 16)
1301
+ throw new Error('requested output is too big');
1302
+ // The spec allows generate while reseed_counter == reseed_interval and increments afterwards.
1303
+ if (this.reseedCnt > 2 ** 48)
1304
+ throw new Error('entropy exhausted');
1305
+ if (info) {
1306
+ abytes(info);
1307
+ if (info.length > this.state.length)
1308
+ throw new Error('info length is too big');
1309
+ this.update(info);
1310
+ }
1311
+ const res = new Uint8Array(len);
1312
+ ctr(this.key, this.nonce).encrypt(res, res);
1313
+ incBytes(this.nonce, false, Math.ceil(len / this.blockLen));
1314
+ this.update(info);
1315
+ this.reseedCnt++;
1316
+ return res;
1317
+ }
1318
+ // Zeroes the current state and resets the counter, but does not make the
1319
+ // instance unusable: later calls continue from the zeroed state.
1320
+ clean() {
1321
+ // `key` and `nonce` alias this backing buffer, so one fill wipes the full
1322
+ // secret state in place.
1323
+ this.state.fill(0);
1324
+ this.reseedCnt = 0;
1325
+ }
1326
+ }
1327
+ // Internal helper for the exported 128-bit and 256-bit aliases; other key
1328
+ // lengths are not validated here.
1329
+ const createAesDrbg = (keyLen) => {
1330
+ return (seed, personalization = undefined) => new _AesCtrDRBG(keyLen, seed, personalization);
1331
+ };
1332
+ /**
1333
+ * AES-CTR DRBG 128-bit - CSPRNG (cryptographically secure pseudorandom number generator).
1334
+ * It's best to limit usage to non-production, non-critical cases: for example, test-only.
1335
+ * @param seed - Initial 32-byte entropy input.
1336
+ * @param personalization - Optional personalization string.
1337
+ * @returns Seeded DRBG instance. The concrete methods also accept optional additional-input bytes.
1338
+ * @example
1339
+ * Seeds the test-only AES-CTR DRBG from fresh entropy and reads bytes from it.
1340
+ *
1341
+ * ```ts
1342
+ * import { rngAesCtrDrbg128 } from './aes';
1343
+ * import { randomBytes } from './utils';
1344
+ * const seed = randomBytes(32);
1345
+ * const prg = rngAesCtrDrbg128(seed);
1346
+ * prg.randomBytes(8);
1347
+ * ```
1348
+ */
1349
+ export const rngAesCtrDrbg128 = /* @__PURE__ */ createAesDrbg(128);
1350
+ /**
1351
+ * AES-CTR DRBG 256-bit - CSPRNG (cryptographically secure pseudorandom number generator).
1352
+ * It's best to limit usage to non-production, non-critical cases: for example, test-only.
1353
+ * @param seed - Initial 48-byte entropy input.
1354
+ * @param personalization - Optional personalization string.
1355
+ * @returns Seeded DRBG instance. The concrete methods also accept optional additional-input bytes.
1356
+ * @example
1357
+ * Seeds the test-only AES-CTR DRBG from fresh entropy and reads bytes from it.
1358
+ *
1359
+ * ```ts
1360
+ * import { rngAesCtrDrbg256 } from './aes';
1361
+ * import { randomBytes } from './utils';
1362
+ * const seed = randomBytes(48);
1363
+ * const prg = rngAesCtrDrbg256(seed);
1364
+ * prg.randomBytes(8);
1365
+ * ```
1366
+ */
1367
+ export const rngAesCtrDrbg256 = /* @__PURE__ */ createAesDrbg(256);
1368
+ //#region CMAC
1369
+ /**
1370
+ * Left-shift by one bit and conditionally XOR with 0x87:
1371
+ * ```
1372
+ * if MSB(L) is equal to 0
1373
+ * then K1 := L << 1;
1374
+ * else K1 := (L << 1) XOR const_Rb;
1375
+ * ```
1376
+ *
1377
+ * Specs:
1378
+ * {@link https://www.rfc-editor.org/rfc/rfc4493.html#section-2.3 | RFC 4493 Section 2.3},
1379
+ * {@link https://datatracker.ietf.org/doc/html/rfc5297.html#section-2.3 | RFC 5297 Section 2.3}
1380
+ *
1381
+ * @returns modified `block` (for chaining)
1382
+ */
1383
+ function dbl(block) {
1384
+ let carry = 0;
1385
+ // Left shift by 1 bit
1386
+ for (let i = BLOCK_SIZE - 1; i >= 0; i--) {
1387
+ const newCarry = (block[i] & 0x80) >>> 7;
1388
+ block[i] = (block[i] << 1) | carry;
1389
+ carry = newCarry;
1390
+ }
1391
+ // XOR with 0x87 if there was a carry from the most significant bit
1392
+ if (carry) {
1393
+ // RFC 4493 §2.3 / RFC 5297 §2.1: 0x87 is const_Rb for doubling in the
1394
+ // CMAC/S2V finite field with primitive polynomial x^128 + x^7 + x^2 + x + 1.
1395
+ block[BLOCK_SIZE - 1] ^= 0x87;
1396
+ }
1397
+ return block;
1398
+ }
1399
+ /**
1400
+ * `a XOR b`, running in-place on `a`.
1401
+ * @param a left operand and output
1402
+ * @param b right operand
1403
+ * @returns `a` (for chaining)
1404
+ */
1405
+ function xorBlock(a, b) {
1406
+ if (a.length !== b.length)
1407
+ throw new Error('xorBlock: blocks must have same length');
1408
+ for (let i = 0; i < a.length; i++) {
1409
+ a[i] = a[i] ^ b[i];
1410
+ }
1411
+ return a;
1412
+ }
1413
+ /**
1414
+ * xorend as defined in
1415
+ * {@link https://datatracker.ietf.org/doc/html/rfc5297.html#section-2.1 | RFC 5297 Section 2.1}.
1416
+ *
1417
+ * ```
1418
+ * leftmost(A, len(A)-len(B)) || (rightmost(A, len(B)) xor B)
1419
+ * ```
1420
+ *
1421
+ * Mutates `a` in place so the left prefix stays untouched and only the
1422
+ * rightmost `len(B)` bytes are xored with `b`.
1423
+ */
1424
+ function xorend(a, b) {
1425
+ if (b.length > a.length) {
1426
+ throw new Error('xorend: len(B) must be less than or equal to len(A)');
1427
+ }
1428
+ // keep leftmost part of `a` unchanged
1429
+ // and xor only the rightmost part:
1430
+ const offset = a.length - b.length;
1431
+ for (let i = 0; i < b.length; i++) {
1432
+ a[offset + i] = a[offset + i] ^ b[i];
1433
+ }
1434
+ return a;
1435
+ }
1436
+ /**
1437
+ * Internal CMAC class.
1438
+ */
1439
+ class _CMAC {
1440
+ blockLen = BLOCK_SIZE;
1441
+ outputLen = BLOCK_SIZE;
1442
+ // CMAC can only decide between `K1` and `K2` once the true final block is known,
1443
+ // so updates process older blocks eagerly but keep one pending block buffered.
1444
+ buffer;
1445
+ pos;
1446
+ finished;
1447
+ destroyed;
1448
+ k1;
1449
+ k2;
1450
+ x;
1451
+ xk;
1452
+ constructor(key) {
1453
+ abytes(key);
1454
+ validateKeyLength(key);
1455
+ this.xk = expandKeyLE(key);
1456
+ this.buffer = new Uint8Array(BLOCK_SIZE);
1457
+ this.pos = 0;
1458
+ this.finished = false;
1459
+ this.destroyed = false;
1460
+ this.x = new Uint8Array(BLOCK_SIZE);
1461
+ // L = AES_encrypt(K, const_Zero)
1462
+ const L = new Uint8Array(BLOCK_SIZE);
1463
+ encryptBlock(this.xk, L);
1464
+ // Generate subkeys K1 and K2 from the main key according to
1465
+ // {@link https://www.rfc-editor.org/rfc/rfc4493.html#section-2.3 | RFC 4493 Section 2.3}
1466
+ // K1
1467
+ this.k1 = dbl(L);
1468
+ this.k2 = dbl(new Uint8Array(this.k1));
1469
+ }
1470
+ process(data) {
1471
+ // RFC 4493 §2.4 step 6 loop body: Y := X XOR M_i; X := AES-128(K, Y).
1472
+ xorBlock(this.x, data);
1473
+ encryptBlock(this.xk, this.x);
1474
+ }
1475
+ update(data) {
1476
+ if (this.destroyed)
1477
+ throw new Error('Hash instance has been destroyed');
1478
+ if (this.finished)
1479
+ throw new Error('Hash#digest() has already been called');
1480
+ abytes(data);
1481
+ let pos = 0;
1482
+ if (this.pos) {
1483
+ const take = Math.min(BLOCK_SIZE - this.pos, data.length);
1484
+ this.buffer.set(data.subarray(0, take), this.pos);
1485
+ this.pos += take;
1486
+ pos = take;
1487
+ if (this.pos === BLOCK_SIZE && pos < data.length) {
1488
+ this.process(this.buffer);
1489
+ this.pos = 0;
1490
+ }
1491
+ }
1492
+ // Keep one complete block buffered: an exact 16-byte tail may still be
1493
+ // M_n, and digestInto() must decide there whether RFC 4493 uses K1 or K2.
1494
+ while (pos + BLOCK_SIZE < data.length) {
1495
+ this.process(data.subarray(pos, pos + BLOCK_SIZE));
1496
+ pos += BLOCK_SIZE;
1497
+ }
1498
+ if (pos < data.length) {
1499
+ this.buffer.set(data.subarray(pos), 0);
1500
+ this.pos = data.length - pos;
1501
+ }
1502
+ return this;
1503
+ }
1504
+ // See {@link https://www.rfc-editor.org/rfc/rfc4493.html#section-2.4 | RFC 4493 Section 2.4}.
1505
+ digestInto(out) {
1506
+ if (this.destroyed)
1507
+ throw new Error('Hash instance has been destroyed');
1508
+ if (this.finished)
1509
+ throw new Error('Hash#digest() has already been called');
1510
+ // `digestInto(out)` is the no-allocation fast path, so AES block re-use below
1511
+ // requires a 32-bit-aligned caller buffer instead of hidden temp copies.
1512
+ aoutput(out, this, true);
1513
+ this.finished = true;
1514
+ // `digestInto()` accepts out.length >= outputLen, so only the first block stores the tag.
1515
+ const view = out.subarray(0, this.outputLen);
1516
+ let last = new Uint8Array(BLOCK_SIZE);
1517
+ if (this.pos === BLOCK_SIZE) {
1518
+ // M_last := M_n XOR K1;
1519
+ last.set(this.buffer);
1520
+ xorBlock(last, this.k1);
1521
+ }
1522
+ else {
1523
+ // M_last := padding(M_n) XOR K2;
1524
+ //
1525
+ // [...] padding(x) is the concatenation of x and a single '1',
1526
+ // followed by the minimum number of '0's, so that the total length is
1527
+ // equal to 128 bits.
1528
+ last.set(this.buffer.subarray(0, this.pos));
1529
+ last[this.pos] = 0x80; // single '1' bit
1530
+ xorBlock(last, this.k2);
1531
+ }
1532
+ view.set(this.x); // X := AES_CBC(K, M_1..M_{n-1})
1533
+ xorBlock(view, last); // Y := X XOR M_last
1534
+ encryptBlock(this.xk, view); // T := AES-128(K, Y)
1535
+ clean(last);
1536
+ }
1537
+ digest() {
1538
+ const { buffer, outputLen } = this;
1539
+ this.digestInto(buffer);
1540
+ // Copy out before destroy() wipes the internal digest buffer in place.
1541
+ const res = buffer.slice(0, outputLen);
1542
+ this.destroy();
1543
+ return res;
1544
+ }
1545
+ destroy() {
1546
+ const { buffer, destroyed, x, xk, k1, k2 } = this;
1547
+ if (destroyed)
1548
+ return;
1549
+ this.destroyed = true;
1550
+ // Wipe the buffered tail, chaining value, expanded AES key, and both CMAC subkeys.
1551
+ clean(buffer, x, xk, k1, k2);
1552
+ }
1553
+ }
1554
+ /**
1555
+ * AES-CMAC (Cipher-based Message Authentication Code).
1556
+ * Specs: {@link https://www.rfc-editor.org/rfc/rfc4493.html | RFC 4493}.
1557
+ * @param msg - Message bytes to authenticate.
1558
+ * @param key - AES key bytes.
1559
+ * @returns 16-byte authentication tag. `cmac.create(...)` follows the same incremental MAC shape as
1560
+ * the other keyed helpers in this repo, including `blockLen`,
1561
+ * `outputLen`, `digestInto()` and `destroy()`.
1562
+ * @example
1563
+ * Authenticates a message with AES-CMAC and a fresh key.
1564
+ *
1565
+ * ```ts
1566
+ * import { cmac } from './aes';
1567
+ * import { randomBytes } from './utils';
1568
+ * const key = randomBytes(16);
1569
+ * cmac(new Uint8Array(), key);
1570
+ * ```
1571
+ */
1572
+ // The 16-byte probe key is only used to read static metadata; runtime CMAC
1573
+ // still accepts AES-128/192/256 keys.
1574
+ export const cmac = /* @__PURE__ */ wrapMacConstructor(16, (key) => new _CMAC(key));
1575
+ /**
1576
+ * S2V (Synthetic Initialization Vector) function as described in
1577
+ * {@link https://datatracker.ietf.org/doc/html/rfc5297.html#section-2.4 | RFC 5297 Section 2.4}.
1578
+ *
1579
+ * ```
1580
+ * S2V(K, S1, ..., Sn) {
1581
+ * if n = 0 then
1582
+ * return V = AES-CMAC(K, <one>)
1583
+ * fi
1584
+ * D = AES-CMAC(K, <zero>)
1585
+ * for i = 1 to n-1 do
1586
+ * D = dbl(D) xor AES-CMAC(K, Si)
1587
+ * done
1588
+ * if len(Sn) >= 128 then
1589
+ * T = Sn xorend D
1590
+ * else
1591
+ * T = dbl(D) xor pad(Sn)
1592
+ * fi
1593
+ * return V = AES-CMAC(K, T)
1594
+ * }
1595
+ * ```
1596
+ *
1597
+ * S2V takes a key and a vector of strings S1, S2, ..., Sn and returns a 128-bit string.
1598
+ * The S2V function is used to generate a synthetic IV for AES-SIV.
1599
+ *
1600
+ * @param key - AES key (128, 192, or 256 bits)
1601
+ * @param strings - Array of byte arrays to process
1602
+ * @returns 128-bit synthetic IV
1603
+ */
1604
+ function s2v(key, strings) {
1605
+ validateKeyLength(key);
1606
+ const len = strings.length;
1607
+ if (len > 127) {
1608
+ // RFC 5297 §7 only proves S2V secure for at most 127 components; SIV
1609
+ // spends one of those on the plaintext, leaving at most 126 AAD inputs.
1610
+ throw new Error('s2v: number of input strings must be less than or equal to 127');
1611
+ }
1612
+ if (len === 0)
1613
+ return cmac(ONE_BLOCK, key);
1614
+ // D = AES-CMAC(K, <zero>)
1615
+ let d = cmac(EMPTY_BLOCK, key);
1616
+ // for i = 1 to n-1 do
1617
+ // D = dbl(D) xor AES-CMAC(K, Si)
1618
+ for (let i = 0; i < len - 1; i++) {
1619
+ dbl(d);
1620
+ const cmacResult = cmac(strings[i], key);
1621
+ xorBlock(d, cmacResult);
1622
+ clean(cmacResult);
1623
+ }
1624
+ const s_n = strings[len - 1];
1625
+ // Earlier components are validated through cmac(...); validate the final one explicitly because
1626
+ // the Uint8Array.from()/set() paths below would otherwise coerce array-like inputs silently.
1627
+ abytes(s_n);
1628
+ let t;
1629
+ // if len(Sn) >= 128 then
1630
+ if (s_n.byteLength >= BLOCK_SIZE) {
1631
+ // T = Sn xorend D
1632
+ t = xorend(Uint8Array.from(s_n), d);
1633
+ }
1634
+ else {
1635
+ // pad(Sn):
1636
+ const paddedSn = new Uint8Array(BLOCK_SIZE);
1637
+ paddedSn.set(s_n);
1638
+ paddedSn[s_n.length] = 0x80; // padding: 0x80 followed by zeros
1639
+ // T = dbl(D) xor pad(Sn)
1640
+ t = xorBlock(dbl(d), paddedSn);
1641
+ clean(paddedSn);
1642
+ }
1643
+ // V = AES-CMAC(K, T)
1644
+ const result = cmac(t, key);
1645
+ clean(d, t);
1646
+ return result;
1647
+ }
1648
+ /**
1649
+ * Use `gcmsiv` or `aessiv`.
1650
+ * @returns Never; always throws with the migration hint.
1651
+ * @throws If called; `siv()` is a removed v1 alias. {@link Error}
1652
+ * @example
1653
+ * `siv()` was removed in v2; use `gcmsiv()` for nonce-based SIV instead.
1654
+ *
1655
+ * ```ts
1656
+ * import { gcmsiv } from './aes';
1657
+ * import { randomBytes } from './utils';
1658
+ * const key = randomBytes(16);
1659
+ * const nonce = randomBytes(12);
1660
+ * const cipher = gcmsiv(key, nonce);
1661
+ * cipher.encrypt(new Uint8Array([1, 2, 3]));
1662
+ * ```
1663
+ */
1664
+ export const siv = () => {
1665
+ throw new Error('"siv" from v1 is now "gcmsiv"');
1666
+ };
1667
+ /**
1668
+ * **SIV**: Synthetic Initialization Vector (SIV) Authenticated Encryption
1669
+ * Nonce is derived from the plaintext and AAD using the S2V function.
1670
+ * Supports at most 126 AAD components. RFC 5297 nonce-based use is expressed by
1671
+ * passing the nonce as the final AAD component before the plaintext.
1672
+ * See {@link https://datatracker.ietf.org/doc/html/rfc5297.html | RFC 5297}.
1673
+ * @param key - 32-byte, 48-byte, or 64-byte key.
1674
+ * @param AAD - Additional authenticated data chunks (up to 126).
1675
+ * @returns AEAD cipher instance.
1676
+ * @example
1677
+ * Authenticates and encrypts plaintext with a fresh key without requiring unique nonces.
1678
+ *
1679
+ * ```ts
1680
+ * import { aessiv } from './aes';
1681
+ * import { randomBytes } from './utils';
1682
+ * const key = randomBytes(32);
1683
+ * const cipher = aessiv(key);
1684
+ * cipher.encrypt(new Uint8Array([1, 2, 3]));
1685
+ * ```
1686
+ */
1687
+ export const aessiv = /* @__PURE__ */ wrapCipher({ blockSize: 16, tagLength: 16 }, function aessiv(key, ...AAD) {
1688
+ // From RFC 5297: Section 6.1, 6.2, 6.3:
1689
+ const PLAIN_LIMIT = limit('plaintext', 0, 2 ** 132);
1690
+ const CIPHER_LIMIT = limit('ciphertext', 16, 2 ** 132 + 16);
1691
+ if (AAD.length > 126) {
1692
+ // RFC 5297 §2.6 / §2.7 / §7: SIV passes the plaintext as the last S2V
1693
+ // component, so callers only get 126 associated-data components.
1694
+ throw new Error('"AAD" number of elements must be less than or equal to 126');
1695
+ }
1696
+ AAD.forEach((aad) => abytes(aad));
1697
+ abytes(key);
1698
+ if (![32, 48, 64].includes(key.length))
1699
+ throw new Error('"aes key" expected Uint8Array of length 32/48/64, got length=' + key.length);
1700
+ // The key is split into equal halves, K1 = leftmost(K, len(K)/2) and
1701
+ // K2 = rightmost(K, len(K)/2). K1 is used for S2V and K2 is used for CTR.
1702
+ // This borrows caller key/AAD buffers by reference; mutating them after
1703
+ // construction changes future encrypt/decrypt results.
1704
+ const k1 = key.subarray(0, key.length / 2);
1705
+ const k2 = key.subarray(key.length / 2);
1706
+ return {
1707
+ // {@link https://datatracker.ietf.org/doc/html/rfc5297.html#section-2.6 | RFC 5297 Section 2.6}
1708
+ encrypt(plaintext) {
1709
+ PLAIN_LIMIT(plaintext.length);
1710
+ const v = s2v(k1, [...AAD, plaintext]);
1711
+ // clear out the 31st and 63rd (rightmost) bit:
1712
+ const q = Uint8Array.from(v);
1713
+ q[8] &= 0x7f;
1714
+ q[12] &= 0x7f;
1715
+ // encrypt:
1716
+ const c = ctr(k2, q).encrypt(plaintext);
1717
+ return concatBytes(v, c);
1718
+ },
1719
+ // {@link https://datatracker.ietf.org/doc/html/rfc5297.html#section-2.7 | RFC 5297 Section 2.7}
1720
+ decrypt(ciphertext) {
1721
+ CIPHER_LIMIT(ciphertext.length);
1722
+ const v = ciphertext.subarray(0, BLOCK_SIZE);
1723
+ const c = ciphertext.subarray(BLOCK_SIZE);
1724
+ // clear out the 31st and 63rd (rightmost) bit:
1725
+ const q = Uint8Array.from(v);
1726
+ q[8] &= 0x7f;
1727
+ q[12] &= 0x7f;
1728
+ // decrypt:
1729
+ const p = ctr(k2, q).decrypt(c);
1730
+ // verify tag:
1731
+ const t = s2v(k1, [...AAD, p]);
1732
+ if (equalBytes(t, v)) {
1733
+ return p;
1734
+ }
1735
+ else {
1736
+ throw new Error('invalid siv tag');
1737
+ }
1738
+ },
1739
+ };
1740
+ });
1741
+ //#endregion
1742
+ /**
1743
+ * Unsafe low-level internal methods. May change at any time.
1744
+ * Callers are expected to use reviewed expanded-key outputs, pass mutable and
1745
+ * aligned 16-byte blocks where required, and treat several helpers as in-place
1746
+ * mutations of their input buffers or counters.
1747
+ */
1748
+ export const unsafe = /* @__PURE__ */ Object.freeze({
1749
+ expandKeyLE,
1750
+ expandKeyDecLE,
1751
+ encrypt,
1752
+ decrypt,
1753
+ encryptBlock,
1754
+ decryptBlock,
1755
+ ctrCounter,
1756
+ ctr32,
1757
+ dbl,
1758
+ xorBlock,
1759
+ xorend,
1760
+ s2v,
1761
+ });
1762
+ export const __TESTS = /* @__PURE__ */ Object.freeze({
1763
+ incBytes: incBytes,
1764
+ });