@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.
@@ -0,0 +1,363 @@
1
+ /**
2
+ * Poly1305 ({@link https://cr.yp.to/mac/poly1305-20050329.pdf | PDF},
3
+ * {@link https://en.wikipedia.org/wiki/Poly1305 | wiki})
4
+ * is a fast and parallel secret-key message-authentication code suitable for
5
+ * a wide variety of applications. It was standardized in
6
+ * {@link https://www.rfc-editor.org/rfc/rfc8439 | RFC 8439} and is now used in TLS 1.3.
7
+ *
8
+ * Polynomial MACs are not perfect for every situation:
9
+ * they lack Random Key Robustness: the MAC can be forged, and can't be used in PAKE schemes.
10
+ * See {@link https://keymaterial.net/2020/09/07/invisible-salamanders-in-aes-gcm-siv/ | the invisible salamanders attack writeup}.
11
+ * To combat invisible salamanders, `hash(key)` can be included in ciphertext,
12
+ * however, this would violate ciphertext indistinguishability:
13
+ * an attacker would know which key was used - so `HKDF(key, i)`
14
+ * could be used instead.
15
+ *
16
+ * Check out the {@link https://cr.yp.to/mac.html | original website}.
17
+ * Based on public-domain {@link https://github.com/floodyberry/poly1305-donna | poly1305-donna}.
18
+ * @module
19
+ */
20
+ // prettier-ignore
21
+ import { abytes, aexists, aoutput, bytesToHex, clean, concatBytes, copyBytes, hexToNumber, numberToBytesBE, wrapMacConstructor } from './utils';
22
+ // Little-endian 2-byte load used by the Poly1305 limb decomposition.
23
+ function u8to16(a, i) {
24
+ return (a[i++] & 0xff) | ((a[i++] & 0xff) << 8);
25
+ }
26
+ function bytesToNumberLE(bytes) {
27
+ return hexToNumber(bytesToHex(Uint8Array.from(bytes).reverse()));
28
+ }
29
+ /** Small version of `poly1305` without loop unrolling. Unused, provided for auditability. */
30
+ function poly1305_small(msg, key) {
31
+ abytes(msg);
32
+ abytes(key, 32, 'key');
33
+ const POW_2_130_5 = BigInt(2) ** BigInt(130) - BigInt(5); // 2^130-5
34
+ const POW_2_128_1 = BigInt(2) ** BigInt(128) - BigInt(1); // 2^128-1
35
+ const CLAMP_R = BigInt('0x0ffffffc0ffffffc0ffffffc0fffffff');
36
+ const r = bytesToNumberLE(key.subarray(0, 16)) & CLAMP_R;
37
+ const s = bytesToNumberLE(key.subarray(16));
38
+ // Process by 16 byte chunks
39
+ let acc = BigInt(0);
40
+ for (let i = 0; i < msg.length; i += 16) {
41
+ const m = msg.subarray(i, i + 16);
42
+ // RFC 8439 §2.5.1 / RFC 7539 §2.5.1 append [0x01] to each chunk before multiplying by r.
43
+ const n = bytesToNumberLE(m) | (BigInt(1) << BigInt(8 * m.length));
44
+ acc = ((acc + n) * r) % POW_2_130_5;
45
+ }
46
+ const res = (acc + s) & POW_2_128_1;
47
+ // RFC 8439 §2.5 / RFC 7539 §2.5 serialize the low 128 bits in little-endian order.
48
+ return numberToBytesBE(res, 16).reverse(); // LE
49
+ }
50
+ // Can be used to replace `computeTag` in chacha.ts. Unused, provided for auditability.
51
+ // @ts-expect-error
52
+ function poly1305_computeTag_small(authKey,
53
+ // AEAD trailer must already be the 16-byte length block:
54
+ // 8-byte little-endian AAD length || 8-byte little-endian ciphertext length.
55
+ lengths, ciphertext, AAD) {
56
+ // RFC 8439 §2.8.1 / RFC 7539 §2.8.1 MAC input is
57
+ // AAD || pad16(AAD) || ciphertext || pad16(ciphertext) || lengths.
58
+ const res = [];
59
+ const updatePadded2 = (msg) => {
60
+ res.push(msg);
61
+ const leftover = msg.length % 16;
62
+ // RFC 8439 §2.8.1 / RFC 7539 §2.8.1: pad16(x) is empty for aligned
63
+ // inputs, else 16-(len%16) zero bytes.
64
+ if (leftover)
65
+ res.push(new Uint8Array(16).slice(leftover));
66
+ };
67
+ if (AAD)
68
+ updatePadded2(AAD);
69
+ updatePadded2(ciphertext);
70
+ res.push(lengths);
71
+ return poly1305_small(concatBytes(...res), authKey);
72
+ }
73
+ /**
74
+ * Incremental Poly1305 MAC state.
75
+ * Prefer `poly1305()` for one-shot use.
76
+ * @param key - 32-byte Poly1305 one-time key.
77
+ * @example
78
+ * Feeds one chunk into an incremental Poly1305 state with a fresh one-time key.
79
+ *
80
+ * ```ts
81
+ * import { Poly1305 } from './_poly1305';
82
+ * import { randomBytes } from './utils';
83
+ * const key = randomBytes(32);
84
+ * const mac = new Poly1305(key);
85
+ * mac.update(new Uint8Array([1, 2, 3]));
86
+ * mac.digest();
87
+ * ```
88
+ */
89
+ export class Poly1305 {
90
+ blockLen = 16;
91
+ outputLen = 16;
92
+ buffer = new Uint8Array(16);
93
+ r = new Uint16Array(10); // Allocating 1 array with .subarray() here is slower than 3
94
+ h = new Uint16Array(10);
95
+ pad = new Uint16Array(8);
96
+ pos = 0;
97
+ finished = false;
98
+ destroyed = false;
99
+ // Can be speed-up using BigUint64Array, at the cost of complexity
100
+ constructor(key) {
101
+ key = copyBytes(abytes(key, 32, 'key'));
102
+ const t0 = u8to16(key, 0);
103
+ const t1 = u8to16(key, 2);
104
+ const t2 = u8to16(key, 4);
105
+ const t3 = u8to16(key, 6);
106
+ const t4 = u8to16(key, 8);
107
+ const t5 = u8to16(key, 10);
108
+ const t6 = u8to16(key, 12);
109
+ const t7 = u8to16(key, 14);
110
+ // RFC 8439 §2.5.1 / RFC 7539 §2.5.1 clamp r before multiplication.
111
+ // These masks unpack that clamped value into 13-bit limbs, while pad
112
+ // keeps the raw s half for finalize().
113
+ // {@link https://github.com/floodyberry/poly1305-donna/blob/e6ad6e091d30d7f4ec2d4f978be1fcfcbce72781/poly1305-donna-16.h#L47 | poly1305-donna reference}
114
+ this.r[0] = t0 & 0x1fff;
115
+ this.r[1] = ((t0 >>> 13) | (t1 << 3)) & 0x1fff;
116
+ this.r[2] = ((t1 >>> 10) | (t2 << 6)) & 0x1f03;
117
+ this.r[3] = ((t2 >>> 7) | (t3 << 9)) & 0x1fff;
118
+ this.r[4] = ((t3 >>> 4) | (t4 << 12)) & 0x00ff;
119
+ this.r[5] = (t4 >>> 1) & 0x1ffe;
120
+ this.r[6] = ((t4 >>> 14) | (t5 << 2)) & 0x1fff;
121
+ this.r[7] = ((t5 >>> 11) | (t6 << 5)) & 0x1f81;
122
+ this.r[8] = ((t6 >>> 8) | (t7 << 8)) & 0x1fff;
123
+ this.r[9] = (t7 >>> 5) & 0x007f;
124
+ for (let i = 0; i < 8; i++)
125
+ this.pad[i] = u8to16(key, 16 + 2 * i);
126
+ }
127
+ process(data, offset, isLast = false) {
128
+ // RFC 8439 §2.5 / §2.5.1 and RFC 7539 §2.5 / §2.5.1 add an extra high
129
+ // bit to every full 16-byte block. The final partial block gets its
130
+ // explicit `1` byte during digestInto(), so `hibit` stays zero there.
131
+ const hibit = isLast ? 0 : 1 << 11;
132
+ const { h, r } = this;
133
+ const r0 = r[0];
134
+ const r1 = r[1];
135
+ const r2 = r[2];
136
+ const r3 = r[3];
137
+ const r4 = r[4];
138
+ const r5 = r[5];
139
+ const r6 = r[6];
140
+ const r7 = r[7];
141
+ const r8 = r[8];
142
+ const r9 = r[9];
143
+ const t0 = u8to16(data, offset + 0);
144
+ const t1 = u8to16(data, offset + 2);
145
+ const t2 = u8to16(data, offset + 4);
146
+ const t3 = u8to16(data, offset + 6);
147
+ const t4 = u8to16(data, offset + 8);
148
+ const t5 = u8to16(data, offset + 10);
149
+ const t6 = u8to16(data, offset + 12);
150
+ const t7 = u8to16(data, offset + 14);
151
+ let h0 = h[0] + (t0 & 0x1fff);
152
+ let h1 = h[1] + (((t0 >>> 13) | (t1 << 3)) & 0x1fff);
153
+ let h2 = h[2] + (((t1 >>> 10) | (t2 << 6)) & 0x1fff);
154
+ let h3 = h[3] + (((t2 >>> 7) | (t3 << 9)) & 0x1fff);
155
+ let h4 = h[4] + (((t3 >>> 4) | (t4 << 12)) & 0x1fff);
156
+ let h5 = h[5] + ((t4 >>> 1) & 0x1fff);
157
+ let h6 = h[6] + (((t4 >>> 14) | (t5 << 2)) & 0x1fff);
158
+ let h7 = h[7] + (((t5 >>> 11) | (t6 << 5)) & 0x1fff);
159
+ let h8 = h[8] + (((t6 >>> 8) | (t7 << 8)) & 0x1fff);
160
+ let h9 = h[9] + ((t7 >>> 5) | hibit);
161
+ let c = 0;
162
+ let d0 = c + h0 * r0 + h1 * (5 * r9) + h2 * (5 * r8) + h3 * (5 * r7) + h4 * (5 * r6);
163
+ c = d0 >>> 13;
164
+ d0 &= 0x1fff;
165
+ d0 += h5 * (5 * r5) + h6 * (5 * r4) + h7 * (5 * r3) + h8 * (5 * r2) + h9 * (5 * r1);
166
+ c += d0 >>> 13;
167
+ d0 &= 0x1fff;
168
+ let d1 = c + h0 * r1 + h1 * r0 + h2 * (5 * r9) + h3 * (5 * r8) + h4 * (5 * r7);
169
+ c = d1 >>> 13;
170
+ d1 &= 0x1fff;
171
+ d1 += h5 * (5 * r6) + h6 * (5 * r5) + h7 * (5 * r4) + h8 * (5 * r3) + h9 * (5 * r2);
172
+ c += d1 >>> 13;
173
+ d1 &= 0x1fff;
174
+ let d2 = c + h0 * r2 + h1 * r1 + h2 * r0 + h3 * (5 * r9) + h4 * (5 * r8);
175
+ c = d2 >>> 13;
176
+ d2 &= 0x1fff;
177
+ d2 += h5 * (5 * r7) + h6 * (5 * r6) + h7 * (5 * r5) + h8 * (5 * r4) + h9 * (5 * r3);
178
+ c += d2 >>> 13;
179
+ d2 &= 0x1fff;
180
+ let d3 = c + h0 * r3 + h1 * r2 + h2 * r1 + h3 * r0 + h4 * (5 * r9);
181
+ c = d3 >>> 13;
182
+ d3 &= 0x1fff;
183
+ d3 += h5 * (5 * r8) + h6 * (5 * r7) + h7 * (5 * r6) + h8 * (5 * r5) + h9 * (5 * r4);
184
+ c += d3 >>> 13;
185
+ d3 &= 0x1fff;
186
+ let d4 = c + h0 * r4 + h1 * r3 + h2 * r2 + h3 * r1 + h4 * r0;
187
+ c = d4 >>> 13;
188
+ d4 &= 0x1fff;
189
+ d4 += h5 * (5 * r9) + h6 * (5 * r8) + h7 * (5 * r7) + h8 * (5 * r6) + h9 * (5 * r5);
190
+ c += d4 >>> 13;
191
+ d4 &= 0x1fff;
192
+ let d5 = c + h0 * r5 + h1 * r4 + h2 * r3 + h3 * r2 + h4 * r1;
193
+ c = d5 >>> 13;
194
+ d5 &= 0x1fff;
195
+ d5 += h5 * r0 + h6 * (5 * r9) + h7 * (5 * r8) + h8 * (5 * r7) + h9 * (5 * r6);
196
+ c += d5 >>> 13;
197
+ d5 &= 0x1fff;
198
+ let d6 = c + h0 * r6 + h1 * r5 + h2 * r4 + h3 * r3 + h4 * r2;
199
+ c = d6 >>> 13;
200
+ d6 &= 0x1fff;
201
+ d6 += h5 * r1 + h6 * r0 + h7 * (5 * r9) + h8 * (5 * r8) + h9 * (5 * r7);
202
+ c += d6 >>> 13;
203
+ d6 &= 0x1fff;
204
+ let d7 = c + h0 * r7 + h1 * r6 + h2 * r5 + h3 * r4 + h4 * r3;
205
+ c = d7 >>> 13;
206
+ d7 &= 0x1fff;
207
+ d7 += h5 * r2 + h6 * r1 + h7 * r0 + h8 * (5 * r9) + h9 * (5 * r8);
208
+ c += d7 >>> 13;
209
+ d7 &= 0x1fff;
210
+ let d8 = c + h0 * r8 + h1 * r7 + h2 * r6 + h3 * r5 + h4 * r4;
211
+ c = d8 >>> 13;
212
+ d8 &= 0x1fff;
213
+ d8 += h5 * r3 + h6 * r2 + h7 * r1 + h8 * r0 + h9 * (5 * r9);
214
+ c += d8 >>> 13;
215
+ d8 &= 0x1fff;
216
+ let d9 = c + h0 * r9 + h1 * r8 + h2 * r7 + h3 * r6 + h4 * r5;
217
+ c = d9 >>> 13;
218
+ d9 &= 0x1fff;
219
+ d9 += h5 * r4 + h6 * r3 + h7 * r2 + h8 * r1 + h9 * r0;
220
+ c += d9 >>> 13;
221
+ d9 &= 0x1fff;
222
+ c = ((c << 2) + c) | 0;
223
+ c = (c + d0) | 0;
224
+ d0 = c & 0x1fff;
225
+ c = c >>> 13;
226
+ d1 += c;
227
+ h[0] = d0;
228
+ h[1] = d1;
229
+ h[2] = d2;
230
+ h[3] = d3;
231
+ h[4] = d4;
232
+ h[5] = d5;
233
+ h[6] = d6;
234
+ h[7] = d7;
235
+ h[8] = d8;
236
+ h[9] = d9;
237
+ }
238
+ finalize() {
239
+ const { h, pad } = this;
240
+ const g = new Uint16Array(10);
241
+ let c = h[1] >>> 13;
242
+ h[1] &= 0x1fff;
243
+ for (let i = 2; i < 10; i++) {
244
+ h[i] += c;
245
+ c = h[i] >>> 13;
246
+ h[i] &= 0x1fff;
247
+ }
248
+ h[0] += c * 5;
249
+ c = h[0] >>> 13;
250
+ h[0] &= 0x1fff;
251
+ h[1] += c;
252
+ c = h[1] >>> 13;
253
+ h[1] &= 0x1fff;
254
+ h[2] += c;
255
+ // RFC 8439 §2.5 / RFC 7539 §2.5 reduce modulo 2^130-5 before repacking
256
+ // to 16-bit words and adding the raw s half.
257
+ g[0] = h[0] + 5;
258
+ c = g[0] >>> 13;
259
+ g[0] &= 0x1fff;
260
+ for (let i = 1; i < 10; i++) {
261
+ g[i] = h[i] + c;
262
+ c = g[i] >>> 13;
263
+ g[i] &= 0x1fff;
264
+ }
265
+ g[9] -= 1 << 13;
266
+ let mask = (c ^ 1) - 1;
267
+ for (let i = 0; i < 10; i++)
268
+ g[i] &= mask;
269
+ mask = ~mask;
270
+ for (let i = 0; i < 10; i++)
271
+ h[i] = (h[i] & mask) | g[i];
272
+ h[0] = (h[0] | (h[1] << 13)) & 0xffff;
273
+ h[1] = ((h[1] >>> 3) | (h[2] << 10)) & 0xffff;
274
+ h[2] = ((h[2] >>> 6) | (h[3] << 7)) & 0xffff;
275
+ h[3] = ((h[3] >>> 9) | (h[4] << 4)) & 0xffff;
276
+ h[4] = ((h[4] >>> 12) | (h[5] << 1) | (h[6] << 14)) & 0xffff;
277
+ h[5] = ((h[6] >>> 2) | (h[7] << 11)) & 0xffff;
278
+ h[6] = ((h[7] >>> 5) | (h[8] << 8)) & 0xffff;
279
+ h[7] = ((h[8] >>> 8) | (h[9] << 5)) & 0xffff;
280
+ let f = h[0] + pad[0];
281
+ h[0] = f & 0xffff;
282
+ for (let i = 1; i < 8; i++) {
283
+ f = (((h[i] + pad[i]) | 0) + (f >>> 16)) | 0;
284
+ h[i] = f & 0xffff;
285
+ }
286
+ clean(g);
287
+ }
288
+ update(data) {
289
+ aexists(this);
290
+ abytes(data);
291
+ data = copyBytes(data);
292
+ const { buffer, blockLen } = this;
293
+ const len = data.length;
294
+ for (let pos = 0; pos < len;) {
295
+ const take = Math.min(blockLen - this.pos, len - pos);
296
+ // Fast path: we have at least one block in input
297
+ if (take === blockLen) {
298
+ for (; blockLen <= len - pos; pos += blockLen)
299
+ this.process(data, pos);
300
+ continue;
301
+ }
302
+ buffer.set(data.subarray(pos, pos + take), this.pos);
303
+ this.pos += take;
304
+ pos += take;
305
+ if (this.pos === blockLen) {
306
+ this.process(buffer, 0, false);
307
+ this.pos = 0;
308
+ }
309
+ }
310
+ return this;
311
+ }
312
+ destroy() {
313
+ // `aexists(this)` guards update/digest paths, so destroy must mark the instance unusable too.
314
+ this.destroyed = true;
315
+ clean(this.h, this.r, this.buffer, this.pad);
316
+ }
317
+ digestInto(out) {
318
+ aexists(this);
319
+ aoutput(out, this);
320
+ this.finished = true;
321
+ const { buffer, h } = this;
322
+ let { pos } = this;
323
+ if (pos) {
324
+ // RFC 8439 §2.5 / RFC 7539 §2.5: the final short block appends a
325
+ // single `0x01` byte and zero-fills the remaining bytes before the
326
+ // last multiplication step.
327
+ buffer[pos++] = 1;
328
+ for (; pos < 16; pos++)
329
+ buffer[pos] = 0;
330
+ this.process(buffer, 0, true);
331
+ }
332
+ this.finalize();
333
+ let opos = 0;
334
+ for (let i = 0; i < 8; i++) {
335
+ out[opos++] = h[i] >>> 0;
336
+ out[opos++] = h[i] >>> 8;
337
+ }
338
+ }
339
+ digest() {
340
+ const { buffer, outputLen } = this;
341
+ this.digestInto(buffer);
342
+ // Copy out before destroy() zeroes the internal buffer.
343
+ const res = buffer.slice(0, outputLen);
344
+ this.destroy();
345
+ return res;
346
+ }
347
+ }
348
+ /**
349
+ * Poly1305 MAC from RFC 8439.
350
+ * @param msg - Message bytes to authenticate.
351
+ * @param key - 32-byte Poly1305 one-time key.
352
+ * @returns 16-byte authentication tag.
353
+ * @example
354
+ * Authenticates one message with a one-shot Poly1305 call and a fresh key.
355
+ *
356
+ * ```ts
357
+ * import { poly1305 } from './_poly1305';
358
+ * import { randomBytes } from './utils';
359
+ * const key = randomBytes(32);
360
+ * poly1305(new Uint8Array(), key);
361
+ * ```
362
+ */
363
+ export const poly1305 = /* @__PURE__ */ wrapMacConstructor(32, (key) => new Poly1305(key));
@@ -0,0 +1,329 @@
1
+ /**
2
+ * GHash from AES-GCM and its little-endian "mirror image" Polyval from AES-SIV.
3
+ *
4
+ * Implemented in terms of GHash with conversion function for keys
5
+ * GCM GHASH from
6
+ * {@link https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-38d.pdf | NIST SP800-38d},
7
+ * SIV from
8
+ * {@link https://www.rfc-editor.org/rfc/rfc8452 | RFC 8452}.
9
+ *
10
+ * GHASH modulo: x^128 + x^7 + x^2 + x + 1
11
+ * POLYVAL modulo: x^128 + x^127 + x^126 + x^121 + 1
12
+ *
13
+ * @module
14
+ */
15
+ import { abytes, aexists, aoutput, clean, copyBytes, createView, swap32IfBE, swap8IfBE, u32, wrapMacConstructor, } from './utils';
16
+ const BLOCK_SIZE = 16;
17
+ // TODO: rewrite
18
+ // temporary padding buffer
19
+ // ZEROS32 aliases these bytes, so clean(ZEROS32) also resets this shared tail-padding scratch.
20
+ const ZEROS16 = /* @__PURE__ */ new Uint8Array(16);
21
+ const ZEROS32 = /* @__PURE__ */ u32(ZEROS16);
22
+ // GHASH reduces modulo x^128 + x^7 + x^2 + x + 1, so the low-degree terms
23
+ // x^7 + x^2 + x + 1 become bits `11100001` = 0xe1 in R = 0xe1 || 0^120.
24
+ const POLY = 0xe1;
25
+ // v = 2*v % POLY
26
+ // NOTE: because x + x = 0 (add/sub is same), mul2(x) != x+x
27
+ // Montgomery ladder can multiply any field element with this doubling step;
28
+ // addition stays simple xor.
29
+ const mul2 = (s0, s1, s2, s3) => {
30
+ const hiBit = s3 & 1;
31
+ return {
32
+ s3: (s2 << 31) | (s3 >>> 1),
33
+ s2: (s1 << 31) | (s2 >>> 1),
34
+ s1: (s0 << 31) | (s1 >>> 1),
35
+ // NIST SP 800-38D §6.3 applies `V >> 1` and XORs R on carry. In this
36
+ // 4x32-bit split, R = 0xe1 || 0^120 lives in the top byte of s0.
37
+ s0: (s0 >>> 1) ^ ((POLY << 24) & -(hiBit & 1)), // reduce % poly
38
+ };
39
+ };
40
+ // Per-word part of RFC 8452 `ByteReverse`; callers also reverse the 32-bit word order.
41
+ const swapLE = (n) => (((n >>> 0) & 0xff) << 24) |
42
+ (((n >>> 8) & 0xff) << 16) |
43
+ (((n >>> 16) & 0xff) << 8) |
44
+ ((n >>> 24) & 0xff) |
45
+ 0;
46
+ // POLYVAL first applies RFC 8452's per-word byte reversal, then re-normalizes
47
+ // host-endian u32 loads to the little-endian word value `_updateBlock()` expects.
48
+ const swap8IfLE = (n) => swap8IfBE(swapLE(n));
49
+ /**
50
+ * `mulX_GHASH(ByteReverse(H))` from RFC 8452 Appendix A.
51
+ * @param k mutated in place
52
+ */
53
+ export function _toGHASHKey(k) {
54
+ // The input is the original POLYVAL key H; reverse() materializes
55
+ // RFC 8452's `ByteReverse(H)` before the GHASH mulX step.
56
+ k.reverse();
57
+ const hiBit = k[15] & 1;
58
+ // k >>= 1
59
+ let carry = 0;
60
+ for (let i = 0; i < k.length; i++) {
61
+ const t = k[i];
62
+ k[i] = (t >>> 1) | carry;
63
+ carry = (t & 1) << 7;
64
+ }
65
+ k[0] ^= -hiBit & 0xe1; // if (hiBit) n ^= 0xe1000000000000000000000000000000;
66
+ return k;
67
+ }
68
+ // Precompute-window heuristic only: larger inputs trade memory for fewer table lookups.
69
+ // Any caller-provided length hint still collapses to one of the supported windows {2, 4, 8}.
70
+ const estimateWindow = (bytes) => {
71
+ if (bytes > 64 * 1024)
72
+ return 8;
73
+ if (bytes > 1024)
74
+ return 4;
75
+ return 2;
76
+ };
77
+ /**
78
+ * Incremental GHASH state for AES-GCM.
79
+ * @param key - 16-byte GHASH key.
80
+ * @param expectedLength - Expected message length for table sizing.
81
+ * Chunking is segment-based, not hash-streaming: every `update()` call is zero-padded
82
+ * to the next 16-byte boundary before it is absorbed. This matches the internal AES/GCM
83
+ * use where AAD, payload, and length block are separate padded segments.
84
+ * @example
85
+ * Feeds one ciphertext block into an incremental GHASH state with a fresh hash key.
86
+ *
87
+ * ```ts
88
+ * import { GHASH } from './_polyval';
89
+ * import { randomBytes } from './utils';
90
+ * const key = randomBytes(16);
91
+ * const mac = new GHASH(key);
92
+ * mac.update(new Uint8Array(16));
93
+ * mac.digest();
94
+ * ```
95
+ */
96
+ export class GHASH {
97
+ blockLen = BLOCK_SIZE;
98
+ outputLen = BLOCK_SIZE;
99
+ s0 = 0;
100
+ s1 = 0;
101
+ s2 = 0;
102
+ s3 = 0;
103
+ finished = false;
104
+ destroyed = false;
105
+ t;
106
+ W;
107
+ windowSize;
108
+ // We select bits per window adaptively based on expectedLength
109
+ constructor(key, expectedLength) {
110
+ abytes(key, 16, 'key');
111
+ key = copyBytes(key);
112
+ const kView = createView(key);
113
+ let k0 = kView.getUint32(0, false);
114
+ let k1 = kView.getUint32(4, false);
115
+ let k2 = kView.getUint32(8, false);
116
+ let k3 = kView.getUint32(12, false);
117
+ // generate table of doubled keys (half of montgomery ladder)
118
+ const doubles = [];
119
+ for (let i = 0; i < 128; i++) {
120
+ doubles.push({ s0: swapLE(k0), s1: swapLE(k1), s2: swapLE(k2), s3: swapLE(k3) });
121
+ ({ s0: k0, s1: k1, s2: k2, s3: k3 } = mul2(k0, k1, k2, k3));
122
+ }
123
+ const W = estimateWindow(expectedLength || 1024);
124
+ if (![1, 2, 4, 8].includes(W))
125
+ throw new Error('ghash: invalid window size, expected 2, 4 or 8');
126
+ this.W = W;
127
+ const bits = 128; // always 128 bits;
128
+ const windows = bits / W;
129
+ const windowSize = (this.windowSize = 2 ** W);
130
+ const items = [];
131
+ // Create precompute table for window of W bits
132
+ for (let w = 0; w < windows; w++) {
133
+ // truth table: 00, 01, 10, 11
134
+ for (let byte = 0; byte < windowSize; byte++) {
135
+ // prettier-ignore
136
+ let s0 = 0, s1 = 0, s2 = 0, s3 = 0;
137
+ for (let j = 0; j < W; j++) {
138
+ const bit = (byte >>> (W - j - 1)) & 1;
139
+ if (!bit)
140
+ continue;
141
+ const { s0: d0, s1: d1, s2: d2, s3: d3 } = doubles[W * w + j];
142
+ ((s0 ^= d0), (s1 ^= d1), (s2 ^= d2), (s3 ^= d3));
143
+ }
144
+ items.push({ s0, s1, s2, s3 });
145
+ }
146
+ }
147
+ this.t = items;
148
+ }
149
+ _updateBlock(s0, s1, s2, s3) {
150
+ ((s0 ^= this.s0), (s1 ^= this.s1), (s2 ^= this.s2), (s3 ^= this.s3));
151
+ const { W, t, windowSize } = this;
152
+ // prettier-ignore
153
+ let o0 = 0, o1 = 0, o2 = 0, o3 = 0;
154
+ const mask = (1 << W) - 1; // 2**W will kill performance.
155
+ let w = 0;
156
+ // NIST SP 800-38D §6.3 interprets blocks as little-endian polynomials,
157
+ // so the lookup walk consumes each word byte-by-byte from
158
+ // least-significant to most-significant bits.
159
+ for (const num of [s0, s1, s2, s3]) {
160
+ for (let bytePos = 0; bytePos < 4; bytePos++) {
161
+ const byte = (num >>> (8 * bytePos)) & 0xff;
162
+ for (let bitPos = 8 / W - 1; bitPos >= 0; bitPos--) {
163
+ const bit = (byte >>> (W * bitPos)) & mask;
164
+ const { s0: e0, s1: e1, s2: e2, s3: e3 } = t[w * windowSize + bit];
165
+ ((o0 ^= e0), (o1 ^= e1), (o2 ^= e2), (o3 ^= e3));
166
+ w += 1;
167
+ }
168
+ }
169
+ }
170
+ this.s0 = o0;
171
+ this.s1 = o1;
172
+ this.s2 = o2;
173
+ this.s3 = o3;
174
+ }
175
+ update(data) {
176
+ aexists(this);
177
+ abytes(data);
178
+ data = copyBytes(data);
179
+ const b32 = u32(data);
180
+ const blocks = Math.floor(data.length / BLOCK_SIZE);
181
+ const left = data.length % BLOCK_SIZE;
182
+ for (let i = 0; i < blocks; i++) {
183
+ this._updateBlock(swap8IfBE(b32[i * 4 + 0]), swap8IfBE(b32[i * 4 + 1]), swap8IfBE(b32[i * 4 + 2]), swap8IfBE(b32[i * 4 + 3]));
184
+ }
185
+ if (left) {
186
+ ZEROS16.set(data.subarray(blocks * BLOCK_SIZE));
187
+ // Tail blocks go through the shared ZEROS32 scratch, so they need the same host-endian
188
+ // normalization as full blocks; otherwise segmented GHASH/POLYVAL updates diverge on BE.
189
+ this._updateBlock(swap8IfBE(ZEROS32[0]), swap8IfBE(ZEROS32[1]), swap8IfBE(ZEROS32[2]), swap8IfBE(ZEROS32[3]));
190
+ clean(ZEROS32); // clean tmp buffer
191
+ }
192
+ return this;
193
+ }
194
+ destroy() {
195
+ // `aexists(this)` guards update/digest paths, so destroy must mark the instance unusable too.
196
+ this.destroyed = true;
197
+ const { t } = this;
198
+ // Wipe the key-derived precompute table; scalar accumulator words remain,
199
+ // but the destroyed guard blocks further use.
200
+ // clean precompute table
201
+ for (const elm of t) {
202
+ ((elm.s0 = 0), (elm.s1 = 0), (elm.s2 = 0), (elm.s3 = 0));
203
+ }
204
+ }
205
+ digestInto(out) {
206
+ aexists(this);
207
+ // `digestInto(out)` is the no-allocation fast path, so callers must pass a
208
+ // 32-bit-aligned buffer before we reinterpret it with `u32(out)`.
209
+ aoutput(out, this, true);
210
+ this.finished = true;
211
+ // NIST SP 800-38D §6.4 returns the final 128-bit block Y_m.
212
+ // `digestInto()` follows the relaxed `aoutput()` contract, so only
213
+ // out[0..15] may be touched.
214
+ const { s0, s1, s2, s3 } = this;
215
+ const o32 = u32(out);
216
+ o32[0] = s0;
217
+ o32[1] = s1;
218
+ o32[2] = s2;
219
+ o32[3] = s3;
220
+ swap32IfBE(o32);
221
+ }
222
+ digest() {
223
+ const res = new Uint8Array(BLOCK_SIZE);
224
+ this.digestInto(res);
225
+ // `res` is independent of internal state, so it stays valid after destroy() wipes the table.
226
+ this.destroy();
227
+ return res;
228
+ }
229
+ }
230
+ /**
231
+ * Incremental POLYVAL state for AES-SIV.
232
+ * @param key - 16-byte POLYVAL key.
233
+ * @param expectedLength - Expected message length for table sizing.
234
+ * Inherits GHASH's segment-padded `update()` behavior: each call is padded
235
+ * independently to a 16-byte boundary before absorption.
236
+ * @example
237
+ * Feeds one block into an incremental POLYVAL state with a fresh hash key.
238
+ *
239
+ * ```ts
240
+ * import { Polyval } from './_polyval';
241
+ * import { randomBytes } from './utils';
242
+ * const key = randomBytes(16);
243
+ * const mac = new Polyval(key);
244
+ * mac.update(new Uint8Array(16));
245
+ * mac.digest();
246
+ * ```
247
+ */
248
+ export class Polyval extends GHASH {
249
+ constructor(key, expectedLength) {
250
+ abytes(key);
251
+ // RFC 8452 Appendix A converts the POLYVAL key with
252
+ // `mulX_GHASH(ByteReverse(H))`; copy first because `_toGHASHKey(...)`
253
+ // mutates in place.
254
+ const ghKey = _toGHASHKey(copyBytes(key));
255
+ super(ghKey, expectedLength);
256
+ clean(ghKey);
257
+ }
258
+ update(data) {
259
+ aexists(this);
260
+ abytes(data);
261
+ data = copyBytes(data);
262
+ const b32 = u32(data);
263
+ const left = data.length % BLOCK_SIZE;
264
+ const blocks = Math.floor(data.length / BLOCK_SIZE);
265
+ for (let i = 0; i < blocks; i++) {
266
+ // RFC 8452 Appendix A feeds `ByteReverse(X_i)` into GHASH, so POLYVAL
267
+ // reverses the 32-bit word order in addition to the per-word byte swap.
268
+ this._updateBlock(swap8IfLE(b32[i * 4 + 3]), swap8IfLE(b32[i * 4 + 2]), swap8IfLE(b32[i * 4 + 1]), swap8IfLE(b32[i * 4 + 0]));
269
+ }
270
+ if (left) {
271
+ ZEROS16.set(data.subarray(blocks * BLOCK_SIZE));
272
+ this._updateBlock(swap8IfLE(ZEROS32[3]), swap8IfLE(ZEROS32[2]), swap8IfLE(ZEROS32[1]), swap8IfLE(ZEROS32[0]));
273
+ clean(ZEROS32);
274
+ }
275
+ return this;
276
+ }
277
+ digestInto(out) {
278
+ aexists(this);
279
+ // `digestInto(out)` is the no-allocation fast path, so callers must pass a
280
+ // 32-bit-aligned buffer before we reinterpret the output prefix with `u32(view)`.
281
+ aoutput(out, this, true);
282
+ this.finished = true;
283
+ // RFC 8452 Appendix A maps POLYVAL output back through `ByteReverse(...)`.
284
+ // `digestInto()` follows the relaxed `aoutput()` contract, so only out[0..15] may be touched.
285
+ const view = out.subarray(0, this.outputLen);
286
+ const { s0, s1, s2, s3 } = this;
287
+ const o32 = u32(view);
288
+ o32[0] = s0;
289
+ o32[1] = s1;
290
+ o32[2] = s2;
291
+ o32[3] = s3;
292
+ swap32IfBE(o32);
293
+ view.reverse();
294
+ }
295
+ }
296
+ /**
297
+ * GHash MAC for AES-GCM.
298
+ * @param msg - Message bytes to authenticate.
299
+ * @param key - 16-byte GHASH key.
300
+ * @returns 16-byte authentication tag.
301
+ * @example
302
+ * Authenticates a short message with GHASH and a fresh hash key.
303
+ *
304
+ * ```ts
305
+ * import { ghash } from './_polyval';
306
+ * import { randomBytes } from './utils';
307
+ * const key = randomBytes(16);
308
+ * ghash(new Uint8Array(), key);
309
+ * ```
310
+ */
311
+ export const ghash =
312
+ /* @__PURE__ */ wrapMacConstructor(16, (key, expectedLength) => new GHASH(key, expectedLength), (msg) => [msg.length]);
313
+ /**
314
+ * POLYVAL MAC for AES-SIV.
315
+ * @param msg - Message bytes to authenticate.
316
+ * @param key - 16-byte POLYVAL key.
317
+ * @returns 16-byte authentication tag.
318
+ * @example
319
+ * Authenticates a short message with POLYVAL and a fresh hash key.
320
+ *
321
+ * ```ts
322
+ * import { polyval } from './_polyval';
323
+ * import { randomBytes } from './utils';
324
+ * const key = randomBytes(16);
325
+ * polyval(new Uint8Array(), key);
326
+ * ```
327
+ */
328
+ export const polyval =
329
+ /* @__PURE__ */ wrapMacConstructor(16, (key, expectedLength) => new Polyval(key, expectedLength), (msg) => [msg.length]);