@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/LICENSE +22 -0
- package/README.md +75 -0
- package/_arx.d.ts +144 -0
- package/_arx.js +375 -0
- package/_poly1305.d.ts +72 -0
- package/_poly1305.js +367 -0
- package/_polyval.d.ts +120 -0
- package/_polyval.js +335 -0
- package/aes.d.ts +461 -0
- package/aes.js +1768 -0
- package/chacha.d.ts +248 -0
- package/chacha.js +579 -0
- package/esm/_arx.js +368 -0
- package/esm/_poly1305.js +363 -0
- package/esm/_polyval.js +329 -0
- package/esm/aes.js +1764 -0
- package/esm/chacha.js +574 -0
- package/esm/ff1.js +203 -0
- package/esm/index.js +26 -0
- package/esm/salsa.js +370 -0
- package/esm/utils.js +806 -0
- package/esm/webcrypto.js +166 -0
- package/ff1.d.ts +39 -0
- package/ff1.js +207 -0
- package/index.d.ts +0 -0
- package/index.js +26 -0
- package/package.json +45 -0
- package/salsa.d.ts +114 -0
- package/salsa.js +375 -0
- package/utils.d.ts +716 -0
- package/utils.js +841 -0
- package/webcrypto.d.ts +88 -0
- package/webcrypto.js +169 -0
package/esm/ff1.js
ADDED
|
@@ -0,0 +1,203 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* FPE-FF1 (Format-preserving encryption algorithm) specified in
|
|
3
|
+
* {@link https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-38G.pdf | NIST 800-38G}.
|
|
4
|
+
* @module
|
|
5
|
+
*/
|
|
6
|
+
import { unsafe } from './aes';
|
|
7
|
+
import { abytes, anumber, bytesToNumberBE, clean, numberToBytesBE, } from './utils';
|
|
8
|
+
// NIST SP 800-38G §4.3 / §5.1 Algorithm 7: FF1's designated CIPH_K here is AES, so this file
|
|
9
|
+
// reuses the reviewed AES key schedule and single-block encryption helpers.
|
|
10
|
+
// NOTE: no point in inlining encrypt instead of encryptBlock, since BigInt stuff will be slow
|
|
11
|
+
const { expandKeyLE, encryptBlock } = unsafe;
|
|
12
|
+
// Format-preserving encryption algorithm (FPE-FF1) specified in
|
|
13
|
+
// {@link https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-38G.pdf | NIST Special Publication 800-38G}.
|
|
14
|
+
const BLOCK_LEN = 16;
|
|
15
|
+
function mod(a, b) {
|
|
16
|
+
const result = a % b;
|
|
17
|
+
return result >= 0 ? result : b + result;
|
|
18
|
+
}
|
|
19
|
+
function NUMradix(radix, data) {
|
|
20
|
+
let res = BigInt(0);
|
|
21
|
+
for (let i of data)
|
|
22
|
+
res = res * BigInt(radix) + BigInt(i);
|
|
23
|
+
return res;
|
|
24
|
+
}
|
|
25
|
+
function getRound(radix, key, tweak, x) {
|
|
26
|
+
if (radix > 2 ** 16 - 1)
|
|
27
|
+
throw new Error('invalid radix ' + radix);
|
|
28
|
+
// radix**minlen ≥ 100
|
|
29
|
+
const minLen = Math.ceil(Math.log(100) / Math.log(radix));
|
|
30
|
+
const maxLen = 2 ** 32 - 1;
|
|
31
|
+
// 2 ≤ minlen ≤ maxlen < 2**32
|
|
32
|
+
if (2 > minLen || minLen > maxLen || maxLen >= 2 ** 32)
|
|
33
|
+
throw new Error('Invalid radix: 2 ≤ minlen ≤ maxlen < 2**32');
|
|
34
|
+
if (!Array.isArray(x))
|
|
35
|
+
throw new Error('invalid X');
|
|
36
|
+
if (x.length < minLen || x.length > maxLen)
|
|
37
|
+
throw new Error('X is outside minLen..maxLen bounds');
|
|
38
|
+
// SP 800-38G defines FF1 over numeral strings in base `radix`; out-of-range digits must fail
|
|
39
|
+
// before NUMradix(...) or round splitting can reinterpret them as a different numeral string.
|
|
40
|
+
for (const i of x) {
|
|
41
|
+
if (!Number.isSafeInteger(i) || i < 0 || i >= radix)
|
|
42
|
+
throw new Error('invalid X: digit outside radix');
|
|
43
|
+
}
|
|
44
|
+
const u = Math.floor(x.length / 2);
|
|
45
|
+
const v = x.length - u;
|
|
46
|
+
const b = Math.ceil(Math.ceil(v * Math.log2(radix)) / 8);
|
|
47
|
+
const d = 4 * Math.ceil(b / 4) + 4;
|
|
48
|
+
const padding = mod(-tweak.length - b - 1, 16);
|
|
49
|
+
// P = [1]1 || [2]1 || [1]1 || [radix]3 || [10]1 || [u mod 256]1 || [n]4 || [t]4.
|
|
50
|
+
const P = Uint8Array.from([1, 2, 1, 0, 0, 0, 10, u, 0, 0, 0, 0, 0, 0, 0, 0]);
|
|
51
|
+
const view = new DataView(P.buffer);
|
|
52
|
+
// NIST SP 800-38G §5.1 bounds radix <= 2^16, so the 24-bit [radix]3 field is encoded here as
|
|
53
|
+
// 0x00 || uint16_be(radix).
|
|
54
|
+
view.setUint16(4, radix, false);
|
|
55
|
+
view.setUint32(8, x.length, false);
|
|
56
|
+
view.setUint32(12, tweak.length, false);
|
|
57
|
+
// Q = T || [0](−t−b−1) mod 16 || [i]1 || [NUMradix(B)]b.
|
|
58
|
+
const PQ = new Uint8Array(P.length + tweak.length + padding + 1 + b);
|
|
59
|
+
PQ.set(P);
|
|
60
|
+
clean(P);
|
|
61
|
+
PQ.set(tweak, P.length);
|
|
62
|
+
const xk = expandKeyLE(key);
|
|
63
|
+
const round = (A, B, i, decrypt = false) => {
|
|
64
|
+
// Q = ... || [i]1 || [NUMradix(B)]b.
|
|
65
|
+
PQ[PQ.length - b - 1] = i;
|
|
66
|
+
if (b)
|
|
67
|
+
PQ.set(numberToBytesBE(NUMradix(radix, B), b), PQ.length - b);
|
|
68
|
+
// NIST SP 800-38G Algorithm 6 PRF: Y_j = CIPH_K(Y_(j-1) xor X_j) starting from Y_0 = 0^128.
|
|
69
|
+
let r = new Uint8Array(16);
|
|
70
|
+
for (let j = 0; j < PQ.length / BLOCK_LEN; j++) {
|
|
71
|
+
for (let i = 0; i < BLOCK_LEN; i++)
|
|
72
|
+
r[i] ^= PQ[j * BLOCK_LEN + i];
|
|
73
|
+
encryptBlock(xk, r);
|
|
74
|
+
}
|
|
75
|
+
// Let S be the first d bytes of the following string of ⎡d/16⎤ blocks:
|
|
76
|
+
// R || CIPHK(R ⊕[1]16) || CIPHK(R ⊕[2]16) ...CIPHK(R ⊕[⎡d / 16⎤ – 1]16).
|
|
77
|
+
let s = Array.from(r);
|
|
78
|
+
for (let j = 1; s.length < d; j++) {
|
|
79
|
+
const block = numberToBytesBE(BigInt(j), 16);
|
|
80
|
+
for (let k = 0; k < BLOCK_LEN; k++)
|
|
81
|
+
block[k] ^= r[k];
|
|
82
|
+
s.push(...Array.from(encryptBlock(xk, block)));
|
|
83
|
+
}
|
|
84
|
+
let y = bytesToNumberBE(Uint8Array.from(s.slice(0, d)));
|
|
85
|
+
s.fill(0);
|
|
86
|
+
if (decrypt)
|
|
87
|
+
y = -y;
|
|
88
|
+
const m = i % 2 === 0 ? u : v;
|
|
89
|
+
let c = mod(NUMradix(radix, A) + y, BigInt(radix) ** BigInt(m));
|
|
90
|
+
// STR(radix, m, c)
|
|
91
|
+
const C = Array(m).fill(0);
|
|
92
|
+
for (let i = 0; i < m; i++, c /= BigInt(radix))
|
|
93
|
+
C[m - 1 - i] = Number(c % BigInt(radix));
|
|
94
|
+
A.fill(0);
|
|
95
|
+
A = B;
|
|
96
|
+
B = C;
|
|
97
|
+
return [A, B];
|
|
98
|
+
};
|
|
99
|
+
const destroy = () => {
|
|
100
|
+
clean(xk, PQ);
|
|
101
|
+
};
|
|
102
|
+
return { u, round, destroy };
|
|
103
|
+
}
|
|
104
|
+
const EMPTY_BUF = /* @__PURE__ */ Uint8Array.of();
|
|
105
|
+
/**
|
|
106
|
+
* FPE-FF1 format-preserving encryption.
|
|
107
|
+
* @param radix - Alphabet size for each input digit.
|
|
108
|
+
* @param key - AES key bytes.
|
|
109
|
+
* @param tweak - Optional tweak bytes.
|
|
110
|
+
* @returns Encrypt/decrypt helpers over digit arrays.
|
|
111
|
+
* @example
|
|
112
|
+
* Encrypts decimal digits without changing their format, using a fresh AES key.
|
|
113
|
+
*
|
|
114
|
+
* ```ts
|
|
115
|
+
* import { FF1 } from './ff1';
|
|
116
|
+
* import { randomBytes } from './utils';
|
|
117
|
+
* const key = randomBytes(16);
|
|
118
|
+
* const ff1 = FF1(10, key);
|
|
119
|
+
* ff1.encrypt([1, 2, 3]);
|
|
120
|
+
* ```
|
|
121
|
+
*/
|
|
122
|
+
export function FF1(radix, key, tweak = EMPTY_BUF) {
|
|
123
|
+
anumber(radix);
|
|
124
|
+
abytes(key);
|
|
125
|
+
abytes(tweak);
|
|
126
|
+
// This borrows caller key/tweak buffers by reference through the bound closure; mutating them
|
|
127
|
+
// after construction changes later encrypt/decrypt outputs.
|
|
128
|
+
const PQ = getRound.bind(null, radix, key, tweak);
|
|
129
|
+
return {
|
|
130
|
+
encrypt(x) {
|
|
131
|
+
const { u, round, destroy } = PQ(x);
|
|
132
|
+
let [A, B] = [x.slice(0, u), x.slice(u)];
|
|
133
|
+
for (let i = 0; i < 10; i++)
|
|
134
|
+
[A, B] = round(A, B, i);
|
|
135
|
+
destroy();
|
|
136
|
+
const res = A.concat(B);
|
|
137
|
+
A.fill(0);
|
|
138
|
+
B.fill(0);
|
|
139
|
+
return res;
|
|
140
|
+
},
|
|
141
|
+
decrypt(x) {
|
|
142
|
+
const { u, round, destroy } = PQ(x);
|
|
143
|
+
// The FF1.Decrypt algorithm is similar to the FF1.Encrypt algorithm;
|
|
144
|
+
// the differences are in Step 6, where:
|
|
145
|
+
// 1) the order of the indices is reversed,
|
|
146
|
+
// 2) the roles of A and B are swapped
|
|
147
|
+
// 3) modular addition is replaced by modular subtraction, in Step 6vi.
|
|
148
|
+
let [B, A] = [x.slice(0, u), x.slice(u)];
|
|
149
|
+
for (let i = 9; i >= 0; i--)
|
|
150
|
+
[A, B] = round(A, B, i, true);
|
|
151
|
+
destroy();
|
|
152
|
+
const res = B.concat(A);
|
|
153
|
+
A.fill(0);
|
|
154
|
+
B.fill(0);
|
|
155
|
+
return res;
|
|
156
|
+
},
|
|
157
|
+
};
|
|
158
|
+
}
|
|
159
|
+
// Binary wrapper uses little-endian bit order within each byte so bit 0 stays
|
|
160
|
+
// in the first numeral slot for this library-defined byte-array surface.
|
|
161
|
+
const binLE = {
|
|
162
|
+
encode(bytes) {
|
|
163
|
+
const x = [];
|
|
164
|
+
for (let i = 0; i < bytes.length; i++) {
|
|
165
|
+
for (let j = 0, tmp = bytes[i]; j < 8; j++, tmp >>= 1)
|
|
166
|
+
x.push(tmp & 1);
|
|
167
|
+
}
|
|
168
|
+
return x;
|
|
169
|
+
},
|
|
170
|
+
decode(b) {
|
|
171
|
+
if (!Array.isArray(b) || b.length % 8)
|
|
172
|
+
throw new Error('Invalid binary string');
|
|
173
|
+
const res = new Uint8Array(b.length / 8);
|
|
174
|
+
for (let i = 0, j = 0; i < res.length; i++) {
|
|
175
|
+
res[i] = b[j++] | (b[j++] << 1) | (b[j++] << 2) | (b[j++] << 3);
|
|
176
|
+
res[i] |= (b[j++] << 4) | (b[j++] << 5) | (b[j++] << 6) | (b[j++] << 7);
|
|
177
|
+
}
|
|
178
|
+
return res;
|
|
179
|
+
},
|
|
180
|
+
};
|
|
181
|
+
/**
|
|
182
|
+
* Binary FPE-FF1 wrapper over byte arrays.
|
|
183
|
+
* @param key - AES key bytes.
|
|
184
|
+
* @param tweak - Optional tweak bytes.
|
|
185
|
+
* @returns Encrypt/decrypt helpers over byte arrays.
|
|
186
|
+
* @example
|
|
187
|
+
* Encrypts raw bytes through FF1's binary alphabet wrapper with a fresh AES key.
|
|
188
|
+
*
|
|
189
|
+
* ```ts
|
|
190
|
+
* import { BinaryFF1 } from './ff1';
|
|
191
|
+
* import { randomBytes } from './utils';
|
|
192
|
+
* const key = randomBytes(16);
|
|
193
|
+
* const ff1 = BinaryFF1(key);
|
|
194
|
+
* ff1.encrypt(new Uint8Array([1, 2, 3]));
|
|
195
|
+
* ```
|
|
196
|
+
*/
|
|
197
|
+
export function BinaryFF1(key, tweak = EMPTY_BUF) {
|
|
198
|
+
const ff1 = FF1(2, key, tweak);
|
|
199
|
+
return {
|
|
200
|
+
encrypt: (x) => binLE.decode(ff1.encrypt(binLE.encode(x))),
|
|
201
|
+
decrypt: (x) => binLE.decode(ff1.decrypt(binLE.encode(x))),
|
|
202
|
+
};
|
|
203
|
+
}
|
package/esm/index.js
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* Audited & minimal JS implementation of Salsa20, ChaCha and AES. Check out individual modules.
|
|
4
|
+
* @example
|
|
5
|
+
```js
|
|
6
|
+
import { gcm, aessiv } from './aes';
|
|
7
|
+
import { xsalsa20poly1305 } from './salsa';
|
|
8
|
+
import { secretbox } from './salsa'; // == xsalsa20poly1305
|
|
9
|
+
import { chacha20poly1305, xchacha20poly1305 } from './chacha';
|
|
10
|
+
|
|
11
|
+
// Unauthenticated encryption: make sure to use HMAC or similar
|
|
12
|
+
import { ctr, cfb, cbc, ecb } from './aes';
|
|
13
|
+
import { salsa20, xsalsa20 } from './salsa';
|
|
14
|
+
import { chacha20, xchacha20, chacha8, chacha12 } from './chacha';
|
|
15
|
+
|
|
16
|
+
// KW
|
|
17
|
+
import { aeskw, aeskwp } from './aes';
|
|
18
|
+
|
|
19
|
+
// Utilities
|
|
20
|
+
import { managedNonce, randomBytes, bytesToHex, hexToBytes } from './utils';
|
|
21
|
+
import { poly1305 } from './_poly1305';
|
|
22
|
+
import { ghash, polyval } from './_polyval';
|
|
23
|
+
```
|
|
24
|
+
* @module
|
|
25
|
+
*/
|
|
26
|
+
throw new Error('root module cannot be imported: import submodules instead. Check out README');
|
package/esm/salsa.js
ADDED
|
@@ -0,0 +1,370 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Salsa20 stream cipher, released in 2005.
|
|
3
|
+
* Salsa's goal was to implement AES replacement that does not rely on S-Boxes,
|
|
4
|
+
* which are hard to implement in a constant-time manner.
|
|
5
|
+
* Salsa20 is usually faster than AES, a big deal on slow, budget mobile phones.
|
|
6
|
+
*
|
|
7
|
+
* - {@link https://cr.yp.to/snuffle/xsalsa-20110204.pdf | XSalsa20},
|
|
8
|
+
* extended-nonce
|
|
9
|
+
* variant was released in 2008. It extends Salsa20's 64-bit nonce to 192 bits,
|
|
10
|
+
* and became safe to be picked at random.
|
|
11
|
+
* - Nacl / Libsodium popularized term "secretbox", - which is just xsalsa20poly1305.
|
|
12
|
+
* We provide the alias and corresponding seal / open methods.
|
|
13
|
+
* "crypto_box" and "sealedbox" are available in package
|
|
14
|
+
* {@link https://github.com/serenity-kit/noble-sodium | noble-sodium}.
|
|
15
|
+
* - Check out
|
|
16
|
+
* {@link https://cr.yp.to/snuffle/salsafamily-20071225.pdf | PDF}
|
|
17
|
+
* and {@link https://cr.yp.to/snuffle.html | website}.
|
|
18
|
+
* @module
|
|
19
|
+
*/
|
|
20
|
+
import { createCipher, rotl } from './_arx';
|
|
21
|
+
import { poly1305 } from './_poly1305';
|
|
22
|
+
import { abytes, clean, equalBytes, getOutput, swap32IfBE, swap8IfBE, wrapCipher, } from './utils';
|
|
23
|
+
/**
|
|
24
|
+
* Salsa20 core function. It is implemented twice:
|
|
25
|
+
* 1. Simple loop (salsaCore_small, hsalsa_small)
|
|
26
|
+
* 2. Unrolled loop (salsaCore, hsalsa) - 4x faster, but larger & harder to read
|
|
27
|
+
* The specific implementation is selected in `createCipher` below.
|
|
28
|
+
* Performance numbers for 1MB inputs:
|
|
29
|
+
* * default x 779 ops/sec @ 1ms/op
|
|
30
|
+
* * if salsa+hsalsa are merged x 459 ops/sec @ 2ms/op
|
|
31
|
+
* * small x 132 ops/sec @ 7ms/op
|
|
32
|
+
*/
|
|
33
|
+
/** RFC 7914 §3 Salsa20/8 core quarter-round on words a, b, c, d. */
|
|
34
|
+
function salsaQR(x, a, b, c, d) {
|
|
35
|
+
x[b] ^= rotl((x[a] + x[d]) | 0, 7);
|
|
36
|
+
x[c] ^= rotl((x[b] + x[a]) | 0, 9);
|
|
37
|
+
x[d] ^= rotl((x[c] + x[b]) | 0, 13);
|
|
38
|
+
x[a] ^= rotl((x[d] + x[c]) | 0, 18);
|
|
39
|
+
}
|
|
40
|
+
/** RFC 7914 §3 double-round schedule: four column rounds, then four row rounds. */
|
|
41
|
+
function salsaRound(x, rounds = 20) {
|
|
42
|
+
for (let r = 0; r < rounds; r += 2) {
|
|
43
|
+
salsaQR(x, 0, 4, 8, 12);
|
|
44
|
+
salsaQR(x, 5, 9, 13, 1);
|
|
45
|
+
salsaQR(x, 10, 14, 2, 6);
|
|
46
|
+
salsaQR(x, 15, 3, 7, 11);
|
|
47
|
+
salsaQR(x, 0, 1, 2, 3);
|
|
48
|
+
salsaQR(x, 5, 6, 7, 4);
|
|
49
|
+
salsaQR(x, 10, 11, 8, 9);
|
|
50
|
+
salsaQR(x, 15, 12, 13, 14);
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
// Shared scratch for the unused auditability helper below; it would be
|
|
54
|
+
// non-reentrant under overlapping/nested calls, but current code doesn't invoke it.
|
|
55
|
+
const stmp = /* @__PURE__ */ new Uint32Array(16);
|
|
56
|
+
/** Small version of salsa without loop unrolling. Unused, provided for auditability. */
|
|
57
|
+
// prettier-ignore
|
|
58
|
+
function salsa(s, k, i, out, isHSalsa = true, rounds = 20) {
|
|
59
|
+
// Create initial array using common pattern
|
|
60
|
+
const y = Uint32Array.from([
|
|
61
|
+
s[0], k[0], k[1], k[2], // "expa" Key Key Key
|
|
62
|
+
k[3], s[1], i[0], i[1], // Key "nd 3" Nonce Nonce
|
|
63
|
+
i[2], i[3], s[2], k[4], // Pos. Pos. "2-by" Key
|
|
64
|
+
k[5], k[6], k[7], s[3], // Key Key Key "te k"
|
|
65
|
+
]);
|
|
66
|
+
const x = stmp;
|
|
67
|
+
x.set(y);
|
|
68
|
+
// const x = y.slice();
|
|
69
|
+
salsaRound(x, rounds);
|
|
70
|
+
// hsalsa extracts 8 specific words for the 32-byte subkey; salsa adds the original state.
|
|
71
|
+
if (isHSalsa) {
|
|
72
|
+
const xindexes = [0, 5, 10, 15, 6, 7, 8, 9];
|
|
73
|
+
for (let i = 0; i < 8; i++)
|
|
74
|
+
out[i] = x[xindexes[i]];
|
|
75
|
+
}
|
|
76
|
+
else {
|
|
77
|
+
for (let i = 0; i < 16; i++)
|
|
78
|
+
out[i] = (y[i] + x[i]) | 0;
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
/** Identical to `salsaCore`. Unused. */
|
|
82
|
+
// @ts-ignore
|
|
83
|
+
const salsaCore_small = (s, k, n, out, cnt, rounds) => salsa(s, k, Uint32Array.from([n[0], n[1], cnt, 0]), out, false, rounds);
|
|
84
|
+
/** Identical to `hsalsa`. Unused. */
|
|
85
|
+
// @ts-ignore
|
|
86
|
+
const hsalsa_small = salsa;
|
|
87
|
+
/** Identical to `salsaCore_small`. Uses only the low 32 bits of Salsa20's 64-bit counter state. */
|
|
88
|
+
// prettier-ignore
|
|
89
|
+
function salsaCore(s, k, n, out, cnt, rounds = 20) {
|
|
90
|
+
// Public wrappers expose only the low 32 bits of Salsa20's 64-bit counter; y09 stays zero.
|
|
91
|
+
// Based on {@link https://cr.yp.to/salsa20.html | the Salsa20 reference page}.
|
|
92
|
+
let y00 = s[0], y01 = k[0], y02 = k[1], y03 = k[2], // "expa" Key Key Key
|
|
93
|
+
y04 = k[3], y05 = s[1], y06 = n[0], y07 = n[1], // Key "nd 3" Nonce Nonce
|
|
94
|
+
y08 = cnt, y09 = 0, y10 = s[2], y11 = k[4], // Pos. Pos. "2-by" Key
|
|
95
|
+
y12 = k[5], y13 = k[6], y14 = k[7], y15 = s[3]; // Key Key Key "te k"
|
|
96
|
+
// Save state to temporary variables
|
|
97
|
+
let x00 = y00, x01 = y01, x02 = y02, x03 = y03, x04 = y04, x05 = y05, x06 = y06, x07 = y07, x08 = y08, x09 = y09, x10 = y10, x11 = y11, x12 = y12, x13 = y13, x14 = y14, x15 = y15;
|
|
98
|
+
for (let r = 0; r < rounds; r += 2) {
|
|
99
|
+
x04 ^= rotl(x00 + x12 | 0, 7);
|
|
100
|
+
x08 ^= rotl(x04 + x00 | 0, 9);
|
|
101
|
+
x12 ^= rotl(x08 + x04 | 0, 13);
|
|
102
|
+
x00 ^= rotl(x12 + x08 | 0, 18);
|
|
103
|
+
x09 ^= rotl(x05 + x01 | 0, 7);
|
|
104
|
+
x13 ^= rotl(x09 + x05 | 0, 9);
|
|
105
|
+
x01 ^= rotl(x13 + x09 | 0, 13);
|
|
106
|
+
x05 ^= rotl(x01 + x13 | 0, 18);
|
|
107
|
+
x14 ^= rotl(x10 + x06 | 0, 7);
|
|
108
|
+
x02 ^= rotl(x14 + x10 | 0, 9);
|
|
109
|
+
x06 ^= rotl(x02 + x14 | 0, 13);
|
|
110
|
+
x10 ^= rotl(x06 + x02 | 0, 18);
|
|
111
|
+
x03 ^= rotl(x15 + x11 | 0, 7);
|
|
112
|
+
x07 ^= rotl(x03 + x15 | 0, 9);
|
|
113
|
+
x11 ^= rotl(x07 + x03 | 0, 13);
|
|
114
|
+
x15 ^= rotl(x11 + x07 | 0, 18);
|
|
115
|
+
x01 ^= rotl(x00 + x03 | 0, 7);
|
|
116
|
+
x02 ^= rotl(x01 + x00 | 0, 9);
|
|
117
|
+
x03 ^= rotl(x02 + x01 | 0, 13);
|
|
118
|
+
x00 ^= rotl(x03 + x02 | 0, 18);
|
|
119
|
+
x06 ^= rotl(x05 + x04 | 0, 7);
|
|
120
|
+
x07 ^= rotl(x06 + x05 | 0, 9);
|
|
121
|
+
x04 ^= rotl(x07 + x06 | 0, 13);
|
|
122
|
+
x05 ^= rotl(x04 + x07 | 0, 18);
|
|
123
|
+
x11 ^= rotl(x10 + x09 | 0, 7);
|
|
124
|
+
x08 ^= rotl(x11 + x10 | 0, 9);
|
|
125
|
+
x09 ^= rotl(x08 + x11 | 0, 13);
|
|
126
|
+
x10 ^= rotl(x09 + x08 | 0, 18);
|
|
127
|
+
x12 ^= rotl(x15 + x14 | 0, 7);
|
|
128
|
+
x13 ^= rotl(x12 + x15 | 0, 9);
|
|
129
|
+
x14 ^= rotl(x13 + x12 | 0, 13);
|
|
130
|
+
x15 ^= rotl(x14 + x13 | 0, 18);
|
|
131
|
+
}
|
|
132
|
+
// Write output
|
|
133
|
+
let oi = 0;
|
|
134
|
+
out[oi++] = (y00 + x00) | 0;
|
|
135
|
+
out[oi++] = (y01 + x01) | 0;
|
|
136
|
+
out[oi++] = (y02 + x02) | 0;
|
|
137
|
+
out[oi++] = (y03 + x03) | 0;
|
|
138
|
+
out[oi++] = (y04 + x04) | 0;
|
|
139
|
+
out[oi++] = (y05 + x05) | 0;
|
|
140
|
+
out[oi++] = (y06 + x06) | 0;
|
|
141
|
+
out[oi++] = (y07 + x07) | 0;
|
|
142
|
+
out[oi++] = (y08 + x08) | 0;
|
|
143
|
+
out[oi++] = (y09 + x09) | 0;
|
|
144
|
+
out[oi++] = (y10 + x10) | 0;
|
|
145
|
+
out[oi++] = (y11 + x11) | 0;
|
|
146
|
+
out[oi++] = (y12 + x12) | 0;
|
|
147
|
+
out[oi++] = (y13 + x13) | 0;
|
|
148
|
+
out[oi++] = (y14 + x14) | 0;
|
|
149
|
+
out[oi++] = (y15 + x15) | 0;
|
|
150
|
+
}
|
|
151
|
+
/**
|
|
152
|
+
* hsalsa hashes key and nonce-prefix words into the 32-byte subkey used by XSalsa20.
|
|
153
|
+
* Identical to `hsalsa_small`.
|
|
154
|
+
* Need to find a way to merge it with `salsaCore` without 25% performance hit.
|
|
155
|
+
* @param s - Sigma constants as 32-bit words.
|
|
156
|
+
* @param k - Key words.
|
|
157
|
+
* @param i - Nonce-prefix words.
|
|
158
|
+
* @param out - Output buffer for the derived subkey.
|
|
159
|
+
* @example
|
|
160
|
+
* Derives the XSalsa20 subkey from sigma, key, and nonce-prefix words.
|
|
161
|
+
*
|
|
162
|
+
* ```ts
|
|
163
|
+
* const sigma = new Uint32Array(4);
|
|
164
|
+
* const key = new Uint32Array(8);
|
|
165
|
+
* const nonce = new Uint32Array(4);
|
|
166
|
+
* const out = new Uint32Array(8);
|
|
167
|
+
* hsalsa(sigma, key, nonce, out);
|
|
168
|
+
* ```
|
|
169
|
+
*/
|
|
170
|
+
// prettier-ignore
|
|
171
|
+
export function hsalsa(s, k, i, out) {
|
|
172
|
+
let x00 = swap8IfBE(s[0]), x01 = swap8IfBE(k[0]), x02 = swap8IfBE(k[1]), x03 = swap8IfBE(k[2]), x04 = swap8IfBE(k[3]), x05 = swap8IfBE(s[1]), x06 = swap8IfBE(i[0]), x07 = swap8IfBE(i[1]), x08 = swap8IfBE(i[2]), x09 = swap8IfBE(i[3]), x10 = swap8IfBE(s[2]), x11 = swap8IfBE(k[4]), x12 = swap8IfBE(k[5]), x13 = swap8IfBE(k[6]), x14 = swap8IfBE(k[7]), x15 = swap8IfBE(s[3]);
|
|
173
|
+
for (let r = 0; r < 20; r += 2) {
|
|
174
|
+
x04 ^= rotl(x00 + x12 | 0, 7);
|
|
175
|
+
x08 ^= rotl(x04 + x00 | 0, 9);
|
|
176
|
+
x12 ^= rotl(x08 + x04 | 0, 13);
|
|
177
|
+
x00 ^= rotl(x12 + x08 | 0, 18);
|
|
178
|
+
x09 ^= rotl(x05 + x01 | 0, 7);
|
|
179
|
+
x13 ^= rotl(x09 + x05 | 0, 9);
|
|
180
|
+
x01 ^= rotl(x13 + x09 | 0, 13);
|
|
181
|
+
x05 ^= rotl(x01 + x13 | 0, 18);
|
|
182
|
+
x14 ^= rotl(x10 + x06 | 0, 7);
|
|
183
|
+
x02 ^= rotl(x14 + x10 | 0, 9);
|
|
184
|
+
x06 ^= rotl(x02 + x14 | 0, 13);
|
|
185
|
+
x10 ^= rotl(x06 + x02 | 0, 18);
|
|
186
|
+
x03 ^= rotl(x15 + x11 | 0, 7);
|
|
187
|
+
x07 ^= rotl(x03 + x15 | 0, 9);
|
|
188
|
+
x11 ^= rotl(x07 + x03 | 0, 13);
|
|
189
|
+
x15 ^= rotl(x11 + x07 | 0, 18);
|
|
190
|
+
x01 ^= rotl(x00 + x03 | 0, 7);
|
|
191
|
+
x02 ^= rotl(x01 + x00 | 0, 9);
|
|
192
|
+
x03 ^= rotl(x02 + x01 | 0, 13);
|
|
193
|
+
x00 ^= rotl(x03 + x02 | 0, 18);
|
|
194
|
+
x06 ^= rotl(x05 + x04 | 0, 7);
|
|
195
|
+
x07 ^= rotl(x06 + x05 | 0, 9);
|
|
196
|
+
x04 ^= rotl(x07 + x06 | 0, 13);
|
|
197
|
+
x05 ^= rotl(x04 + x07 | 0, 18);
|
|
198
|
+
x11 ^= rotl(x10 + x09 | 0, 7);
|
|
199
|
+
x08 ^= rotl(x11 + x10 | 0, 9);
|
|
200
|
+
x09 ^= rotl(x08 + x11 | 0, 13);
|
|
201
|
+
x10 ^= rotl(x09 + x08 | 0, 18);
|
|
202
|
+
x12 ^= rotl(x15 + x14 | 0, 7);
|
|
203
|
+
x13 ^= rotl(x12 + x15 | 0, 9);
|
|
204
|
+
x14 ^= rotl(x13 + x12 | 0, 13);
|
|
205
|
+
x15 ^= rotl(x14 + x13 | 0, 18);
|
|
206
|
+
}
|
|
207
|
+
let oi = 0;
|
|
208
|
+
// XSalsa20 takes words 0,5,10,15 and 6,7,8,9 as the 32-byte subkey material.
|
|
209
|
+
out[oi++] = x00;
|
|
210
|
+
out[oi++] = x05;
|
|
211
|
+
out[oi++] = x10;
|
|
212
|
+
out[oi++] = x15;
|
|
213
|
+
out[oi++] = x06;
|
|
214
|
+
out[oi++] = x07;
|
|
215
|
+
out[oi++] = x08;
|
|
216
|
+
out[oi++] = x09;
|
|
217
|
+
swap32IfBE(out);
|
|
218
|
+
}
|
|
219
|
+
/**
|
|
220
|
+
* Salsa20 from original paper. 8-byte nonce.
|
|
221
|
+
* With smaller nonce, it's not safe to make it random (CSPRNG), due to collision chance.
|
|
222
|
+
* @param key - 16-byte or 32-byte key.
|
|
223
|
+
* @param nonce - 8-byte nonce.
|
|
224
|
+
* @param data - Input bytes to xor with the keystream.
|
|
225
|
+
* @param output - Optional destination buffer.
|
|
226
|
+
* @param counter - Initial block counter.
|
|
227
|
+
* Only the low 32 bits of Salsa20's 64-bit counter state are exposed here;
|
|
228
|
+
* the high word stays zero and the implementation still caps the public
|
|
229
|
+
* value to 32 bits.
|
|
230
|
+
* @returns Encrypted or decrypted bytes.
|
|
231
|
+
* @example
|
|
232
|
+
* Encrypts bytes with the original 8-byte-nonce Salsa20 stream cipher.
|
|
233
|
+
*
|
|
234
|
+
* ```ts
|
|
235
|
+
* import { salsa20 } from './salsa';
|
|
236
|
+
* import { randomBytes } from './utils';
|
|
237
|
+
* const key = randomBytes(32);
|
|
238
|
+
* const nonce = randomBytes(8);
|
|
239
|
+
* salsa20(key, nonce, new Uint8Array([1, 2, 3, 4]));
|
|
240
|
+
* ```
|
|
241
|
+
*/
|
|
242
|
+
export const salsa20 = /* @__PURE__ */ createCipher(salsaCore, {
|
|
243
|
+
allowShortKeys: true,
|
|
244
|
+
counterRight: true,
|
|
245
|
+
});
|
|
246
|
+
/**
|
|
247
|
+
* XSalsa20 extended-nonce salsa.
|
|
248
|
+
* With 24-byte nonce, it's safe to make it random (CSPRNG).
|
|
249
|
+
* @param key - 32-byte key.
|
|
250
|
+
* This XSalsa20 wrapper does not enable Salsa20's 16-byte legacy key mode.
|
|
251
|
+
* @param nonce - 24-byte nonce.
|
|
252
|
+
* @param data - Input bytes to xor with the keystream.
|
|
253
|
+
* @param output - Optional destination buffer.
|
|
254
|
+
* @param counter - Initial block counter.
|
|
255
|
+
* @returns Encrypted or decrypted bytes.
|
|
256
|
+
* @example
|
|
257
|
+
* Encrypts bytes with XSalsa20 and a random 24-byte nonce.
|
|
258
|
+
*
|
|
259
|
+
* ```ts
|
|
260
|
+
* import { xsalsa20 } from './salsa';
|
|
261
|
+
* import { randomBytes } from './utils';
|
|
262
|
+
* const key = randomBytes(32);
|
|
263
|
+
* const nonce = randomBytes(24);
|
|
264
|
+
* xsalsa20(key, nonce, new Uint8Array([1, 2, 3, 4]));
|
|
265
|
+
* ```
|
|
266
|
+
*/
|
|
267
|
+
export const xsalsa20 = /* @__PURE__ */ createCipher(salsaCore, {
|
|
268
|
+
counterRight: true,
|
|
269
|
+
extendNonceFn: hsalsa,
|
|
270
|
+
});
|
|
271
|
+
/**
|
|
272
|
+
* xsalsa20-poly1305 eXtended-nonce (24 bytes) salsa.
|
|
273
|
+
* With 24-byte nonce, it's safe to make it random (CSPRNG).
|
|
274
|
+
* Also known as `secretbox` from libsodium / nacl.
|
|
275
|
+
* No AAD input is supported here. Caller-provided `output` buffers for
|
|
276
|
+
* `encrypt()` / `decrypt()` must be `input.length + 32` bytes because the
|
|
277
|
+
* implementation uses a 32-byte leading scratch area before returning `+16`.
|
|
278
|
+
* @param key - 32-byte key.
|
|
279
|
+
* @param nonce - 24-byte nonce.
|
|
280
|
+
* @param AAD - Must be omitted; XSalsa20-Poly1305 secretbox does not support associated data.
|
|
281
|
+
* @returns AEAD cipher instance.
|
|
282
|
+
* @example
|
|
283
|
+
* Encrypts and authenticates plaintext with XSalsa20-Poly1305.
|
|
284
|
+
*
|
|
285
|
+
* ```ts
|
|
286
|
+
* import { xsalsa20poly1305 } from './salsa';
|
|
287
|
+
* import { randomBytes } from './utils';
|
|
288
|
+
* const key = randomBytes(32);
|
|
289
|
+
* const nonce = randomBytes(24);
|
|
290
|
+
* const cipher = xsalsa20poly1305(key, nonce);
|
|
291
|
+
* cipher.encrypt(new Uint8Array([1, 2, 3]));
|
|
292
|
+
* ```
|
|
293
|
+
*/
|
|
294
|
+
export const xsalsa20poly1305 = /* @__PURE__ */ wrapCipher({ blockSize: 64, nonceLength: 24, tagLength: 16 }, (key, nonce) => {
|
|
295
|
+
// This borrows caller key/nonce buffers by reference; mutating them after construction changes
|
|
296
|
+
// later encrypt/decrypt outputs.
|
|
297
|
+
return {
|
|
298
|
+
encrypt(plaintext, output) {
|
|
299
|
+
// xsalsa20poly1305 optimizes by calculating auth key during the same call as encryption.
|
|
300
|
+
// Unfortunately, makes it hard to separate tag calculation & encryption itself,
|
|
301
|
+
// because 32 bytes is half-block of 64-byte salsa.
|
|
302
|
+
// Need 32 extra bytes up front for the auth-key scratch area described above.
|
|
303
|
+
output = getOutput(plaintext.length + 32, output, false);
|
|
304
|
+
// output[0..32] = Poly1305 auth key, output[32..] = plaintext then ciphertext.
|
|
305
|
+
const authKey = output.subarray(0, 32);
|
|
306
|
+
const ciphPlaintext = output.subarray(32);
|
|
307
|
+
output.set(plaintext, 32);
|
|
308
|
+
// authKey is produced by xoring the first 32 bytes with zeros.
|
|
309
|
+
clean(authKey);
|
|
310
|
+
// output = stream ^ output; authKey = stream ^ zeros(32)
|
|
311
|
+
xsalsa20(key, nonce, output, output);
|
|
312
|
+
const tag = poly1305(ciphPlaintext, authKey);
|
|
313
|
+
output.set(tag, 16);
|
|
314
|
+
// Clean up auth-key remnants and the temporary tag copy.
|
|
315
|
+
clean(output.subarray(0, 16), tag);
|
|
316
|
+
// Return output[16..].
|
|
317
|
+
return output.subarray(16);
|
|
318
|
+
},
|
|
319
|
+
decrypt(ciphertext, output) {
|
|
320
|
+
// tmp part passed tag ciphertext
|
|
321
|
+
// [0..32] [32..48] [48..]
|
|
322
|
+
// Authenticate the ciphertext before decrypting it; on tag failure the scratch/output
|
|
323
|
+
// buffer may already contain copied ciphertext and derived auth-key material.
|
|
324
|
+
abytes(ciphertext);
|
|
325
|
+
output = getOutput(ciphertext.length + 32, output, false);
|
|
326
|
+
// output[0..32] is auth-key scratch, output[32..48] is passed tag,
|
|
327
|
+
// output[48..] is ciphertext then plaintext.
|
|
328
|
+
const tmp = output.subarray(0, 32);
|
|
329
|
+
const passedTag = output.subarray(32, 48);
|
|
330
|
+
const ciphPlaintext = output.subarray(48);
|
|
331
|
+
output.set(ciphertext, 32);
|
|
332
|
+
// authKey is produced by xoring the scratch area with zeros.
|
|
333
|
+
clean(tmp);
|
|
334
|
+
const authKey = xsalsa20(key, nonce, tmp, tmp);
|
|
335
|
+
const tag = poly1305(ciphPlaintext, authKey);
|
|
336
|
+
if (!equalBytes(passedTag, tag)) {
|
|
337
|
+
clean(output);
|
|
338
|
+
throw new Error('invalid tag');
|
|
339
|
+
}
|
|
340
|
+
// output = stream ^ output[16..]
|
|
341
|
+
xsalsa20(key, nonce, output.subarray(16), output.subarray(16));
|
|
342
|
+
clean(tmp, passedTag, tag);
|
|
343
|
+
// Return output[48..], skipping zeroized output[0..48].
|
|
344
|
+
return ciphPlaintext;
|
|
345
|
+
},
|
|
346
|
+
};
|
|
347
|
+
});
|
|
348
|
+
/**
|
|
349
|
+
* Alias to `xsalsa20poly1305`, for compatibility with libsodium / nacl.
|
|
350
|
+
* Check out {@link https://github.com/serenity-kit/noble-sodium | noble-sodium}
|
|
351
|
+
* for `crypto_box`.
|
|
352
|
+
* @param key - 32-byte key.
|
|
353
|
+
* @param nonce - 24-byte nonce.
|
|
354
|
+
* @returns Wrapper with `seal()` and `open()` helpers.
|
|
355
|
+
* @example
|
|
356
|
+
* Uses the libsodium-style `seal()` and `open()` wrapper.
|
|
357
|
+
*
|
|
358
|
+
* ```ts
|
|
359
|
+
* import { secretbox } from './salsa';
|
|
360
|
+
* import { randomBytes } from './utils';
|
|
361
|
+
* const key = randomBytes(32);
|
|
362
|
+
* const nonce = randomBytes(24);
|
|
363
|
+
* const box = secretbox(key, nonce);
|
|
364
|
+
* box.seal(new Uint8Array([1, 2, 3]));
|
|
365
|
+
* ```
|
|
366
|
+
*/
|
|
367
|
+
export function secretbox(key, nonce) {
|
|
368
|
+
const xs = xsalsa20poly1305(key, nonce);
|
|
369
|
+
return { seal: xs.encrypt, open: xs.decrypt };
|
|
370
|
+
}
|