@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/_arx.js ADDED
@@ -0,0 +1,368 @@
1
+ /**
2
+ * Basic utils for ARX (add-rotate-xor) salsa and chacha ciphers.
3
+
4
+ RFC8439 requires multi-step cipher stream, where
5
+ authKey starts with counter: 0, actual msg with counter: 1.
6
+
7
+ For this, we need a way to re-use nonce / counter:
8
+
9
+ const counter = new Uint8Array(4);
10
+ chacha(..., counter, ...); // counter is now 1
11
+ chacha(..., counter, ...); // counter is now 2
12
+
13
+ This is complicated:
14
+
15
+ - 32-bit counters are enough, no need for 64-bit: max ArrayBuffer size in JS is 4GB
16
+ - Original papers don't allow mutating counters
17
+ - Counter overflow is undefined [^1]
18
+ - Idea A: allow providing (nonce | counter) instead of just nonce, re-use it
19
+ - Caveat: Cannot be re-used through all cases:
20
+ - * chacha has (counter | nonce)
21
+ - * xchacha has (nonce16 | counter | nonce16)
22
+ - Idea B: separate nonce / counter and provide separate API for counter re-use
23
+ - Caveat: there are different counter sizes depending on an algorithm.
24
+ - salsa & chacha also differ in structures of key & sigma:
25
+ salsa20: s[0] | k(4) | s[1] | nonce(2) | cnt(2) | s[2] | k(4) | s[3]
26
+ chacha: s(4) | k(8) | cnt(1) | nonce(3)
27
+ chacha20orig: s(4) | k(8) | cnt(2) | nonce(2)
28
+ - Idea C: helper method such as `setSalsaState(key, nonce, sigma, data)`
29
+ - Caveat: we can't re-use counter array
30
+
31
+ xchacha uses the subkey and remaining 8 byte nonce with ChaCha20 as normal
32
+ (prefixed by 4 NUL bytes, since RFC8439 specifies a 12-byte nonce).
33
+ Counter overflow is undefined; see {@link https://mailarchive.ietf.org/arch/msg/cfrg/gsOnTJzcbgG6OqD8Sc0GO5aR_tU/ | the CFRG thread}.
34
+ Current noble policy is strict non-wrap for the shared 32-bit counter path:
35
+ exported ARX ciphers reject initial `0xffffffff` and stop before any implicit
36
+ wrap back to zero.
37
+ See {@link https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-xchacha#appendix-A.2 | the XChaCha appendix} for the extended-nonce construction.
38
+
39
+ * @module
40
+ */
41
+ import { abool, abytes, anumber, checkOpts, clean, copyBytes, getOutput, isAligned32, isLE, randomBytes, swap32IfBE, u32, } from './utils';
42
+ // Replaces `TextEncoder` for ASCII literals, which is enough for sigma constants.
43
+ // Non-ASCII input would not match UTF-8 `TextEncoder` output.
44
+ const encodeStr = (str) => Uint8Array.from(str.split(''), (c) => c.charCodeAt(0));
45
+ // Raw `createCipher(...)` exports consume these native-endian `u32(...)` views directly.
46
+ // Public `wrapCipher(...)` APIs reject non-little-endian platforms before reaching this path.
47
+ // RFC 8439 §2.3 / RFC 7539 §2.3 only define the 256-bit-key constants; this 16-byte sigma is
48
+ // kept for legacy allowShortKeys Salsa/ChaCha variants.
49
+ const sigma16_32 = /* @__PURE__ */ (() => swap32IfBE(u32(encodeStr('expand 16-byte k'))))();
50
+ // RFC 8439 §2.3 / RFC 7539 §2.3 define words 0-3 as
51
+ // `0x61707865 0x3320646e 0x79622d32 0x6b206574`, i.e. `expand 32-byte k`.
52
+ const sigma32_32 = /* @__PURE__ */ (() => swap32IfBE(u32(encodeStr('expand 32-byte k'))))();
53
+ /**
54
+ * Rotates a 32-bit word left.
55
+ * @param a - Input word.
56
+ * @param b - Rotation count in bits.
57
+ * @returns Rotated 32-bit word.
58
+ * @example
59
+ * Moves the top byte of `0x12345678` into the low byte position.
60
+ * ```ts
61
+ * rotl(0x12345678, 8);
62
+ * ```
63
+ */
64
+ export function rotl(a, b) {
65
+ return (a << b) | (a >>> (32 - b));
66
+ }
67
+ // Salsa and Chacha block length is always 512-bit
68
+ const BLOCK_LEN = 64;
69
+ // RFC 8439 §2.2 / RFC 7539 §2.2: the ChaCha state has 16 32-bit words.
70
+ const BLOCK_LEN32 = 16;
71
+ // Counter policy for the shared public `counter` argument:
72
+ // - RFC/IETF ChaCha20 uses a 32-bit counter.
73
+ // - OpenSSL/Node `chacha20` instead treat the full 16-byte IV as a 128-bit
74
+ // counter state and carry into the next word.
75
+ // - Raw `chacha20orig`, `salsa20`, `xsalsa20`, and `xchacha20` use 64-bit counters in libsodium
76
+ // and libtomcrypt, while some libs (for example libtomcrypt's RFC/IETF path) reject the max
77
+ // boundary instead of carrying.
78
+ // - AEAD wrappers diverge too: libsodium `xchacha20poly1305` uses the IETF payload counter from
79
+ // block 1, while `secretstream_xchacha20poly1305` is a different protocol with rekey/reset.
80
+ // Noble intentionally throws instead of silently picking one wrap model for users. In the default
81
+ // path, even a 32-bit boundary would take 2^32 blocks * 64 bytes = 256 GiB, which is practically
82
+ // unreachable for normal JS callers; advanced users who pass `counter` explicitly can implement
83
+ // whatever wider carry / wrap policy they need on top.
84
+ const MAX_COUNTER = /* @__PURE__ */ (() => 2 ** 32 - 1)();
85
+ const U32_EMPTY = /* @__PURE__ */ Uint32Array.of();
86
+ function runCipher(core, sigma, key, nonce, data, output, counter, rounds) {
87
+ const len = data.length;
88
+ const block = new Uint8Array(BLOCK_LEN);
89
+ const b32 = u32(block);
90
+ // Make sure that buffers aligned to 4 bytes
91
+ const isAligned = isLE && isAligned32(data) && isAligned32(output);
92
+ const d32 = isAligned ? u32(data) : U32_EMPTY;
93
+ const o32 = isAligned ? u32(output) : U32_EMPTY;
94
+ // RFC 8439 §2.4.1 / RFC 7539 §2.4.1 allow XORing one keystream block at a time and
95
+ // truncating the final partial block instead of materializing the whole keystream.
96
+ if (!isLE) {
97
+ for (let pos = 0; pos < len; counter++) {
98
+ core(sigma, key, nonce, b32, counter, rounds);
99
+ // RFC 8439 §2.4 / RFC 7539 §2.4 serialize keystream words in little-endian order.
100
+ swap32IfBE(b32);
101
+ if (counter >= MAX_COUNTER)
102
+ throw new Error('arx: counter overflow');
103
+ const take = Math.min(BLOCK_LEN, len - pos);
104
+ for (let j = 0, posj; j < take; j++) {
105
+ posj = pos + j;
106
+ output[posj] = data[posj] ^ block[j];
107
+ }
108
+ pos += take;
109
+ }
110
+ return;
111
+ }
112
+ for (let pos = 0; pos < len; counter++) {
113
+ core(sigma, key, nonce, b32, counter, rounds);
114
+ // See MAX_COUNTER policy note above: never silently wrap the shared public counter.
115
+ if (counter >= MAX_COUNTER)
116
+ throw new Error('arx: counter overflow');
117
+ const take = Math.min(BLOCK_LEN, len - pos);
118
+ // aligned to 4 bytes
119
+ if (isAligned && take === BLOCK_LEN) {
120
+ const pos32 = pos / 4;
121
+ if (pos % 4 !== 0)
122
+ throw new Error('arx: invalid block position');
123
+ for (let j = 0, posj; j < BLOCK_LEN32; j++) {
124
+ posj = pos32 + j;
125
+ o32[posj] = d32[posj] ^ b32[j];
126
+ }
127
+ pos += BLOCK_LEN;
128
+ continue;
129
+ }
130
+ for (let j = 0, posj; j < take; j++) {
131
+ posj = pos + j;
132
+ output[posj] = data[posj] ^ block[j];
133
+ }
134
+ pos += take;
135
+ }
136
+ }
137
+ /**
138
+ * Creates an ARX stream cipher from a 32-bit core permutation.
139
+ * Used internally to build the exported Salsa and ChaCha stream ciphers.
140
+ * @param core - Core function that fills one keystream block.
141
+ * @param opts - Cipher layout and nonce-extension options. See {@link CipherOpts}.
142
+ * @returns Stream cipher function over byte arrays.
143
+ * @throws If the core callback, key size, counter, or output sizing is invalid. {@link Error}
144
+ */
145
+ export function createCipher(core, opts) {
146
+ const { allowShortKeys, extendNonceFn, counterLength, counterRight, rounds } = checkOpts({ allowShortKeys: false, counterLength: 8, counterRight: false, rounds: 20 }, opts);
147
+ if (typeof core !== 'function')
148
+ throw new Error('core must be a function');
149
+ anumber(counterLength);
150
+ anumber(rounds);
151
+ abool(counterRight);
152
+ abool(allowShortKeys);
153
+ return (key, nonce, data, output, counter = 0) => {
154
+ abytes(key, undefined, 'key');
155
+ abytes(nonce, undefined, 'nonce');
156
+ abytes(data, undefined, 'data');
157
+ const len = data.length;
158
+ // Raw XorStream APIs return ciphertext/plaintext bytes directly, so caller-provided outputs
159
+ // must match the logical result length exactly instead of returning an oversized workspace.
160
+ output = getOutput(len, output, false);
161
+ anumber(counter);
162
+ // See MAX_COUNTER policy note above: reject advanced explicit-counter requests before any wrap.
163
+ if (counter < 0 || counter >= MAX_COUNTER)
164
+ throw new Error('arx: counter overflow');
165
+ const toClean = [];
166
+ // Key & sigma
167
+ // key=16 -> sigma16, k=key|key
168
+ // key=32 -> sigma32, k=key
169
+ let l = key.length;
170
+ let k;
171
+ let sigma;
172
+ if (l === 32) {
173
+ // Copy caller keys too: big-endian normalization, extended-nonce subkey derivation, and
174
+ // final clean(...) all mutate or wipe the temporary buffer in place.
175
+ toClean.push((k = copyBytes(key)));
176
+ sigma = sigma32_32;
177
+ }
178
+ else if (l === 16 && allowShortKeys) {
179
+ k = new Uint8Array(32);
180
+ k.set(key);
181
+ k.set(key, 16);
182
+ sigma = sigma16_32;
183
+ toClean.push(k);
184
+ }
185
+ else {
186
+ abytes(key, 32, 'arx key');
187
+ throw new Error('invalid key size');
188
+ // throw new Error(`"arx key" expected Uint8Array of length 32, got length=${l}`);
189
+ }
190
+ // Nonce
191
+ // salsa20: 8 (8-byte counter)
192
+ // chacha20orig: 8 (8-byte counter)
193
+ // chacha20: 12 (4-byte counter)
194
+ // xsalsa20: 24 (16 -> hsalsa, 8 -> old nonce)
195
+ // xchacha20: 24 (16 -> hchacha, 8 -> old nonce)
196
+ // Copy before taking u32(...) views on misaligned inputs, and on big-endian so later
197
+ // swap32IfBE(...) never mutates caller nonce bytes in place.
198
+ if (!isLE || !isAligned32(nonce))
199
+ toClean.push((nonce = copyBytes(nonce)));
200
+ let k32 = u32(k);
201
+ // hsalsa & hchacha: handle extended nonce
202
+ if (extendNonceFn) {
203
+ if (nonce.length !== 24)
204
+ throw new Error(`arx: extended nonce must be 24 bytes`);
205
+ const n16 = nonce.subarray(0, 16);
206
+ if (isLE)
207
+ extendNonceFn(sigma, k32, u32(n16), k32);
208
+ else {
209
+ const sigmaRaw = swap32IfBE(Uint32Array.from(sigma));
210
+ extendNonceFn(sigmaRaw, k32, u32(n16), k32);
211
+ clean(sigmaRaw);
212
+ swap32IfBE(k32);
213
+ }
214
+ nonce = nonce.subarray(16);
215
+ }
216
+ else if (!isLE)
217
+ swap32IfBE(k32);
218
+ // Handle nonce counter
219
+ const nonceNcLen = 16 - counterLength;
220
+ if (nonceNcLen !== nonce.length)
221
+ throw new Error(`arx: nonce must be ${nonceNcLen} or 16 bytes`);
222
+ // Normalize 64-bit-nonce layouts to the 12-byte core input: ChaCha/XChaCha prefix 4 zero
223
+ // counter bytes, while Salsa/XSalsa append them after the nonce words.
224
+ if (nonceNcLen !== 12) {
225
+ const nc = new Uint8Array(12);
226
+ nc.set(nonce, counterRight ? 0 : 12 - nonce.length);
227
+ nonce = nc;
228
+ toClean.push(nonce);
229
+ }
230
+ const n32 = swap32IfBE(u32(nonce));
231
+ // Ensure temporary key/nonce copies are wiped even if the remaining
232
+ // runtime guard in runCipher(...) throws on counter overflow.
233
+ try {
234
+ runCipher(core, sigma, k32, n32, data, output, counter, rounds);
235
+ return output;
236
+ }
237
+ finally {
238
+ clean(...toClean);
239
+ }
240
+ };
241
+ }
242
+ /** Internal class which wraps chacha20 or chacha8 to create CSPRNG. */
243
+ export class _XorStreamPRG {
244
+ blockLen;
245
+ keyLen;
246
+ nonceLen;
247
+ state;
248
+ buf;
249
+ key;
250
+ nonce;
251
+ pos;
252
+ ctr;
253
+ cipher;
254
+ constructor(cipher, blockLen, keyLen, nonceLen, seed) {
255
+ this.cipher = cipher;
256
+ this.blockLen = blockLen;
257
+ this.keyLen = keyLen;
258
+ this.nonceLen = nonceLen;
259
+ this.state = new Uint8Array(this.keyLen + this.nonceLen);
260
+ this.reseed(seed);
261
+ this.ctr = 0;
262
+ this.pos = this.blockLen;
263
+ this.buf = new Uint8Array(this.blockLen);
264
+ // Keep a single key||nonce backing buffer so reseed/addEntropy/clean update the live cipher
265
+ // inputs in place through these subarray views.
266
+ this.key = this.state.subarray(0, this.keyLen);
267
+ this.nonce = this.state.subarray(this.keyLen);
268
+ }
269
+ reseed(seed) {
270
+ abytes(seed);
271
+ if (!seed || seed.length === 0)
272
+ throw new Error('entropy required');
273
+ // Mix variable-length entropy cyclically across the whole key||nonce state, then restart the
274
+ // keystream so buffered leftovers from the previous state are never reused.
275
+ for (let i = 0; i < seed.length; i++)
276
+ this.state[i % this.state.length] ^= seed[i];
277
+ this.ctr = 0;
278
+ this.pos = this.blockLen;
279
+ }
280
+ addEntropy(seed) {
281
+ // Reject empty entropy before re-keying, otherwise a throwing call would still advance state.
282
+ abytes(seed);
283
+ if (seed.length === 0)
284
+ throw new Error('entropy required');
285
+ // Re-key from the current stream first, then mix external entropy into the fresh key||nonce
286
+ // state through reseed() so stale buffered bytes are discarded.
287
+ this.state.set(this.randomBytes(this.state.length));
288
+ this.reseed(seed);
289
+ }
290
+ randomBytes(len) {
291
+ anumber(len);
292
+ if (len === 0)
293
+ return new Uint8Array(0);
294
+ const avail = this.pos < this.blockLen ? this.blockLen - this.pos : 0;
295
+ const blocks = Math.ceil(Math.max(0, len - avail) / this.blockLen);
296
+ // Preflight overflow so failed reads don't partially consume keystream
297
+ // and leave the PRG repeating blocks.
298
+ if (blocks > 0 && this.ctr > MAX_COUNTER - blocks)
299
+ throw new Error('arx: counter overflow');
300
+ const out = new Uint8Array(len);
301
+ let outPos = 0;
302
+ // `out` starts zero-filled, and `buf.fill(0)` below does the same for leftovers: XOR-stream
303
+ // ciphers then emit raw keystream bytes directly into those buffers.
304
+ // Serve buffered leftovers first so split reads stay identical to one larger read.
305
+ if (this.pos < this.blockLen) {
306
+ const take = Math.min(len, this.blockLen - this.pos);
307
+ out.set(this.buf.subarray(this.pos, this.pos + take), 0);
308
+ this.pos += take;
309
+ outPos += take;
310
+ if (outPos === len)
311
+ return out; // fast path
312
+ }
313
+ // Full blocks directly to out
314
+ const full = Math.floor((len - outPos) / this.blockLen);
315
+ if (full > 0) {
316
+ const blockBytes = full * this.blockLen;
317
+ const b = out.subarray(outPos, outPos + blockBytes);
318
+ this.cipher(this.key, this.nonce, b, b, this.ctr);
319
+ this.ctr += full;
320
+ outPos += blockBytes;
321
+ }
322
+ // Save leftovers
323
+ const left = len - outPos;
324
+ if (left > 0) {
325
+ this.buf.fill(0);
326
+ // NOTE: cipher will handle overflow
327
+ this.cipher(this.key, this.nonce, this.buf, this.buf, this.ctr++);
328
+ out.set(this.buf.subarray(0, left), outPos);
329
+ this.pos = left;
330
+ }
331
+ return out;
332
+ }
333
+ // Clone seeds the new instance from this stream, so the source PRG advances too.
334
+ clone() {
335
+ return new _XorStreamPRG(this.cipher, this.blockLen, this.keyLen, this.nonceLen, this.randomBytes(this.state.length));
336
+ }
337
+ // Zeroes the current state and leftover buffer, but does not make the instance unusable:
338
+ // Later reads first drain zeros from the cleared buffer and then continue
339
+ // from zero key||nonce state.
340
+ clean() {
341
+ this.pos = 0;
342
+ this.ctr = 0;
343
+ this.buf.fill(0);
344
+ this.state.fill(0);
345
+ }
346
+ }
347
+ /**
348
+ * Creates a PRG constructor from a stream cipher.
349
+ * @param cipher - Stream cipher used to fill output blocks.
350
+ * @param blockLen - Keystream block length in bytes.
351
+ * @param keyLen - Internal key length in bytes.
352
+ * @param nonceLen - Internal nonce length in bytes.
353
+ * @returns PRG factory for seeded concrete `_XorStreamPRG` instances.
354
+ * @example
355
+ * Builds a PRG from XChaCha20 and reads bytes from a randomly seeded instance.
356
+ * ```ts
357
+ * import { xchacha20 } from './chacha';
358
+ * import { createPRG } from './_arx';
359
+ * import { randomBytes } from './utils';
360
+ * const seed = randomBytes(32);
361
+ * const init = createPRG(xchacha20, 64, 32, 24);
362
+ * const prg = init(seed);
363
+ * prg.randomBytes(8);
364
+ * ```
365
+ */
366
+ export const createPRG = (cipher, blockLen, keyLen, nonceLen) => {
367
+ return ((seed = randomBytes(32)) => new _XorStreamPRG(cipher, blockLen, keyLen, nonceLen, seed));
368
+ };