@push.rocks/smartcrypto 3.3.0 → 3.4.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/dist_ts/00_commitinfo_data.js +1 -1
- package/dist_ts/index.d.ts +1 -0
- package/dist_ts/index.js +2 -1
- package/dist_ts/smartcrypto.mlkem768.d.ts +54 -0
- package/dist_ts/smartcrypto.mlkem768.js +677 -0
- package/package.json +1 -1
- package/ts/00_commitinfo_data.ts +1 -1
- package/ts/index.ts +1 -0
- package/ts/smartcrypto.mlkem768.ts +754 -0
|
@@ -0,0 +1,754 @@
|
|
|
1
|
+
import { createSmartCryptoError } from './smartcrypto.errors.js';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Pure TypeScript, zero-dependency implementation of NIST FIPS 203 ML-KEM-768
|
|
5
|
+
* (and FIPS 202 Keccak-f[1600] / SHA3-256 / SHA3-512 / SHAKE128 / SHAKE256).
|
|
6
|
+
*
|
|
7
|
+
* Designed for cross-runtime use (browsers and Node.js) with strict input
|
|
8
|
+
* validation, constant-time implicit rejection on decapsulation, and exact
|
|
9
|
+
* compatibility with OpenSSL 3.5 / Node.js `ml-kem-768`.
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
const Q = 3329;
|
|
13
|
+
const N = 256;
|
|
14
|
+
const K = 3;
|
|
15
|
+
const DU = 10;
|
|
16
|
+
const DV = 4;
|
|
17
|
+
|
|
18
|
+
export const MLKEM768_PUBLIC_KEY_BYTES = 1184;
|
|
19
|
+
export const MLKEM768_SECRET_KEY_BYTES = 2400;
|
|
20
|
+
export const MLKEM768_CIPHERTEXT_BYTES = 1088;
|
|
21
|
+
export const MLKEM768_SHARED_SECRET_BYTES = 32;
|
|
22
|
+
export const MLKEM768_SEED_BYTES = 64;
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* Fixed 22-byte ASN.1 DER SubjectPublicKeyInfo prefix for id-alg-ml-kem-768
|
|
26
|
+
* (OID 2.16.840.1.101.3.4.4.2, RFC 9881 / OpenSSL 3.5).
|
|
27
|
+
*/
|
|
28
|
+
const MLKEM768_SPKI_PREFIX = Uint8Array.from([
|
|
29
|
+
0x30, 0x82, 0x04, 0xb2, 0x30, 0x0b, 0x06, 0x09,
|
|
30
|
+
0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x04,
|
|
31
|
+
0x02, 0x03, 0x82, 0x04, 0xa1, 0x00,
|
|
32
|
+
]);
|
|
33
|
+
|
|
34
|
+
export const MLKEM768_SPKI_BYTES = MLKEM768_SPKI_PREFIX.length + MLKEM768_PUBLIC_KEY_BYTES; // 1206
|
|
35
|
+
|
|
36
|
+
export interface IMlKem768KeyPair {
|
|
37
|
+
/** Raw 1184-byte FIPS 203 encapsulation key (`ek`). */
|
|
38
|
+
publicKey: Uint8Array;
|
|
39
|
+
/** Raw 2400-byte FIPS 203 decapsulation key (`dk`). */
|
|
40
|
+
secretKey: Uint8Array;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export interface IMlKem768EncapsulationResult {
|
|
44
|
+
/** 1088-byte FIPS 203 ciphertext (`c`). */
|
|
45
|
+
ciphertext: Uint8Array;
|
|
46
|
+
/** 32-byte shared secret (`K`). */
|
|
47
|
+
sharedSecret: Uint8Array;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
// ============================================================================
|
|
51
|
+
// FIPS 202 Keccak-f[1600] (32-bit lane pair implementation, zero BigInt allocs)
|
|
52
|
+
// ============================================================================
|
|
53
|
+
|
|
54
|
+
const KECCAK_RC_LO = new Uint32Array([
|
|
55
|
+
0x00000001, 0x00008082, 0x0000808a, 0x80008000,
|
|
56
|
+
0x0000808b, 0x80000001, 0x80008081, 0x00008009,
|
|
57
|
+
0x0000008a, 0x00000088, 0x80008009, 0x8000000a,
|
|
58
|
+
0x8000808b, 0x0000008b, 0x00008089, 0x00008003,
|
|
59
|
+
0x00008002, 0x00000080, 0x0000800a, 0x8000000a,
|
|
60
|
+
0x80008081, 0x00008080, 0x80000001, 0x80008008,
|
|
61
|
+
]);
|
|
62
|
+
|
|
63
|
+
const KECCAK_RC_HI = new Uint32Array([
|
|
64
|
+
0x00000000, 0x00000000, 0x80000000, 0x80000000,
|
|
65
|
+
0x00000000, 0x00000000, 0x80000000, 0x80000000,
|
|
66
|
+
0x00000000, 0x00000000, 0x00000000, 0x00000000,
|
|
67
|
+
0x00000000, 0x80000000, 0x80000000, 0x80000000,
|
|
68
|
+
0x80000000, 0x80000000, 0x00000000, 0x80000000,
|
|
69
|
+
0x80000000, 0x80000000, 0x00000000, 0x80000000,
|
|
70
|
+
]);
|
|
71
|
+
|
|
72
|
+
const KECCAK_PI = [
|
|
73
|
+
10, 7, 11, 17, 18, 3, 5, 16, 8, 21, 24, 4,
|
|
74
|
+
15, 23, 19, 13, 12, 2, 20, 14, 22, 9, 6, 1,
|
|
75
|
+
];
|
|
76
|
+
|
|
77
|
+
const KECCAK_ROT = [
|
|
78
|
+
1, 3, 6, 10, 15, 21, 28, 36, 45, 55, 2, 14,
|
|
79
|
+
27, 41, 56, 8, 25, 43, 62, 18, 39, 61, 20, 44,
|
|
80
|
+
];
|
|
81
|
+
|
|
82
|
+
const keccakF1600 = (stateArg: Uint32Array): void => {
|
|
83
|
+
const cLo = new Uint32Array(5);
|
|
84
|
+
const cHi = new Uint32Array(5);
|
|
85
|
+
for (let round = 0; round < 24; round++) {
|
|
86
|
+
// Theta
|
|
87
|
+
for (let x = 0; x < 5; x++) {
|
|
88
|
+
cLo[x] =
|
|
89
|
+
stateArg[2 * x] ^
|
|
90
|
+
stateArg[2 * (x + 5)] ^
|
|
91
|
+
stateArg[2 * (x + 10)] ^
|
|
92
|
+
stateArg[2 * (x + 15)] ^
|
|
93
|
+
stateArg[2 * (x + 20)];
|
|
94
|
+
cHi[x] =
|
|
95
|
+
stateArg[2 * x + 1] ^
|
|
96
|
+
stateArg[2 * (x + 5) + 1] ^
|
|
97
|
+
stateArg[2 * (x + 10) + 1] ^
|
|
98
|
+
stateArg[2 * (x + 15) + 1] ^
|
|
99
|
+
stateArg[2 * (x + 20) + 1];
|
|
100
|
+
}
|
|
101
|
+
for (let x = 0; x < 5; x++) {
|
|
102
|
+
const prev = (x + 4) % 5;
|
|
103
|
+
const next = (x + 1) % 5;
|
|
104
|
+
const dLo = cLo[prev] ^ ((cLo[next] << 1) | (cHi[next] >>> 31));
|
|
105
|
+
const dHi = cHi[prev] ^ ((cHi[next] << 1) | (cLo[next] >>> 31));
|
|
106
|
+
for (let y = 0; y < 25; y += 5) {
|
|
107
|
+
stateArg[2 * (x + y)] ^= dLo;
|
|
108
|
+
stateArg[2 * (x + y) + 1] ^= dHi;
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
// Rho and Pi
|
|
113
|
+
let curLo = stateArg[2];
|
|
114
|
+
let curHi = stateArg[3];
|
|
115
|
+
for (let i = 0; i < 24; i++) {
|
|
116
|
+
const j = KECCAK_PI[i];
|
|
117
|
+
const nextLo = stateArg[2 * j];
|
|
118
|
+
const nextHi = stateArg[2 * j + 1];
|
|
119
|
+
const r = KECCAK_ROT[i];
|
|
120
|
+
if (r < 32) {
|
|
121
|
+
stateArg[2 * j] = (curLo << r) | (curHi >>> (32 - r));
|
|
122
|
+
stateArg[2 * j + 1] = (curHi << r) | (curLo >>> (32 - r));
|
|
123
|
+
} else {
|
|
124
|
+
const s = r - 32;
|
|
125
|
+
stateArg[2 * j] = (curHi << s) | (curLo >>> (32 - s));
|
|
126
|
+
stateArg[2 * j + 1] = (curLo << s) | (curHi >>> (32 - s));
|
|
127
|
+
}
|
|
128
|
+
curLo = nextLo;
|
|
129
|
+
curHi = nextHi;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
// Chi
|
|
133
|
+
for (let y = 0; y < 25; y += 5) {
|
|
134
|
+
for (let x = 0; x < 5; x++) {
|
|
135
|
+
cLo[x] = stateArg[2 * (y + x)];
|
|
136
|
+
cHi[x] = stateArg[2 * (y + x) + 1];
|
|
137
|
+
}
|
|
138
|
+
for (let x = 0; x < 5; x++) {
|
|
139
|
+
const x1 = (x + 1) % 5;
|
|
140
|
+
const x2 = (x + 2) % 5;
|
|
141
|
+
stateArg[2 * (y + x)] = cLo[x] ^ (~cLo[x1] & cLo[x2]);
|
|
142
|
+
stateArg[2 * (y + x) + 1] = cHi[x] ^ (~cHi[x1] & cHi[x2]);
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
// Iota
|
|
147
|
+
stateArg[0] ^= KECCAK_RC_LO[round];
|
|
148
|
+
stateArg[1] ^= KECCAK_RC_HI[round];
|
|
149
|
+
}
|
|
150
|
+
};
|
|
151
|
+
|
|
152
|
+
class KeccakSponge {
|
|
153
|
+
private readonly state = new Uint32Array(50);
|
|
154
|
+
private readonly bytes: Uint8Array;
|
|
155
|
+
private pos = 0;
|
|
156
|
+
private finalized = false;
|
|
157
|
+
|
|
158
|
+
constructor(
|
|
159
|
+
private readonly rate: number,
|
|
160
|
+
private readonly suffix: number,
|
|
161
|
+
) {
|
|
162
|
+
this.bytes = new Uint8Array(this.state.buffer);
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
public absorb(dataArg: Uint8Array): this {
|
|
166
|
+
let offset = 0;
|
|
167
|
+
while (offset < dataArg.length) {
|
|
168
|
+
const take = Math.min(this.rate - this.pos, dataArg.length - offset);
|
|
169
|
+
for (let i = 0; i < take; i++) {
|
|
170
|
+
this.bytes[this.pos + i] ^= dataArg[offset + i];
|
|
171
|
+
}
|
|
172
|
+
this.pos += take;
|
|
173
|
+
offset += take;
|
|
174
|
+
if (this.pos === this.rate) {
|
|
175
|
+
keccakF1600(this.state);
|
|
176
|
+
this.pos = 0;
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
return this;
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
public squeeze(outLengthArg: number): Uint8Array {
|
|
183
|
+
if (!this.finalized) {
|
|
184
|
+
this.bytes[this.pos] ^= this.suffix;
|
|
185
|
+
this.bytes[this.rate - 1] ^= 0x80;
|
|
186
|
+
keccakF1600(this.state);
|
|
187
|
+
this.pos = 0;
|
|
188
|
+
this.finalized = true;
|
|
189
|
+
}
|
|
190
|
+
const out = new Uint8Array(outLengthArg);
|
|
191
|
+
let offset = 0;
|
|
192
|
+
while (offset < outLengthArg) {
|
|
193
|
+
if (this.pos === this.rate) {
|
|
194
|
+
keccakF1600(this.state);
|
|
195
|
+
this.pos = 0;
|
|
196
|
+
}
|
|
197
|
+
const take = Math.min(this.rate - this.pos, outLengthArg - offset);
|
|
198
|
+
out.set(this.bytes.subarray(this.pos, this.pos + take), offset);
|
|
199
|
+
this.pos += take;
|
|
200
|
+
offset += take;
|
|
201
|
+
}
|
|
202
|
+
return out;
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
const sha3_256 = (...chunksArg: Uint8Array[]): Uint8Array => {
|
|
207
|
+
const sponge = new KeccakSponge(136, 0x06);
|
|
208
|
+
for (const chunk of chunksArg) sponge.absorb(chunk);
|
|
209
|
+
return sponge.squeeze(32);
|
|
210
|
+
};
|
|
211
|
+
|
|
212
|
+
const sha3_512 = (...chunksArg: Uint8Array[]): Uint8Array => {
|
|
213
|
+
const sponge = new KeccakSponge(72, 0x06);
|
|
214
|
+
for (const chunk of chunksArg) sponge.absorb(chunk);
|
|
215
|
+
return sponge.squeeze(64);
|
|
216
|
+
};
|
|
217
|
+
|
|
218
|
+
const shake256 = (outLengthArg: number, ...chunksArg: Uint8Array[]): Uint8Array => {
|
|
219
|
+
const sponge = new KeccakSponge(136, 0x1f);
|
|
220
|
+
for (const chunk of chunksArg) sponge.absorb(chunk);
|
|
221
|
+
return sponge.squeeze(outLengthArg);
|
|
222
|
+
};
|
|
223
|
+
|
|
224
|
+
// ============================================================================
|
|
225
|
+
// FIPS 203 NTT, Sampling, Compression, and ByteEncode/ByteDecode
|
|
226
|
+
// ============================================================================
|
|
227
|
+
|
|
228
|
+
const modQ = (xArg: number): number => {
|
|
229
|
+
const r = xArg % Q;
|
|
230
|
+
return r < 0 ? r + Q : r;
|
|
231
|
+
};
|
|
232
|
+
|
|
233
|
+
const bitRev7 = (vArg: number): number => {
|
|
234
|
+
let out = 0;
|
|
235
|
+
for (let i = 0; i < 7; i++) {
|
|
236
|
+
out = (out << 1) | ((vArg >> i) & 1);
|
|
237
|
+
}
|
|
238
|
+
return out;
|
|
239
|
+
};
|
|
240
|
+
|
|
241
|
+
const powModQ = (baseArg: number, expArg: number): number => {
|
|
242
|
+
let result = 1;
|
|
243
|
+
let base = modQ(baseArg);
|
|
244
|
+
let exp = expArg;
|
|
245
|
+
while (exp > 0) {
|
|
246
|
+
if (exp & 1) result = (result * base) % Q;
|
|
247
|
+
base = (base * base) % Q;
|
|
248
|
+
exp >>= 1;
|
|
249
|
+
}
|
|
250
|
+
return result;
|
|
251
|
+
};
|
|
252
|
+
|
|
253
|
+
// Lazily initialized on first call so the module obeys "zero import-time work".
|
|
254
|
+
let cachedZetas: Int16Array | null = null;
|
|
255
|
+
let cachedBaseCaseGammas: Int16Array | null = null;
|
|
256
|
+
|
|
257
|
+
const getZetas = (): Int16Array => {
|
|
258
|
+
if (!cachedZetas) {
|
|
259
|
+
const zetas = new Int16Array(128);
|
|
260
|
+
for (let i = 0; i < 128; i++) {
|
|
261
|
+
zetas[i] = powModQ(17, bitRev7(i));
|
|
262
|
+
}
|
|
263
|
+
cachedZetas = zetas;
|
|
264
|
+
}
|
|
265
|
+
return cachedZetas;
|
|
266
|
+
};
|
|
267
|
+
|
|
268
|
+
const getBaseCaseGammas = (): Int16Array => {
|
|
269
|
+
if (!cachedBaseCaseGammas) {
|
|
270
|
+
const gammas = new Int16Array(128);
|
|
271
|
+
for (let i = 0; i < 128; i++) {
|
|
272
|
+
gammas[i] = powModQ(17, 2 * bitRev7(i) + 1);
|
|
273
|
+
}
|
|
274
|
+
cachedBaseCaseGammas = gammas;
|
|
275
|
+
}
|
|
276
|
+
return cachedBaseCaseGammas;
|
|
277
|
+
};
|
|
278
|
+
|
|
279
|
+
const ntt = (polyArg: Int16Array): Int16Array => {
|
|
280
|
+
const f = new Int16Array(polyArg);
|
|
281
|
+
const zetas = getZetas();
|
|
282
|
+
let i = 1;
|
|
283
|
+
for (let len = 128; len >= 2; len >>= 1) {
|
|
284
|
+
for (let start = 0; start < N; start += 2 * len) {
|
|
285
|
+
const zeta = zetas[i++];
|
|
286
|
+
for (let j = start; j < start + len; j++) {
|
|
287
|
+
const t = (zeta * f[j + len]) % Q;
|
|
288
|
+
let hi = f[j] - t;
|
|
289
|
+
if (hi < 0) hi += Q;
|
|
290
|
+
let lo = f[j] + t;
|
|
291
|
+
if (lo >= Q) lo -= Q;
|
|
292
|
+
f[j + len] = hi;
|
|
293
|
+
f[j] = lo;
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
}
|
|
297
|
+
return f;
|
|
298
|
+
};
|
|
299
|
+
|
|
300
|
+
const invNtt = (polyArg: Int16Array): Int16Array => {
|
|
301
|
+
const f = new Int16Array(polyArg);
|
|
302
|
+
const zetas = getZetas();
|
|
303
|
+
let i = 127;
|
|
304
|
+
for (let len = 2; len <= 128; len <<= 1) {
|
|
305
|
+
for (let start = 0; start < N; start += 2 * len) {
|
|
306
|
+
const zeta = zetas[i--];
|
|
307
|
+
for (let j = start; j < start + len; j++) {
|
|
308
|
+
const t = f[j];
|
|
309
|
+
let sum = t + f[j + len];
|
|
310
|
+
if (sum >= Q) sum -= Q;
|
|
311
|
+
let diff = f[j + len] - t;
|
|
312
|
+
if (diff < 0) diff += Q;
|
|
313
|
+
f[j] = sum;
|
|
314
|
+
f[j + len] = (zeta * diff) % Q;
|
|
315
|
+
}
|
|
316
|
+
}
|
|
317
|
+
}
|
|
318
|
+
// 128^{-1} mod 3329 = 3303
|
|
319
|
+
for (let j = 0; j < N; j++) {
|
|
320
|
+
f[j] = (f[j] * 3303) % Q;
|
|
321
|
+
}
|
|
322
|
+
return f;
|
|
323
|
+
};
|
|
324
|
+
|
|
325
|
+
const multiplyNtts = (aArg: Int16Array, bArg: Int16Array): Int16Array => {
|
|
326
|
+
const out = new Int16Array(N);
|
|
327
|
+
const gammas = getBaseCaseGammas();
|
|
328
|
+
for (let i = 0; i < 128; i++) {
|
|
329
|
+
const a0 = aArg[2 * i];
|
|
330
|
+
const a1 = aArg[2 * i + 1];
|
|
331
|
+
const b0 = bArg[2 * i];
|
|
332
|
+
const b1 = bArg[2 * i + 1];
|
|
333
|
+
const gamma = gammas[i];
|
|
334
|
+
out[2 * i] = (a0 * b0 + ((a1 * b1) % Q) * gamma) % Q;
|
|
335
|
+
out[2 * i + 1] = (a0 * b1 + a1 * b0) % Q;
|
|
336
|
+
}
|
|
337
|
+
return out;
|
|
338
|
+
};
|
|
339
|
+
|
|
340
|
+
const polyAdd = (aArg: Int16Array, bArg: Int16Array): Int16Array => {
|
|
341
|
+
const out = new Int16Array(N);
|
|
342
|
+
for (let i = 0; i < N; i++) {
|
|
343
|
+
let s = aArg[i] + bArg[i];
|
|
344
|
+
if (s >= Q) s -= Q;
|
|
345
|
+
out[i] = s;
|
|
346
|
+
}
|
|
347
|
+
return out;
|
|
348
|
+
};
|
|
349
|
+
|
|
350
|
+
const polySub = (aArg: Int16Array, bArg: Int16Array): Int16Array => {
|
|
351
|
+
const out = new Int16Array(N);
|
|
352
|
+
for (let i = 0; i < N; i++) {
|
|
353
|
+
let d = aArg[i] - bArg[i];
|
|
354
|
+
if (d < 0) d += Q;
|
|
355
|
+
out[i] = d;
|
|
356
|
+
}
|
|
357
|
+
return out;
|
|
358
|
+
};
|
|
359
|
+
|
|
360
|
+
const sampleNtt = (rhoArg: Uint8Array, byte1Arg: number, byte2Arg: number): Int16Array => {
|
|
361
|
+
const xof = new KeccakSponge(168, 0x1f);
|
|
362
|
+
xof.absorb(rhoArg);
|
|
363
|
+
xof.absorb(Uint8Array.of(byte1Arg, byte2Arg));
|
|
364
|
+
const out = new Int16Array(N);
|
|
365
|
+
let j = 0;
|
|
366
|
+
while (j < N) {
|
|
367
|
+
const block = xof.squeeze(168);
|
|
368
|
+
for (let pos = 0; pos + 2 < block.length && j < N; pos += 3) {
|
|
369
|
+
const b0 = block[pos];
|
|
370
|
+
const b1 = block[pos + 1];
|
|
371
|
+
const b2 = block[pos + 2];
|
|
372
|
+
const d1 = b0 | ((b1 & 0x0f) << 8);
|
|
373
|
+
const d2 = (b1 >> 4) | (b2 << 4);
|
|
374
|
+
if (d1 < Q) out[j++] = d1;
|
|
375
|
+
if (d2 < Q && j < N) out[j++] = d2;
|
|
376
|
+
}
|
|
377
|
+
}
|
|
378
|
+
return out;
|
|
379
|
+
};
|
|
380
|
+
|
|
381
|
+
const samplePolyCbd2 = (sigmaArg: Uint8Array, nonceArg: number): Int16Array => {
|
|
382
|
+
const buf = shake256(128, sigmaArg, Uint8Array.of(nonceArg));
|
|
383
|
+
const out = new Int16Array(N);
|
|
384
|
+
for (let i = 0; i < 128; i++) {
|
|
385
|
+
const byte = buf[i];
|
|
386
|
+
const x0 = (byte & 1) + ((byte >> 1) & 1);
|
|
387
|
+
const y0 = ((byte >> 2) & 1) + ((byte >> 3) & 1);
|
|
388
|
+
let c0 = x0 - y0;
|
|
389
|
+
if (c0 < 0) c0 += Q;
|
|
390
|
+
out[2 * i] = c0;
|
|
391
|
+
|
|
392
|
+
const x1 = ((byte >> 4) & 1) + ((byte >> 5) & 1);
|
|
393
|
+
const y1 = ((byte >> 6) & 1) + ((byte >> 7) & 1);
|
|
394
|
+
let c1 = x1 - y1;
|
|
395
|
+
if (c1 < 0) c1 += Q;
|
|
396
|
+
out[2 * i + 1] = c1;
|
|
397
|
+
}
|
|
398
|
+
return out;
|
|
399
|
+
};
|
|
400
|
+
|
|
401
|
+
const compress = (xArg: number, dArg: number): number =>
|
|
402
|
+
((((xArg << dArg) + 1664) / Q) | 0) & ((1 << dArg) - 1);
|
|
403
|
+
|
|
404
|
+
const decompress = (yArg: number, dArg: number): number =>
|
|
405
|
+
(yArg * Q + (1 << (dArg - 1))) >> dArg;
|
|
406
|
+
|
|
407
|
+
const byteEncode = (polyArg: Int16Array, dArg: number): Uint8Array => {
|
|
408
|
+
const out = new Uint8Array(32 * dArg);
|
|
409
|
+
let bitPos = 0;
|
|
410
|
+
for (let i = 0; i < N; i++) {
|
|
411
|
+
const val = polyArg[i];
|
|
412
|
+
for (let b = 0; b < dArg; b++) {
|
|
413
|
+
if ((val >> b) & 1) {
|
|
414
|
+
out[bitPos >> 3] |= 1 << (bitPos & 7);
|
|
415
|
+
}
|
|
416
|
+
bitPos++;
|
|
417
|
+
}
|
|
418
|
+
}
|
|
419
|
+
return out;
|
|
420
|
+
};
|
|
421
|
+
|
|
422
|
+
const byteDecode = (bytesArg: Uint8Array, dArg: number, strictModQArg = false): Int16Array => {
|
|
423
|
+
const out = new Int16Array(N);
|
|
424
|
+
let bitPos = 0;
|
|
425
|
+
for (let i = 0; i < N; i++) {
|
|
426
|
+
let val = 0;
|
|
427
|
+
for (let b = 0; b < dArg; b++) {
|
|
428
|
+
if ((bytesArg[bitPos >> 3] >> (bitPos & 7)) & 1) {
|
|
429
|
+
val |= 1 << b;
|
|
430
|
+
}
|
|
431
|
+
bitPos++;
|
|
432
|
+
}
|
|
433
|
+
if (dArg === 12) {
|
|
434
|
+
if (strictModQArg && val >= Q) {
|
|
435
|
+
throw createSmartCryptoError('INVALID_KEY', 'ML-KEM-768 encapsulation key coefficient out of range');
|
|
436
|
+
}
|
|
437
|
+
out[i] = val % Q;
|
|
438
|
+
} else {
|
|
439
|
+
out[i] = val;
|
|
440
|
+
}
|
|
441
|
+
}
|
|
442
|
+
return out;
|
|
443
|
+
};
|
|
444
|
+
|
|
445
|
+
const concatBytes = (...partsArg: Uint8Array[]): Uint8Array => {
|
|
446
|
+
let total = 0;
|
|
447
|
+
for (const part of partsArg) total += part.length;
|
|
448
|
+
const out = new Uint8Array(total);
|
|
449
|
+
let offset = 0;
|
|
450
|
+
for (const part of partsArg) {
|
|
451
|
+
out.set(part, offset);
|
|
452
|
+
offset += part.length;
|
|
453
|
+
}
|
|
454
|
+
return out;
|
|
455
|
+
};
|
|
456
|
+
|
|
457
|
+
const getRandomBytes = (lengthArg: number): Uint8Array => {
|
|
458
|
+
const cryptoApi = globalThis.crypto;
|
|
459
|
+
if (!cryptoApi || typeof cryptoApi.getRandomValues !== 'function') {
|
|
460
|
+
throw createSmartCryptoError('CRYPTO_OPERATION_FAILED', 'Secure random source is unavailable');
|
|
461
|
+
}
|
|
462
|
+
const bytes = new Uint8Array(lengthArg);
|
|
463
|
+
cryptoApi.getRandomValues(bytes);
|
|
464
|
+
return bytes;
|
|
465
|
+
};
|
|
466
|
+
|
|
467
|
+
// ============================================================================
|
|
468
|
+
// FIPS 203 K-PKE & ML-KEM-768 Internal and Public Algorithms
|
|
469
|
+
// ============================================================================
|
|
470
|
+
|
|
471
|
+
const kpkeKeyGen = (dArg: Uint8Array): { ekPke: Uint8Array; dkPke: Uint8Array } => {
|
|
472
|
+
const expanded = sha3_512(dArg, Uint8Array.of(K));
|
|
473
|
+
const rho = expanded.subarray(0, 32);
|
|
474
|
+
const sigma = expanded.subarray(32, 64);
|
|
475
|
+
|
|
476
|
+
let nonce = 0;
|
|
477
|
+
const sHat: Int16Array[] = [];
|
|
478
|
+
for (let i = 0; i < K; i++) {
|
|
479
|
+
sHat.push(ntt(samplePolyCbd2(sigma, nonce++)));
|
|
480
|
+
}
|
|
481
|
+
const eHat: Int16Array[] = [];
|
|
482
|
+
for (let i = 0; i < K; i++) {
|
|
483
|
+
eHat.push(ntt(samplePolyCbd2(sigma, nonce++)));
|
|
484
|
+
}
|
|
485
|
+
|
|
486
|
+
const tHatBytes: Uint8Array[] = [];
|
|
487
|
+
const sHatBytes: Uint8Array[] = [];
|
|
488
|
+
for (let i = 0; i < K; i++) {
|
|
489
|
+
let acc: Int16Array = new Int16Array(N);
|
|
490
|
+
for (let j = 0; j < K; j++) {
|
|
491
|
+
const aIJ = sampleNtt(rho, j, i);
|
|
492
|
+
acc = polyAdd(acc, multiplyNtts(aIJ, sHat[j]));
|
|
493
|
+
}
|
|
494
|
+
const tHatI = polyAdd(acc, eHat[i]);
|
|
495
|
+
tHatBytes.push(byteEncode(tHatI, 12));
|
|
496
|
+
sHatBytes.push(byteEncode(sHat[i], 12));
|
|
497
|
+
}
|
|
498
|
+
|
|
499
|
+
return {
|
|
500
|
+
ekPke: concatBytes(...tHatBytes, rho),
|
|
501
|
+
dkPke: concatBytes(...sHatBytes),
|
|
502
|
+
};
|
|
503
|
+
};
|
|
504
|
+
|
|
505
|
+
const kpkeEncrypt = (
|
|
506
|
+
ekPkeArg: Uint8Array,
|
|
507
|
+
mArg: Uint8Array,
|
|
508
|
+
rArg: Uint8Array,
|
|
509
|
+
): Uint8Array => {
|
|
510
|
+
const tHat: Int16Array[] = [];
|
|
511
|
+
for (let i = 0; i < K; i++) {
|
|
512
|
+
tHat.push(byteDecode(ekPkeArg.subarray(384 * i, 384 * (i + 1)), 12, true));
|
|
513
|
+
}
|
|
514
|
+
const rho = ekPkeArg.subarray(384 * K, 384 * K + 32);
|
|
515
|
+
|
|
516
|
+
let nonce = 0;
|
|
517
|
+
const yHat: Int16Array[] = [];
|
|
518
|
+
for (let i = 0; i < K; i++) {
|
|
519
|
+
yHat.push(ntt(samplePolyCbd2(rArg, nonce++)));
|
|
520
|
+
}
|
|
521
|
+
const e1: Int16Array[] = [];
|
|
522
|
+
for (let i = 0; i < K; i++) {
|
|
523
|
+
e1.push(samplePolyCbd2(rArg, nonce++));
|
|
524
|
+
}
|
|
525
|
+
const e2 = samplePolyCbd2(rArg, nonce++);
|
|
526
|
+
|
|
527
|
+
// u = NTT^-1(A^T * yHat) + e1
|
|
528
|
+
const c1Parts: Uint8Array[] = [];
|
|
529
|
+
for (let i = 0; i < K; i++) {
|
|
530
|
+
let acc: Int16Array = new Int16Array(N);
|
|
531
|
+
for (let j = 0; j < K; j++) {
|
|
532
|
+
// A^T[i][j] = A[j][i] = SampleNTT(rho || i || j)
|
|
533
|
+
const aTij = sampleNtt(rho, i, j);
|
|
534
|
+
acc = polyAdd(acc, multiplyNtts(aTij, yHat[j]));
|
|
535
|
+
}
|
|
536
|
+
const uI = polyAdd(invNtt(acc), e1[i]);
|
|
537
|
+
const uCompressed = new Int16Array(N);
|
|
538
|
+
for (let c = 0; c < N; c++) {
|
|
539
|
+
uCompressed[c] = compress(uI[c], DU);
|
|
540
|
+
}
|
|
541
|
+
c1Parts.push(byteEncode(uCompressed, DU));
|
|
542
|
+
}
|
|
543
|
+
|
|
544
|
+
// mu = Decompress_1(ByteDecode_1(m))
|
|
545
|
+
const mBits = byteDecode(mArg, 1);
|
|
546
|
+
const mu = new Int16Array(N);
|
|
547
|
+
for (let c = 0; c < N; c++) {
|
|
548
|
+
mu[c] = decompress(mBits[c], 1);
|
|
549
|
+
}
|
|
550
|
+
|
|
551
|
+
// v = NTT^-1(tHat^T * yHat) + e2 + mu
|
|
552
|
+
let vAcc: Int16Array = new Int16Array(N);
|
|
553
|
+
for (let i = 0; i < K; i++) {
|
|
554
|
+
vAcc = polyAdd(vAcc, multiplyNtts(tHat[i], yHat[i]));
|
|
555
|
+
}
|
|
556
|
+
const v = polyAdd(polyAdd(invNtt(vAcc), e2), mu);
|
|
557
|
+
const vCompressed = new Int16Array(N);
|
|
558
|
+
for (let c = 0; c < N; c++) {
|
|
559
|
+
vCompressed[c] = compress(v[c], DV);
|
|
560
|
+
}
|
|
561
|
+
const c2 = byteEncode(vCompressed, DV);
|
|
562
|
+
|
|
563
|
+
return concatBytes(...c1Parts, c2);
|
|
564
|
+
};
|
|
565
|
+
|
|
566
|
+
const kpkeDecrypt = (dkPkeArg: Uint8Array, cArg: Uint8Array): Uint8Array => {
|
|
567
|
+
const u: Int16Array[] = [];
|
|
568
|
+
for (let i = 0; i < K; i++) {
|
|
569
|
+
const decoded = byteDecode(cArg.subarray(320 * i, 320 * (i + 1)), DU);
|
|
570
|
+
const decompressed = new Int16Array(N);
|
|
571
|
+
for (let c = 0; c < N; c++) {
|
|
572
|
+
decompressed[c] = decompress(decoded[c], DU);
|
|
573
|
+
}
|
|
574
|
+
u.push(decompressed);
|
|
575
|
+
}
|
|
576
|
+
const vDecoded = byteDecode(cArg.subarray(320 * K, 320 * K + 128), DV);
|
|
577
|
+
const v = new Int16Array(N);
|
|
578
|
+
for (let c = 0; c < N; c++) {
|
|
579
|
+
v[c] = decompress(vDecoded[c], DV);
|
|
580
|
+
}
|
|
581
|
+
|
|
582
|
+
const sHat: Int16Array[] = [];
|
|
583
|
+
for (let i = 0; i < K; i++) {
|
|
584
|
+
sHat.push(byteDecode(dkPkeArg.subarray(384 * i, 384 * (i + 1)), 12, false));
|
|
585
|
+
}
|
|
586
|
+
|
|
587
|
+
let acc: Int16Array = new Int16Array(N);
|
|
588
|
+
for (let i = 0; i < K; i++) {
|
|
589
|
+
acc = polyAdd(acc, multiplyNtts(sHat[i], ntt(u[i])));
|
|
590
|
+
}
|
|
591
|
+
const w = polySub(v, invNtt(acc));
|
|
592
|
+
const mPoly = new Int16Array(N);
|
|
593
|
+
for (let c = 0; c < N; c++) {
|
|
594
|
+
mPoly[c] = compress(w[c], 1);
|
|
595
|
+
}
|
|
596
|
+
return byteEncode(mPoly, 1);
|
|
597
|
+
};
|
|
598
|
+
|
|
599
|
+
/**
|
|
600
|
+
* Validates a raw 1184-byte FIPS 203 ML-KEM-768 encapsulation key (length and
|
|
601
|
+
* FIPS 203 §7.2 modulus check on every 12-bit coefficient).
|
|
602
|
+
*/
|
|
603
|
+
export const assertValidMlKem768PublicKey = (publicKeyArg: Uint8Array): void => {
|
|
604
|
+
if (!(publicKeyArg instanceof Uint8Array) || publicKeyArg.length !== MLKEM768_PUBLIC_KEY_BYTES) {
|
|
605
|
+
throw createSmartCryptoError('INVALID_KEY', 'ML-KEM-768 encapsulation key must be 1184 bytes');
|
|
606
|
+
}
|
|
607
|
+
for (let i = 0; i < K; i++) {
|
|
608
|
+
byteDecode(publicKeyArg.subarray(384 * i, 384 * (i + 1)), 12, true);
|
|
609
|
+
}
|
|
610
|
+
};
|
|
611
|
+
|
|
612
|
+
/**
|
|
613
|
+
* Deterministic FIPS 203 `ML-KEM.KeyGen_internal(d, z)` from a 64-byte seed (`d || z`).
|
|
614
|
+
*/
|
|
615
|
+
export const mlKem768KeyGenFromSeed = (seedArg: Uint8Array): IMlKem768KeyPair => {
|
|
616
|
+
if (!(seedArg instanceof Uint8Array) || seedArg.length !== MLKEM768_SEED_BYTES) {
|
|
617
|
+
throw createSmartCryptoError('INVALID_ARGUMENT', 'ML-KEM-768 seed must be 64 bytes');
|
|
618
|
+
}
|
|
619
|
+
const d = seedArg.subarray(0, 32);
|
|
620
|
+
const z = seedArg.subarray(32, 64);
|
|
621
|
+
const { ekPke, dkPke } = kpkeKeyGen(d);
|
|
622
|
+
const hEk = sha3_256(ekPke);
|
|
623
|
+
const secretKey = concatBytes(dkPke, ekPke, hEk, z);
|
|
624
|
+
return {
|
|
625
|
+
publicKey: ekPke,
|
|
626
|
+
secretKey,
|
|
627
|
+
};
|
|
628
|
+
};
|
|
629
|
+
|
|
630
|
+
/**
|
|
631
|
+
* Generates a fresh random FIPS 203 ML-KEM-768 keypair.
|
|
632
|
+
*/
|
|
633
|
+
export const generateMlKem768KeyPair = (): IMlKem768KeyPair => {
|
|
634
|
+
const seed = getRandomBytes(MLKEM768_SEED_BYTES);
|
|
635
|
+
try {
|
|
636
|
+
return mlKem768KeyGenFromSeed(seed);
|
|
637
|
+
} finally {
|
|
638
|
+
seed.fill(0);
|
|
639
|
+
}
|
|
640
|
+
};
|
|
641
|
+
|
|
642
|
+
/**
|
|
643
|
+
* Deterministic FIPS 203 `ML-KEM.Encaps_internal(ek, m)` from a 32-byte message `m`.
|
|
644
|
+
*/
|
|
645
|
+
export const mlKem768EncapsulateDeterministic = (
|
|
646
|
+
publicKeyArg: Uint8Array,
|
|
647
|
+
messageArg: Uint8Array,
|
|
648
|
+
): IMlKem768EncapsulationResult => {
|
|
649
|
+
assertValidMlKem768PublicKey(publicKeyArg);
|
|
650
|
+
if (!(messageArg instanceof Uint8Array) || messageArg.length !== 32) {
|
|
651
|
+
throw createSmartCryptoError('INVALID_ARGUMENT', 'ML-KEM-768 encapsulation randomness must be 32 bytes');
|
|
652
|
+
}
|
|
653
|
+
const hEk = sha3_256(publicKeyArg);
|
|
654
|
+
const gOut = sha3_512(messageArg, hEk);
|
|
655
|
+
const sharedSecret = gOut.slice(0, 32);
|
|
656
|
+
const r = gOut.subarray(32, 64);
|
|
657
|
+
const ciphertext = kpkeEncrypt(publicKeyArg, messageArg, r);
|
|
658
|
+
gOut.fill(0);
|
|
659
|
+
return { ciphertext, sharedSecret };
|
|
660
|
+
};
|
|
661
|
+
|
|
662
|
+
/**
|
|
663
|
+
* FIPS 203 `ML-KEM.Encaps(ek)`: encapsulates a fresh 32-byte shared secret to `publicKeyArg`.
|
|
664
|
+
*/
|
|
665
|
+
export const mlKem768Encapsulate = (
|
|
666
|
+
publicKeyArg: Uint8Array,
|
|
667
|
+
): IMlKem768EncapsulationResult => {
|
|
668
|
+
assertValidMlKem768PublicKey(publicKeyArg);
|
|
669
|
+
const m = getRandomBytes(32);
|
|
670
|
+
try {
|
|
671
|
+
return mlKem768EncapsulateDeterministic(publicKeyArg, m);
|
|
672
|
+
} finally {
|
|
673
|
+
m.fill(0);
|
|
674
|
+
}
|
|
675
|
+
};
|
|
676
|
+
|
|
677
|
+
/**
|
|
678
|
+
* FIPS 203 `ML-KEM.Decaps(dk, c)`: decapsulates `ciphertextArg` with constant-time
|
|
679
|
+
* implicit rejection on ciphertext mismatch.
|
|
680
|
+
*/
|
|
681
|
+
export const mlKem768Decapsulate = (
|
|
682
|
+
secretKeyArg: Uint8Array,
|
|
683
|
+
ciphertextArg: Uint8Array,
|
|
684
|
+
): Uint8Array => {
|
|
685
|
+
if (!(secretKeyArg instanceof Uint8Array) || secretKeyArg.length !== MLKEM768_SECRET_KEY_BYTES) {
|
|
686
|
+
throw createSmartCryptoError('INVALID_KEY', 'ML-KEM-768 decapsulation key must be 2400 bytes');
|
|
687
|
+
}
|
|
688
|
+
if (!(ciphertextArg instanceof Uint8Array) || ciphertextArg.length !== MLKEM768_CIPHERTEXT_BYTES) {
|
|
689
|
+
throw createSmartCryptoError('INVALID_ENVELOPE', 'ML-KEM-768 ciphertext must be 1088 bytes');
|
|
690
|
+
}
|
|
691
|
+
|
|
692
|
+
const dkPke = secretKeyArg.subarray(0, 384 * K); // 1152
|
|
693
|
+
const ekPke = secretKeyArg.subarray(384 * K, 384 * K + MLKEM768_PUBLIC_KEY_BYTES); // 1152..2336
|
|
694
|
+
const h = secretKeyArg.subarray(2336, 2368);
|
|
695
|
+
const z = secretKeyArg.subarray(2368, 2400);
|
|
696
|
+
|
|
697
|
+
// FIPS 203 §7.3 decapsulation key hash check
|
|
698
|
+
const expectedH = sha3_256(ekPke);
|
|
699
|
+
let hDiff = 0;
|
|
700
|
+
for (let i = 0; i < 32; i++) hDiff |= h[i] ^ expectedH[i];
|
|
701
|
+
if (hDiff !== 0) {
|
|
702
|
+
throw createSmartCryptoError('INVALID_KEY', 'ML-KEM-768 decapsulation key hash check failed');
|
|
703
|
+
}
|
|
704
|
+
|
|
705
|
+
const mPrime = kpkeDecrypt(dkPke, ciphertextArg);
|
|
706
|
+
const gOut = sha3_512(mPrime, h);
|
|
707
|
+
const kPrime = gOut.subarray(0, 32);
|
|
708
|
+
const rPrime = gOut.subarray(32, 64);
|
|
709
|
+
const kBar = shake256(32, z, ciphertextArg);
|
|
710
|
+
const cPrime = kpkeEncrypt(ekPke, mPrime, rPrime);
|
|
711
|
+
|
|
712
|
+
// Constant-time comparison & selection (implicit rejection)
|
|
713
|
+
let diff = 0;
|
|
714
|
+
for (let i = 0; i < MLKEM768_CIPHERTEXT_BYTES; i++) {
|
|
715
|
+
diff |= ciphertextArg[i] ^ cPrime[i];
|
|
716
|
+
}
|
|
717
|
+
// mask = 0x00 if diff === 0, else 0xff
|
|
718
|
+
const mask = ((diff | -diff) >> 31) & 0xff;
|
|
719
|
+
const sharedSecret = new Uint8Array(32);
|
|
720
|
+
for (let i = 0; i < 32; i++) {
|
|
721
|
+
sharedSecret[i] = (kPrime[i] & ~mask) | (kBar[i] & mask);
|
|
722
|
+
}
|
|
723
|
+
mPrime.fill(0);
|
|
724
|
+
gOut.fill(0);
|
|
725
|
+
kBar.fill(0);
|
|
726
|
+
return sharedSecret;
|
|
727
|
+
};
|
|
728
|
+
|
|
729
|
+
/**
|
|
730
|
+
* Wraps a validated raw 1184-byte ML-KEM-768 public key in canonical ASN.1 DER
|
|
731
|
+
* SubjectPublicKeyInfo (1206 bytes, compatible with OpenSSL 3.5 / Node.js).
|
|
732
|
+
*/
|
|
733
|
+
export const mlKem768PublicKeyToSpki = (publicKeyArg: Uint8Array): Uint8Array => {
|
|
734
|
+
assertValidMlKem768PublicKey(publicKeyArg);
|
|
735
|
+
return concatBytes(MLKEM768_SPKI_PREFIX, publicKeyArg);
|
|
736
|
+
};
|
|
737
|
+
|
|
738
|
+
/**
|
|
739
|
+
* Extracts and validates the raw 1184-byte ML-KEM-768 public key from a canonical
|
|
740
|
+
* 1206-byte ASN.1 DER SubjectPublicKeyInfo buffer.
|
|
741
|
+
*/
|
|
742
|
+
export const spkiToMlKem768PublicKey = (spkiArg: Uint8Array): Uint8Array => {
|
|
743
|
+
if (!(spkiArg instanceof Uint8Array) || spkiArg.length !== MLKEM768_SPKI_BYTES) {
|
|
744
|
+
throw createSmartCryptoError('INVALID_KEY', 'ML-KEM-768 SPKI must be 1206 bytes');
|
|
745
|
+
}
|
|
746
|
+
for (let i = 0; i < MLKEM768_SPKI_PREFIX.length; i++) {
|
|
747
|
+
if (spkiArg[i] !== MLKEM768_SPKI_PREFIX[i]) {
|
|
748
|
+
throw createSmartCryptoError('INVALID_KEY', 'ML-KEM-768 SPKI header is not canonical');
|
|
749
|
+
}
|
|
750
|
+
}
|
|
751
|
+
const raw = spkiArg.slice(MLKEM768_SPKI_PREFIX.length);
|
|
752
|
+
assertValidMlKem768PublicKey(raw);
|
|
753
|
+
return raw;
|
|
754
|
+
};
|