@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/_polyval.js ADDED
@@ -0,0 +1,335 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.polyval = exports.ghash = exports.Polyval = exports.GHASH = void 0;
4
+ exports._toGHASHKey = _toGHASHKey;
5
+ /**
6
+ * GHash from AES-GCM and its little-endian "mirror image" Polyval from AES-SIV.
7
+ *
8
+ * Implemented in terms of GHash with conversion function for keys
9
+ * GCM GHASH from
10
+ * {@link https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-38d.pdf | NIST SP800-38d},
11
+ * SIV from
12
+ * {@link https://www.rfc-editor.org/rfc/rfc8452 | RFC 8452}.
13
+ *
14
+ * GHASH modulo: x^128 + x^7 + x^2 + x + 1
15
+ * POLYVAL modulo: x^128 + x^127 + x^126 + x^121 + 1
16
+ *
17
+ * @module
18
+ */
19
+ const utils_1 = require("./utils");
20
+ const BLOCK_SIZE = 16;
21
+ // TODO: rewrite
22
+ // temporary padding buffer
23
+ // ZEROS32 aliases these bytes, so clean(ZEROS32) also resets this shared tail-padding scratch.
24
+ const ZEROS16 = /* @__PURE__ */ new Uint8Array(16);
25
+ const ZEROS32 = /* @__PURE__ */ (0, utils_1.u32)(ZEROS16);
26
+ // GHASH reduces modulo x^128 + x^7 + x^2 + x + 1, so the low-degree terms
27
+ // x^7 + x^2 + x + 1 become bits `11100001` = 0xe1 in R = 0xe1 || 0^120.
28
+ const POLY = 0xe1;
29
+ // v = 2*v % POLY
30
+ // NOTE: because x + x = 0 (add/sub is same), mul2(x) != x+x
31
+ // Montgomery ladder can multiply any field element with this doubling step;
32
+ // addition stays simple xor.
33
+ const mul2 = (s0, s1, s2, s3) => {
34
+ const hiBit = s3 & 1;
35
+ return {
36
+ s3: (s2 << 31) | (s3 >>> 1),
37
+ s2: (s1 << 31) | (s2 >>> 1),
38
+ s1: (s0 << 31) | (s1 >>> 1),
39
+ // NIST SP 800-38D §6.3 applies `V >> 1` and XORs R on carry. In this
40
+ // 4x32-bit split, R = 0xe1 || 0^120 lives in the top byte of s0.
41
+ s0: (s0 >>> 1) ^ ((POLY << 24) & -(hiBit & 1)), // reduce % poly
42
+ };
43
+ };
44
+ // Per-word part of RFC 8452 `ByteReverse`; callers also reverse the 32-bit word order.
45
+ const swapLE = (n) => (((n >>> 0) & 0xff) << 24) |
46
+ (((n >>> 8) & 0xff) << 16) |
47
+ (((n >>> 16) & 0xff) << 8) |
48
+ ((n >>> 24) & 0xff) |
49
+ 0;
50
+ // POLYVAL first applies RFC 8452's per-word byte reversal, then re-normalizes
51
+ // host-endian u32 loads to the little-endian word value `_updateBlock()` expects.
52
+ const swap8IfLE = (n) => (0, utils_1.swap8IfBE)(swapLE(n));
53
+ /**
54
+ * `mulX_GHASH(ByteReverse(H))` from RFC 8452 Appendix A.
55
+ * @param k mutated in place
56
+ */
57
+ function _toGHASHKey(k) {
58
+ // The input is the original POLYVAL key H; reverse() materializes
59
+ // RFC 8452's `ByteReverse(H)` before the GHASH mulX step.
60
+ k.reverse();
61
+ const hiBit = k[15] & 1;
62
+ // k >>= 1
63
+ let carry = 0;
64
+ for (let i = 0; i < k.length; i++) {
65
+ const t = k[i];
66
+ k[i] = (t >>> 1) | carry;
67
+ carry = (t & 1) << 7;
68
+ }
69
+ k[0] ^= -hiBit & 0xe1; // if (hiBit) n ^= 0xe1000000000000000000000000000000;
70
+ return k;
71
+ }
72
+ // Precompute-window heuristic only: larger inputs trade memory for fewer table lookups.
73
+ // Any caller-provided length hint still collapses to one of the supported windows {2, 4, 8}.
74
+ const estimateWindow = (bytes) => {
75
+ if (bytes > 64 * 1024)
76
+ return 8;
77
+ if (bytes > 1024)
78
+ return 4;
79
+ return 2;
80
+ };
81
+ /**
82
+ * Incremental GHASH state for AES-GCM.
83
+ * @param key - 16-byte GHASH key.
84
+ * @param expectedLength - Expected message length for table sizing.
85
+ * Chunking is segment-based, not hash-streaming: every `update()` call is zero-padded
86
+ * to the next 16-byte boundary before it is absorbed. This matches the internal AES/GCM
87
+ * use where AAD, payload, and length block are separate padded segments.
88
+ * @example
89
+ * Feeds one ciphertext block into an incremental GHASH state with a fresh hash key.
90
+ *
91
+ * ```ts
92
+ * import { GHASH } from './_polyval';
93
+ * import { randomBytes } from './utils';
94
+ * const key = randomBytes(16);
95
+ * const mac = new GHASH(key);
96
+ * mac.update(new Uint8Array(16));
97
+ * mac.digest();
98
+ * ```
99
+ */
100
+ class GHASH {
101
+ blockLen = BLOCK_SIZE;
102
+ outputLen = BLOCK_SIZE;
103
+ s0 = 0;
104
+ s1 = 0;
105
+ s2 = 0;
106
+ s3 = 0;
107
+ finished = false;
108
+ destroyed = false;
109
+ t;
110
+ W;
111
+ windowSize;
112
+ // We select bits per window adaptively based on expectedLength
113
+ constructor(key, expectedLength) {
114
+ (0, utils_1.abytes)(key, 16, 'key');
115
+ key = (0, utils_1.copyBytes)(key);
116
+ const kView = (0, utils_1.createView)(key);
117
+ let k0 = kView.getUint32(0, false);
118
+ let k1 = kView.getUint32(4, false);
119
+ let k2 = kView.getUint32(8, false);
120
+ let k3 = kView.getUint32(12, false);
121
+ // generate table of doubled keys (half of montgomery ladder)
122
+ const doubles = [];
123
+ for (let i = 0; i < 128; i++) {
124
+ doubles.push({ s0: swapLE(k0), s1: swapLE(k1), s2: swapLE(k2), s3: swapLE(k3) });
125
+ ({ s0: k0, s1: k1, s2: k2, s3: k3 } = mul2(k0, k1, k2, k3));
126
+ }
127
+ const W = estimateWindow(expectedLength || 1024);
128
+ if (![1, 2, 4, 8].includes(W))
129
+ throw new Error('ghash: invalid window size, expected 2, 4 or 8');
130
+ this.W = W;
131
+ const bits = 128; // always 128 bits;
132
+ const windows = bits / W;
133
+ const windowSize = (this.windowSize = 2 ** W);
134
+ const items = [];
135
+ // Create precompute table for window of W bits
136
+ for (let w = 0; w < windows; w++) {
137
+ // truth table: 00, 01, 10, 11
138
+ for (let byte = 0; byte < windowSize; byte++) {
139
+ // prettier-ignore
140
+ let s0 = 0, s1 = 0, s2 = 0, s3 = 0;
141
+ for (let j = 0; j < W; j++) {
142
+ const bit = (byte >>> (W - j - 1)) & 1;
143
+ if (!bit)
144
+ continue;
145
+ const { s0: d0, s1: d1, s2: d2, s3: d3 } = doubles[W * w + j];
146
+ ((s0 ^= d0), (s1 ^= d1), (s2 ^= d2), (s3 ^= d3));
147
+ }
148
+ items.push({ s0, s1, s2, s3 });
149
+ }
150
+ }
151
+ this.t = items;
152
+ }
153
+ _updateBlock(s0, s1, s2, s3) {
154
+ ((s0 ^= this.s0), (s1 ^= this.s1), (s2 ^= this.s2), (s3 ^= this.s3));
155
+ const { W, t, windowSize } = this;
156
+ // prettier-ignore
157
+ let o0 = 0, o1 = 0, o2 = 0, o3 = 0;
158
+ const mask = (1 << W) - 1; // 2**W will kill performance.
159
+ let w = 0;
160
+ // NIST SP 800-38D §6.3 interprets blocks as little-endian polynomials,
161
+ // so the lookup walk consumes each word byte-by-byte from
162
+ // least-significant to most-significant bits.
163
+ for (const num of [s0, s1, s2, s3]) {
164
+ for (let bytePos = 0; bytePos < 4; bytePos++) {
165
+ const byte = (num >>> (8 * bytePos)) & 0xff;
166
+ for (let bitPos = 8 / W - 1; bitPos >= 0; bitPos--) {
167
+ const bit = (byte >>> (W * bitPos)) & mask;
168
+ const { s0: e0, s1: e1, s2: e2, s3: e3 } = t[w * windowSize + bit];
169
+ ((o0 ^= e0), (o1 ^= e1), (o2 ^= e2), (o3 ^= e3));
170
+ w += 1;
171
+ }
172
+ }
173
+ }
174
+ this.s0 = o0;
175
+ this.s1 = o1;
176
+ this.s2 = o2;
177
+ this.s3 = o3;
178
+ }
179
+ update(data) {
180
+ (0, utils_1.aexists)(this);
181
+ (0, utils_1.abytes)(data);
182
+ data = (0, utils_1.copyBytes)(data);
183
+ const b32 = (0, utils_1.u32)(data);
184
+ const blocks = Math.floor(data.length / BLOCK_SIZE);
185
+ const left = data.length % BLOCK_SIZE;
186
+ for (let i = 0; i < blocks; i++) {
187
+ this._updateBlock((0, utils_1.swap8IfBE)(b32[i * 4 + 0]), (0, utils_1.swap8IfBE)(b32[i * 4 + 1]), (0, utils_1.swap8IfBE)(b32[i * 4 + 2]), (0, utils_1.swap8IfBE)(b32[i * 4 + 3]));
188
+ }
189
+ if (left) {
190
+ ZEROS16.set(data.subarray(blocks * BLOCK_SIZE));
191
+ // Tail blocks go through the shared ZEROS32 scratch, so they need the same host-endian
192
+ // normalization as full blocks; otherwise segmented GHASH/POLYVAL updates diverge on BE.
193
+ this._updateBlock((0, utils_1.swap8IfBE)(ZEROS32[0]), (0, utils_1.swap8IfBE)(ZEROS32[1]), (0, utils_1.swap8IfBE)(ZEROS32[2]), (0, utils_1.swap8IfBE)(ZEROS32[3]));
194
+ (0, utils_1.clean)(ZEROS32); // clean tmp buffer
195
+ }
196
+ return this;
197
+ }
198
+ destroy() {
199
+ // `aexists(this)` guards update/digest paths, so destroy must mark the instance unusable too.
200
+ this.destroyed = true;
201
+ const { t } = this;
202
+ // Wipe the key-derived precompute table; scalar accumulator words remain,
203
+ // but the destroyed guard blocks further use.
204
+ // clean precompute table
205
+ for (const elm of t) {
206
+ ((elm.s0 = 0), (elm.s1 = 0), (elm.s2 = 0), (elm.s3 = 0));
207
+ }
208
+ }
209
+ digestInto(out) {
210
+ (0, utils_1.aexists)(this);
211
+ // `digestInto(out)` is the no-allocation fast path, so callers must pass a
212
+ // 32-bit-aligned buffer before we reinterpret it with `u32(out)`.
213
+ (0, utils_1.aoutput)(out, this, true);
214
+ this.finished = true;
215
+ // NIST SP 800-38D §6.4 returns the final 128-bit block Y_m.
216
+ // `digestInto()` follows the relaxed `aoutput()` contract, so only
217
+ // out[0..15] may be touched.
218
+ const { s0, s1, s2, s3 } = this;
219
+ const o32 = (0, utils_1.u32)(out);
220
+ o32[0] = s0;
221
+ o32[1] = s1;
222
+ o32[2] = s2;
223
+ o32[3] = s3;
224
+ (0, utils_1.swap32IfBE)(o32);
225
+ }
226
+ digest() {
227
+ const res = new Uint8Array(BLOCK_SIZE);
228
+ this.digestInto(res);
229
+ // `res` is independent of internal state, so it stays valid after destroy() wipes the table.
230
+ this.destroy();
231
+ return res;
232
+ }
233
+ }
234
+ exports.GHASH = GHASH;
235
+ /**
236
+ * Incremental POLYVAL state for AES-SIV.
237
+ * @param key - 16-byte POLYVAL key.
238
+ * @param expectedLength - Expected message length for table sizing.
239
+ * Inherits GHASH's segment-padded `update()` behavior: each call is padded
240
+ * independently to a 16-byte boundary before absorption.
241
+ * @example
242
+ * Feeds one block into an incremental POLYVAL state with a fresh hash key.
243
+ *
244
+ * ```ts
245
+ * import { Polyval } from './_polyval';
246
+ * import { randomBytes } from './utils';
247
+ * const key = randomBytes(16);
248
+ * const mac = new Polyval(key);
249
+ * mac.update(new Uint8Array(16));
250
+ * mac.digest();
251
+ * ```
252
+ */
253
+ class Polyval extends GHASH {
254
+ constructor(key, expectedLength) {
255
+ (0, utils_1.abytes)(key);
256
+ // RFC 8452 Appendix A converts the POLYVAL key with
257
+ // `mulX_GHASH(ByteReverse(H))`; copy first because `_toGHASHKey(...)`
258
+ // mutates in place.
259
+ const ghKey = _toGHASHKey((0, utils_1.copyBytes)(key));
260
+ super(ghKey, expectedLength);
261
+ (0, utils_1.clean)(ghKey);
262
+ }
263
+ update(data) {
264
+ (0, utils_1.aexists)(this);
265
+ (0, utils_1.abytes)(data);
266
+ data = (0, utils_1.copyBytes)(data);
267
+ const b32 = (0, utils_1.u32)(data);
268
+ const left = data.length % BLOCK_SIZE;
269
+ const blocks = Math.floor(data.length / BLOCK_SIZE);
270
+ for (let i = 0; i < blocks; i++) {
271
+ // RFC 8452 Appendix A feeds `ByteReverse(X_i)` into GHASH, so POLYVAL
272
+ // reverses the 32-bit word order in addition to the per-word byte swap.
273
+ this._updateBlock(swap8IfLE(b32[i * 4 + 3]), swap8IfLE(b32[i * 4 + 2]), swap8IfLE(b32[i * 4 + 1]), swap8IfLE(b32[i * 4 + 0]));
274
+ }
275
+ if (left) {
276
+ ZEROS16.set(data.subarray(blocks * BLOCK_SIZE));
277
+ this._updateBlock(swap8IfLE(ZEROS32[3]), swap8IfLE(ZEROS32[2]), swap8IfLE(ZEROS32[1]), swap8IfLE(ZEROS32[0]));
278
+ (0, utils_1.clean)(ZEROS32);
279
+ }
280
+ return this;
281
+ }
282
+ digestInto(out) {
283
+ (0, utils_1.aexists)(this);
284
+ // `digestInto(out)` is the no-allocation fast path, so callers must pass a
285
+ // 32-bit-aligned buffer before we reinterpret the output prefix with `u32(view)`.
286
+ (0, utils_1.aoutput)(out, this, true);
287
+ this.finished = true;
288
+ // RFC 8452 Appendix A maps POLYVAL output back through `ByteReverse(...)`.
289
+ // `digestInto()` follows the relaxed `aoutput()` contract, so only out[0..15] may be touched.
290
+ const view = out.subarray(0, this.outputLen);
291
+ const { s0, s1, s2, s3 } = this;
292
+ const o32 = (0, utils_1.u32)(view);
293
+ o32[0] = s0;
294
+ o32[1] = s1;
295
+ o32[2] = s2;
296
+ o32[3] = s3;
297
+ (0, utils_1.swap32IfBE)(o32);
298
+ view.reverse();
299
+ }
300
+ }
301
+ exports.Polyval = Polyval;
302
+ /**
303
+ * GHash MAC for AES-GCM.
304
+ * @param msg - Message bytes to authenticate.
305
+ * @param key - 16-byte GHASH key.
306
+ * @returns 16-byte authentication tag.
307
+ * @example
308
+ * Authenticates a short message with GHASH and a fresh hash key.
309
+ *
310
+ * ```ts
311
+ * import { ghash } from './_polyval';
312
+ * import { randomBytes } from './utils';
313
+ * const key = randomBytes(16);
314
+ * ghash(new Uint8Array(), key);
315
+ * ```
316
+ */
317
+ exports.ghash =
318
+ /* @__PURE__ */ (0, utils_1.wrapMacConstructor)(16, (key, expectedLength) => new GHASH(key, expectedLength), (msg) => [msg.length]);
319
+ /**
320
+ * POLYVAL MAC for AES-SIV.
321
+ * @param msg - Message bytes to authenticate.
322
+ * @param key - 16-byte POLYVAL key.
323
+ * @returns 16-byte authentication tag.
324
+ * @example
325
+ * Authenticates a short message with POLYVAL and a fresh hash key.
326
+ *
327
+ * ```ts
328
+ * import { polyval } from './_polyval';
329
+ * import { randomBytes } from './utils';
330
+ * const key = randomBytes(16);
331
+ * polyval(new Uint8Array(), key);
332
+ * ```
333
+ */
334
+ exports.polyval =
335
+ /* @__PURE__ */ (0, utils_1.wrapMacConstructor)(16, (key, expectedLength) => new Polyval(key, expectedLength), (msg) => [msg.length]);