starknet 11.8.0 → 11.9.1
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/CHANGELOG.md +12 -0
- package/dist/falcon/index.d.ts +194 -2
- package/dist/falcon/index.js +833 -154
- package/dist/falcon/index.js.map +1 -1
- package/dist/falcon/index.mjs +828 -150
- package/dist/falcon/index.mjs.map +1 -1
- package/dist/index.d.ts +102 -47
- package/dist/index.global.js +130 -67
- package/dist/index.global.js.map +1 -1
- package/dist/index.js +130 -67
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +130 -67
- package/dist/index.mjs.map +1 -1
- package/package.json +1 -1
package/dist/falcon/index.js
CHANGED
|
@@ -31,7 +31,8 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
|
|
|
31
31
|
var falcon_exports = {};
|
|
32
32
|
__export(falcon_exports, {
|
|
33
33
|
Falcon512Signer: () => Falcon512Signer,
|
|
34
|
-
falcon512: () => falcon512_exports
|
|
34
|
+
falcon512: () => falcon512_exports,
|
|
35
|
+
mlkem: () => mlkem_exports
|
|
35
36
|
});
|
|
36
37
|
module.exports = __toCommonJS(falcon_exports);
|
|
37
38
|
|
|
@@ -105,7 +106,7 @@ function ownershipAcceptanceHash(accountAddress, currentPublicKey) {
|
|
|
105
106
|
}
|
|
106
107
|
|
|
107
108
|
// src/falcon/oz/signature.ts
|
|
108
|
-
var
|
|
109
|
+
var import_utils9 = require("@noble/hashes/utils.js");
|
|
109
110
|
var starknet6 = __toESM(require("starknet"));
|
|
110
111
|
|
|
111
112
|
// src/falcon/engine/noble/falcon.ts
|
|
@@ -123,6 +124,15 @@ var import_sha3 = require("@noble/hashes/sha3.js");
|
|
|
123
124
|
|
|
124
125
|
// src/falcon/engine/noble/utils.ts
|
|
125
126
|
var import_utils = require("@noble/hashes/utils.js");
|
|
127
|
+
var abytesDoc = import_utils.abytes;
|
|
128
|
+
var randomBytes = import_utils.randomBytes;
|
|
129
|
+
function aarray(item, title, inner = () => {
|
|
130
|
+
}) {
|
|
131
|
+
if (!Array.isArray(item))
|
|
132
|
+
throw new TypeError(`"${title}" expected array, got type=${typeof item}`);
|
|
133
|
+
for (let i = 0; i < item.length; i++) inner(item[i], `${title}[${i}]`);
|
|
134
|
+
return item;
|
|
135
|
+
}
|
|
126
136
|
function aobject(value, title = "object") {
|
|
127
137
|
if (value === null || typeof value !== "object" || Array.isArray(value))
|
|
128
138
|
throw new TypeError(
|
|
@@ -130,6 +140,14 @@ function aobject(value, title = "object") {
|
|
|
130
140
|
);
|
|
131
141
|
return value;
|
|
132
142
|
}
|
|
143
|
+
function equalBytes(a, b) {
|
|
144
|
+
a = (0, import_utils.abytes)(a);
|
|
145
|
+
b = (0, import_utils.abytes)(b);
|
|
146
|
+
if (a.length !== b.length) return false;
|
|
147
|
+
let diff = 0;
|
|
148
|
+
for (let i = 0; i < a.length; i++) diff |= a[i] ^ b[i];
|
|
149
|
+
return diff === 0;
|
|
150
|
+
}
|
|
133
151
|
function copyBytes(bytes) {
|
|
134
152
|
return new Uint8Array((0, import_utils.abytes)(bytes));
|
|
135
153
|
}
|
|
@@ -152,10 +170,10 @@ function byteSwap64(arr) {
|
|
|
152
170
|
return arr;
|
|
153
171
|
}
|
|
154
172
|
var baswap64If = import_utils.isLE ? (arr) => arr : byteSwap64;
|
|
155
|
-
function validateOpts(
|
|
156
|
-
if ((0, import_utils.isBytes)(
|
|
157
|
-
aobject(
|
|
158
|
-
const proto = Object.getPrototypeOf(
|
|
173
|
+
function validateOpts(opts2) {
|
|
174
|
+
if ((0, import_utils.isBytes)(opts2)) throw new TypeError('"opts" expected object, got Uint8Array');
|
|
175
|
+
aobject(opts2, "opts");
|
|
176
|
+
const proto = Object.getPrototypeOf(opts2);
|
|
159
177
|
if (proto !== null && proto !== Object.prototype)
|
|
160
178
|
throw new TypeError('"opts" expected a plain object');
|
|
161
179
|
}
|
|
@@ -166,9 +184,9 @@ var SIG_OPT_KEYS = /* @__PURE__ */ Object.freeze([
|
|
|
166
184
|
"context",
|
|
167
185
|
"extraEntropy"
|
|
168
186
|
]);
|
|
169
|
-
function checkOptKeys(
|
|
170
|
-
validateOpts(
|
|
171
|
-
const normalized = Object.assign(/* @__PURE__ */ Object.create(null),
|
|
187
|
+
function checkOptKeys(opts2, allowed) {
|
|
188
|
+
validateOpts(opts2);
|
|
189
|
+
const normalized = Object.assign(/* @__PURE__ */ Object.create(null), opts2);
|
|
172
190
|
for (const [k, v] of Object.entries(normalized)) {
|
|
173
191
|
if (v === void 0) continue;
|
|
174
192
|
if (!allowed.includes(k))
|
|
@@ -178,13 +196,13 @@ function checkOptKeys(opts, allowed) {
|
|
|
178
196
|
}
|
|
179
197
|
return Object.freeze(normalized);
|
|
180
198
|
}
|
|
181
|
-
function validateVerOpts(
|
|
182
|
-
const normalized = checkOptKeys(
|
|
199
|
+
function validateVerOpts(opts2, allowed = VER_OPT_KEYS) {
|
|
200
|
+
const normalized = checkOptKeys(opts2, allowed);
|
|
183
201
|
if (normalized.context !== void 0) (0, import_utils.abytes)(normalized.context, void 0, "opts.context");
|
|
184
202
|
return normalized;
|
|
185
203
|
}
|
|
186
|
-
function validateSigOpts(
|
|
187
|
-
const normalized = checkOptKeys(
|
|
204
|
+
function validateSigOpts(opts2, allowed = SIG_OPT_KEYS) {
|
|
205
|
+
const normalized = checkOptKeys(opts2, allowed);
|
|
188
206
|
if (normalized.context !== void 0) (0, import_utils.abytes)(normalized.context, void 0, "opts.context");
|
|
189
207
|
if (normalized.extraEntropy !== false && normalized.extraEntropy !== void 0)
|
|
190
208
|
(0, import_utils.abytes)(normalized.extraEntropy, void 0, "opts.extraEntropy");
|
|
@@ -221,6 +239,33 @@ function splitCoder(label, ...lengths) {
|
|
|
221
239
|
}
|
|
222
240
|
};
|
|
223
241
|
}
|
|
242
|
+
function vecCoder(c, vecLen) {
|
|
243
|
+
const coder = c;
|
|
244
|
+
const bytesLen = vecLen * coder.bytesLen;
|
|
245
|
+
return {
|
|
246
|
+
bytesLen,
|
|
247
|
+
encode: (u) => {
|
|
248
|
+
const uArr = aarray(u, "u");
|
|
249
|
+
if (uArr.length !== vecLen)
|
|
250
|
+
throw new RangeError(`vecCoder.encode: wrong length=${uArr.length}. Expected: ${vecLen}`);
|
|
251
|
+
const res = new Uint8Array(bytesLen);
|
|
252
|
+
for (let i = 0, pos = 0; i < uArr.length; i++) {
|
|
253
|
+
const b = coder.encode(uArr[i]);
|
|
254
|
+
res.set(b, pos);
|
|
255
|
+
b.fill(0);
|
|
256
|
+
pos += b.length;
|
|
257
|
+
}
|
|
258
|
+
return res;
|
|
259
|
+
},
|
|
260
|
+
decode: (a) => {
|
|
261
|
+
(0, import_utils.abytes)(a, bytesLen);
|
|
262
|
+
const r = [];
|
|
263
|
+
for (let i = 0; i < a.length; i += coder.bytesLen)
|
|
264
|
+
r.push(coder.decode(a.subarray(i, i + coder.bytesLen)));
|
|
265
|
+
return r;
|
|
266
|
+
}
|
|
267
|
+
};
|
|
268
|
+
}
|
|
224
269
|
function cleanBytes(...list) {
|
|
225
270
|
for (const t of list) {
|
|
226
271
|
if (Array.isArray(t)) for (const b of t) b.fill(0);
|
|
@@ -234,21 +279,21 @@ function getMask(bits) {
|
|
|
234
279
|
}
|
|
235
280
|
|
|
236
281
|
// src/falcon/engine/noble/_crystals.ts
|
|
237
|
-
var genCrystals = (
|
|
238
|
-
const { newPoly, N:
|
|
239
|
-
const mod = (a, modulo =
|
|
282
|
+
var genCrystals = (opts2) => {
|
|
283
|
+
const { newPoly, N: N3, Q: Q4, F: F2, ROOT_OF_UNITY: ROOT_OF_UNITY2, brvBits, isKyber } = opts2;
|
|
284
|
+
const mod = (a, modulo = Q4) => {
|
|
240
285
|
const result = a % modulo | 0;
|
|
241
286
|
return (result >= 0 ? result | 0 : modulo + result | 0) | 0;
|
|
242
287
|
};
|
|
243
|
-
const smod = (a, modulo =
|
|
288
|
+
const smod = (a, modulo = Q4) => {
|
|
244
289
|
const r = mod(a, modulo) | 0;
|
|
245
290
|
return (r > modulo >> 1 ? r - modulo | 0 : r) | 0;
|
|
246
291
|
};
|
|
247
292
|
function getZettas() {
|
|
248
|
-
const out = newPoly(
|
|
249
|
-
for (let i = 0; i <
|
|
293
|
+
const out = newPoly(N3);
|
|
294
|
+
for (let i = 0; i < N3; i++) {
|
|
250
295
|
const b = (0, import_fft.reverseBits)(i, brvBits);
|
|
251
|
-
const p = BigInt(
|
|
296
|
+
const p = BigInt(ROOT_OF_UNITY2) ** BigInt(b) % BigInt(Q4);
|
|
252
297
|
out[i] = Number(p) | 0;
|
|
253
298
|
}
|
|
254
299
|
return out;
|
|
@@ -260,11 +305,11 @@ var genCrystals = (opts) => {
|
|
|
260
305
|
const field = isKyber ? {
|
|
261
306
|
add: (a, b) => {
|
|
262
307
|
const r = a + b | 0;
|
|
263
|
-
return r >=
|
|
308
|
+
return r >= Q4 ? r - Q4 | 0 : r;
|
|
264
309
|
},
|
|
265
310
|
sub: (a, b) => {
|
|
266
311
|
const r = a - b | 0;
|
|
267
|
-
return r < 0 ? r +
|
|
312
|
+
return r < 0 ? r + Q4 | 0 : r;
|
|
268
313
|
},
|
|
269
314
|
mul: (a, b) => mod((a | 0) * (b | 0)) | 0,
|
|
270
315
|
inv
|
|
@@ -275,7 +320,7 @@ var genCrystals = (opts) => {
|
|
|
275
320
|
inv
|
|
276
321
|
};
|
|
277
322
|
const nttOpts = {
|
|
278
|
-
N:
|
|
323
|
+
N: N3,
|
|
279
324
|
roots: nttZetas,
|
|
280
325
|
invertButterflies: true,
|
|
281
326
|
skipStages: isKyber ? 1 : 0,
|
|
@@ -289,18 +334,18 @@ var genCrystals = (opts) => {
|
|
|
289
334
|
},
|
|
290
335
|
decode: (r) => {
|
|
291
336
|
dit(r);
|
|
292
|
-
for (let i = 0; i < r.length; i++) r[i] = mod(
|
|
337
|
+
for (let i = 0; i < r.length; i++) r[i] = mod(F2 * r[i]);
|
|
293
338
|
return r;
|
|
294
339
|
}
|
|
295
340
|
};
|
|
296
341
|
const bitsCoder = (d, c) => {
|
|
297
|
-
for (let i = 0, bufLen = 0; i <
|
|
342
|
+
for (let i = 0, bufLen = 0; i < N3; i++) {
|
|
298
343
|
bufLen += d;
|
|
299
344
|
if (bufLen > 32) getMask(bufLen);
|
|
300
345
|
bufLen %= 8;
|
|
301
346
|
}
|
|
302
347
|
const mask = getMask(d);
|
|
303
|
-
const bytesLen = d * (
|
|
348
|
+
const bytesLen = d * (N3 / 8);
|
|
304
349
|
return {
|
|
305
350
|
bytesLen,
|
|
306
351
|
encode: (poly_) => {
|
|
@@ -314,7 +359,7 @@ var genCrystals = (opts) => {
|
|
|
314
359
|
return r;
|
|
315
360
|
},
|
|
316
361
|
decode: (bytes) => {
|
|
317
|
-
const r = newPoly(
|
|
362
|
+
const r = newPoly(N3);
|
|
318
363
|
for (let i = 0, buf = 0, bufLen = 0, pos = 0; i < bytes.length; i++) {
|
|
319
364
|
buf |= bytes[i] << bufLen;
|
|
320
365
|
bufLen += 8;
|
|
@@ -335,15 +380,44 @@ var genCrystals = (opts) => {
|
|
|
335
380
|
bitsCoder
|
|
336
381
|
};
|
|
337
382
|
};
|
|
383
|
+
var createXofShake = (shake) => (seed, blockLen) => {
|
|
384
|
+
if (!blockLen) blockLen = shake.blockLen;
|
|
385
|
+
const _seed = new Uint8Array(seed.length + 2);
|
|
386
|
+
_seed.set(seed);
|
|
387
|
+
const seedLen = seed.length;
|
|
388
|
+
const buf = new Uint8Array(blockLen);
|
|
389
|
+
let h = shake.create({});
|
|
390
|
+
let calls = 0;
|
|
391
|
+
let xofs = 0;
|
|
392
|
+
return {
|
|
393
|
+
stats: () => ({ calls, xofs }),
|
|
394
|
+
get: (x, y) => {
|
|
395
|
+
_seed[seedLen + 0] = x;
|
|
396
|
+
_seed[seedLen + 1] = y;
|
|
397
|
+
h.destroy();
|
|
398
|
+
h = shake.create({}).update(_seed);
|
|
399
|
+
calls++;
|
|
400
|
+
return () => {
|
|
401
|
+
xofs++;
|
|
402
|
+
return h.xofInto(buf);
|
|
403
|
+
};
|
|
404
|
+
},
|
|
405
|
+
clean: () => {
|
|
406
|
+
h.destroy();
|
|
407
|
+
cleanBytes(buf, _seed);
|
|
408
|
+
}
|
|
409
|
+
};
|
|
410
|
+
};
|
|
411
|
+
var XOF128 = /* @__PURE__ */ createXofShake(import_sha3.shake128);
|
|
338
412
|
|
|
339
413
|
// src/falcon/engine/noble/falcon.ts
|
|
340
|
-
var bitsCoderMSB = (newPoly,
|
|
414
|
+
var bitsCoderMSB = (newPoly, N3, d, c) => {
|
|
341
415
|
const mask = getMask(d);
|
|
342
|
-
const bytesLen = d * (
|
|
416
|
+
const bytesLen = d * (N3 / 8);
|
|
343
417
|
return {
|
|
344
418
|
bytesLen,
|
|
345
419
|
encode: (poly) => {
|
|
346
|
-
if (poly.length !==
|
|
420
|
+
if (poly.length !== N3) throw new Error(`wrong length: expected ${N3}, got ${poly.length}`);
|
|
347
421
|
const r = new Uint8Array(bytesLen);
|
|
348
422
|
for (let i = 0, buf = 0, bufLen = 0, pos = 0; i < poly.length; i++) {
|
|
349
423
|
buf = buf << d | c.encode(poly[i]) & mask;
|
|
@@ -353,7 +427,7 @@ var bitsCoderMSB = (newPoly, N2, d, c) => {
|
|
|
353
427
|
return r;
|
|
354
428
|
},
|
|
355
429
|
decode: (bytes) => {
|
|
356
|
-
const r = newPoly(
|
|
430
|
+
const r = newPoly(N3);
|
|
357
431
|
for (let i = 0, buf = 0, bufLen = 0, pos = 0; i < bytes.length; i++) {
|
|
358
432
|
buf = buf << 8 | bytes[i];
|
|
359
433
|
bufLen += 8;
|
|
@@ -463,43 +537,43 @@ var cleanCPoly = (...list) => {
|
|
|
463
537
|
}
|
|
464
538
|
};
|
|
465
539
|
function getComplex(field) {
|
|
466
|
-
const
|
|
540
|
+
const F2 = field;
|
|
467
541
|
return {
|
|
468
542
|
lift: (x) => {
|
|
469
543
|
if (x.re !== void 0 && x.im !== void 0) return x;
|
|
470
|
-
return { re: x, im:
|
|
544
|
+
return { re: x, im: F2.ZERO };
|
|
471
545
|
},
|
|
472
546
|
add: (a, b) => ({
|
|
473
|
-
re:
|
|
474
|
-
im:
|
|
547
|
+
re: F2.add(a.re, b.re),
|
|
548
|
+
im: F2.add(a.im, b.im)
|
|
475
549
|
}),
|
|
476
550
|
sub: (a, b) => ({
|
|
477
|
-
re:
|
|
478
|
-
im:
|
|
551
|
+
re: F2.sub(a.re, b.re),
|
|
552
|
+
im: F2.sub(a.im, b.im)
|
|
479
553
|
}),
|
|
480
554
|
mul: (a, b) => ({
|
|
481
|
-
re:
|
|
482
|
-
im:
|
|
555
|
+
re: F2.sub(F2.mul(a.re, b.re), F2.mul(a.im, b.im)),
|
|
556
|
+
im: F2.add(F2.mul(a.re, b.im), F2.mul(a.im, b.re))
|
|
483
557
|
}),
|
|
484
558
|
div: (a, b) => {
|
|
485
|
-
const denom =
|
|
559
|
+
const denom = F2.add(F2.mul(b.re, b.re), F2.mul(b.im, b.im));
|
|
486
560
|
return {
|
|
487
|
-
re:
|
|
488
|
-
im:
|
|
561
|
+
re: F2.div(F2.add(F2.mul(a.re, b.re), F2.mul(a.im, b.im)), denom),
|
|
562
|
+
im: F2.div(F2.sub(F2.mul(a.im, b.re), F2.mul(a.re, b.im)), denom)
|
|
489
563
|
};
|
|
490
564
|
},
|
|
491
|
-
neg: (a) => ({ re:
|
|
492
|
-
conj: (a) => ({ re: a.re, im:
|
|
565
|
+
neg: (a) => ({ re: F2.neg(a.re), im: F2.neg(a.im) }),
|
|
566
|
+
conj: (a) => ({ re: a.re, im: F2.neg(a.im) }),
|
|
493
567
|
scale: (a, x) => ({
|
|
494
|
-
re:
|
|
495
|
-
im:
|
|
568
|
+
re: F2.mul(a.re, x),
|
|
569
|
+
im: F2.mul(a.im, x)
|
|
496
570
|
}),
|
|
497
571
|
// a.re * a.re + a.im * a.im + b.re * b.re + b.im * b.im;
|
|
498
|
-
magSqSum: (a, b) =>
|
|
499
|
-
|
|
500
|
-
|
|
572
|
+
magSqSum: (a, b) => F2.add(
|
|
573
|
+
F2.add(F2.add(F2.mul(a.re, a.re), F2.mul(a.im, a.im)), F2.mul(b.re, b.re)),
|
|
574
|
+
F2.mul(b.im, b.im)
|
|
501
575
|
),
|
|
502
|
-
eql: (a, b) =>
|
|
576
|
+
eql: (a, b) => F2.eql(a.re, b.re) && F2.eql(a.im, b.im),
|
|
503
577
|
clone: (a) => ({ re: a.re, im: a.im }),
|
|
504
578
|
inv: () => {
|
|
505
579
|
throw new Error("not implemented");
|
|
@@ -508,8 +582,8 @@ function getComplex(field) {
|
|
|
508
582
|
}
|
|
509
583
|
var ComplexArr = {
|
|
510
584
|
decode(lst) {
|
|
511
|
-
const
|
|
512
|
-
const hn =
|
|
585
|
+
const N3 = lst.length;
|
|
586
|
+
const hn = N3 >> 1;
|
|
513
587
|
const len = lst.length;
|
|
514
588
|
if (len === 0) return [];
|
|
515
589
|
if (len % 2 !== 0)
|
|
@@ -780,11 +854,11 @@ var intField = {
|
|
|
780
854
|
function getIntPoly(logn) {
|
|
781
855
|
const n = 1 << logn;
|
|
782
856
|
const newPoly = (n2) => new Uint16Array(n2);
|
|
783
|
-
const
|
|
857
|
+
const F2 = Number((0, import_modular.invert)(BigInt(n), QBig));
|
|
784
858
|
const { mod, smod, NTT } = genCrystals({
|
|
785
859
|
N: n,
|
|
786
860
|
Q: Q2,
|
|
787
|
-
F,
|
|
861
|
+
F: F2,
|
|
788
862
|
ROOT_OF_UNITY: 7,
|
|
789
863
|
newPoly,
|
|
790
864
|
isKyber: false,
|
|
@@ -934,9 +1008,9 @@ function ApproxExp(x, ccs) {
|
|
|
934
1008
|
for (let i = ev.length - 2; i >= 0; i--) z = z * y + ev[i];
|
|
935
1009
|
return ccs * (1 + z * y);
|
|
936
1010
|
}
|
|
937
|
-
function genFalcon(
|
|
938
|
-
const { N:
|
|
939
|
-
const logn = Math.log2(
|
|
1011
|
+
function genFalcon(opts2) {
|
|
1012
|
+
const { N: N3 } = opts2;
|
|
1013
|
+
const logn = Math.log2(N3);
|
|
940
1014
|
const id = (n) => n;
|
|
941
1015
|
const { newPoly, intPoly, signedCoder } = getIntPoly(logn);
|
|
942
1016
|
const floatPoly = getFloatPoly(logn);
|
|
@@ -1023,7 +1097,7 @@ function genFalcon(opts) {
|
|
|
1023
1097
|
}
|
|
1024
1098
|
return a;
|
|
1025
1099
|
}
|
|
1026
|
-
reduce(logn2, f, g,
|
|
1100
|
+
reduce(logn2, f, g, F2, G, logn_top) {
|
|
1027
1101
|
const n = 1 << logn2;
|
|
1028
1102
|
const depth = logn_top - logn2;
|
|
1029
1103
|
const floatPoly2 = getFloatPoly(logn2);
|
|
@@ -1050,7 +1124,7 @@ function genFalcon(opts) {
|
|
|
1050
1124
|
while (true) {
|
|
1051
1125
|
let scaleFG = _31n * (FGlen - _10n);
|
|
1052
1126
|
for (let i = 0; i < n; i++) {
|
|
1053
|
-
Fx[i] = Number(
|
|
1127
|
+
Fx[i] = Number(F2[i] >> scaleFG);
|
|
1054
1128
|
Gx[i] = Number(G[i] >> scaleFG);
|
|
1055
1129
|
}
|
|
1056
1130
|
const rt2 = floatPoly2.mul(floatPoly2.FFT(floatPoly2.to(Gx)), rt4);
|
|
@@ -1065,7 +1139,7 @@ function genFalcon(opts) {
|
|
|
1065
1139
|
if (val <= -BOUND || val >= BOUND) return false;
|
|
1066
1140
|
k[i] = BigInt(Math.round(val));
|
|
1067
1141
|
}
|
|
1068
|
-
|
|
1142
|
+
F2 = this.subMul(logn2, F2, f, k, scaleK);
|
|
1069
1143
|
G = this.subMul(logn2, G, g, k, scaleK);
|
|
1070
1144
|
const maxfgNew = scaleK + BigInt(Math.round(fgMaxBits)) + _10n;
|
|
1071
1145
|
if (maxfgNew < maxFGBits) maxFGBits = maxfgNew;
|
|
@@ -1077,7 +1151,7 @@ function genFalcon(opts) {
|
|
|
1077
1151
|
return true;
|
|
1078
1152
|
}
|
|
1079
1153
|
// This is recursive thing that goes from logn to 0
|
|
1080
|
-
solveBranch(logn2, f, g,
|
|
1154
|
+
solveBranch(logn2, f, g, F2, G, logn_top) {
|
|
1081
1155
|
if (logn2 === 0) {
|
|
1082
1156
|
const xf = f[0];
|
|
1083
1157
|
const xg = g[0];
|
|
@@ -1085,7 +1159,7 @@ function genFalcon(opts) {
|
|
|
1085
1159
|
try {
|
|
1086
1160
|
const u1 = (0, import_modular.invert)(xf, xg);
|
|
1087
1161
|
const v1 = (_1n - u1 * xf) / xg;
|
|
1088
|
-
|
|
1162
|
+
F2[0] = -v1 * QBig;
|
|
1089
1163
|
G[0] = u1 * QBig;
|
|
1090
1164
|
return true;
|
|
1091
1165
|
} catch (e) {
|
|
@@ -1101,9 +1175,9 @@ function genFalcon(opts) {
|
|
|
1101
1175
|
const Fp = new Array(hn);
|
|
1102
1176
|
const Gp = new Array(hn);
|
|
1103
1177
|
if (!this.solveBranch(logn2 - 1, fp, gp, Fp, Gp, logn_top)) return false;
|
|
1104
|
-
|
|
1178
|
+
F2 = this.mulConjD(logn2, F2, g, Fp);
|
|
1105
1179
|
G = this.mulConjD(logn2, G, f, Gp);
|
|
1106
|
-
return this.reduce(logn2, f, g,
|
|
1180
|
+
return this.reduce(logn2, f, g, F2, G, logn_top);
|
|
1107
1181
|
}
|
|
1108
1182
|
solve(f, g) {
|
|
1109
1183
|
const n = 1 << logn;
|
|
@@ -1112,16 +1186,16 @@ function genFalcon(opts) {
|
|
|
1112
1186
|
const bF = new Array(n);
|
|
1113
1187
|
const bG = new Array(n);
|
|
1114
1188
|
if (!this.solveBranch(logn, bf, bg, bF, bG)) return false;
|
|
1115
|
-
const
|
|
1189
|
+
const F2 = new Int8Array(n);
|
|
1116
1190
|
const G = new Int8Array(n);
|
|
1117
1191
|
for (let i = 0; i < n; i++) {
|
|
1118
1192
|
const x = bF[i];
|
|
1119
1193
|
const y = bG[i];
|
|
1120
1194
|
if (x < -127 || x > 127 || y < -127 || y > 127) return false;
|
|
1121
|
-
|
|
1195
|
+
F2[i] = Number(x);
|
|
1122
1196
|
G[i] = Number(y);
|
|
1123
1197
|
}
|
|
1124
|
-
return [
|
|
1198
|
+
return [F2, G];
|
|
1125
1199
|
}
|
|
1126
1200
|
generate() {
|
|
1127
1201
|
let max = 1e6;
|
|
@@ -1130,8 +1204,8 @@ function genFalcon(opts) {
|
|
|
1130
1204
|
if (curr++ === max) throw new Error("can't generate key");
|
|
1131
1205
|
const f = this.polyGauss();
|
|
1132
1206
|
const g = this.polyGauss();
|
|
1133
|
-
let lim = 1 <<
|
|
1134
|
-
for (let u = 0; u <
|
|
1207
|
+
let lim = 1 << opts2.fgBits - 1;
|
|
1208
|
+
for (let u = 0; u < N3; u++) {
|
|
1135
1209
|
if (f[u] >= lim || f[u] <= -lim || g[u] >= lim || g[u] <= -lim) {
|
|
1136
1210
|
lim = -1;
|
|
1137
1211
|
break;
|
|
@@ -1170,7 +1244,7 @@ function genFalcon(opts) {
|
|
|
1170
1244
|
}
|
|
1171
1245
|
}
|
|
1172
1246
|
const modqCoder = () => {
|
|
1173
|
-
const coder = bitsCoderMSB(newPoly,
|
|
1247
|
+
const coder = bitsCoderMSB(newPoly, N3, 14, {
|
|
1174
1248
|
encode: id,
|
|
1175
1249
|
decode: id
|
|
1176
1250
|
});
|
|
@@ -1196,7 +1270,7 @@ function genFalcon(opts) {
|
|
|
1196
1270
|
};
|
|
1197
1271
|
const trimI8Coder = (bits) => {
|
|
1198
1272
|
const shift = 32 - bits;
|
|
1199
|
-
const coder = bitsCoderMSB((len) => new Int8Array(len),
|
|
1273
|
+
const coder = bitsCoderMSB((len) => new Int8Array(len), N3, bits, {
|
|
1200
1274
|
encode: (v) => v & (1 << bits) - 1,
|
|
1201
1275
|
decode: (w) => (w & getMask(bits)) << shift >> shift
|
|
1202
1276
|
});
|
|
@@ -1218,25 +1292,25 @@ function genFalcon(opts) {
|
|
|
1218
1292
|
}
|
|
1219
1293
|
};
|
|
1220
1294
|
};
|
|
1221
|
-
const fgCoder = trimI8Coder(
|
|
1222
|
-
const FGCoder = trimI8Coder(
|
|
1295
|
+
const fgCoder = trimI8Coder(opts2.fgBits);
|
|
1296
|
+
const FGCoder = trimI8Coder(opts2.FGBits);
|
|
1223
1297
|
const secretKeyCoder = headerCoder(
|
|
1224
1298
|
80 + logn,
|
|
1225
1299
|
splitCoder("falcon.secretKey", fgCoder, fgCoder, FGCoder)
|
|
1226
1300
|
);
|
|
1227
1301
|
const publicKeyCoder = headerCoder(0 + logn, modqCoder());
|
|
1228
1302
|
const decodePaddedSig = (s2) => {
|
|
1229
|
-
const normalized = compCoder(
|
|
1303
|
+
const normalized = compCoder(N3).encode(compCoder(N3).decode(s2));
|
|
1230
1304
|
for (let i = normalized.length; i < s2.length; i++)
|
|
1231
1305
|
if (s2[i] !== 0) throw new Error("non-zero padding");
|
|
1232
1306
|
return normalized;
|
|
1233
1307
|
};
|
|
1234
1308
|
const decodeUnpaddedSig = (s2) => {
|
|
1235
|
-
const normalized = compCoder(
|
|
1309
|
+
const normalized = compCoder(N3).encode(compCoder(N3).decode(s2));
|
|
1236
1310
|
if (normalized.length !== s2.length) throw new Error("wrong signature length");
|
|
1237
1311
|
return s2;
|
|
1238
1312
|
};
|
|
1239
|
-
const decodeSig =
|
|
1313
|
+
const decodeSig = opts2.padded ? decodePaddedSig : decodeUnpaddedSig;
|
|
1240
1314
|
const SignatureCoderBasic = (logn2) => {
|
|
1241
1315
|
const TYPE_BYTE = 32 + logn2;
|
|
1242
1316
|
return {
|
|
@@ -1273,7 +1347,7 @@ function genFalcon(opts) {
|
|
|
1273
1347
|
};
|
|
1274
1348
|
};
|
|
1275
1349
|
const SignatureCoderPadded = (logn2) => {
|
|
1276
|
-
const sigLen =
|
|
1350
|
+
const sigLen = opts2.paddedLen;
|
|
1277
1351
|
return {
|
|
1278
1352
|
encode({ msg, nonce, s2 }) {
|
|
1279
1353
|
return headerCoder(
|
|
@@ -1294,19 +1368,19 @@ function genFalcon(opts) {
|
|
|
1294
1368
|
};
|
|
1295
1369
|
};
|
|
1296
1370
|
const SignatureCoderDetached = (logn2) => {
|
|
1297
|
-
const paddedSigLen =
|
|
1298
|
-
const getSigLen = (s2) =>
|
|
1371
|
+
const paddedSigLen = opts2.sigLen - 1 - NONCELEN;
|
|
1372
|
+
const getSigLen = (s2) => opts2.padded ? paddedSigLen : s2.length;
|
|
1299
1373
|
return {
|
|
1300
1374
|
encode({ nonce, s2 }) {
|
|
1301
1375
|
return headerCoder(
|
|
1302
1376
|
48 + logn2,
|
|
1303
1377
|
splitCoder("falcon.detachedSignature", NONCELEN, getSigLen(s2))
|
|
1304
|
-
).encode([nonce,
|
|
1378
|
+
).encode([nonce, opts2.padded ? pad(paddedSigLen).encode(s2) : s2]);
|
|
1305
1379
|
},
|
|
1306
1380
|
decode(data) {
|
|
1307
|
-
if (!
|
|
1381
|
+
if (!opts2.padded && data.length > 1 + NONCELEN + opts2.maxS2Len)
|
|
1308
1382
|
throw new Error("detached signature too long");
|
|
1309
|
-
const payloadLen =
|
|
1383
|
+
const payloadLen = opts2.padded ? paddedSigLen : data.length - NONCELEN - 1;
|
|
1310
1384
|
const [nonce, raw] = headerCoder(
|
|
1311
1385
|
48 + logn2,
|
|
1312
1386
|
splitCoder("falcon.detachedSignature", NONCELEN, payloadLen)
|
|
@@ -1316,10 +1390,10 @@ function genFalcon(opts) {
|
|
|
1316
1390
|
}
|
|
1317
1391
|
};
|
|
1318
1392
|
};
|
|
1319
|
-
const SignatureCoder = (
|
|
1393
|
+
const SignatureCoder = (opts2.padded ? SignatureCoderPadded : SignatureCoderBasic)(logn);
|
|
1320
1394
|
const invertF = (f) => {
|
|
1321
1395
|
const tt = intPoly.ntt(signedCoder.decode(f));
|
|
1322
|
-
for (let u = 0; u <
|
|
1396
|
+
for (let u = 0; u < N3; u++)
|
|
1323
1397
|
if (tt[u] === 0) throw new Error("invalid secretKey: non-invertible f");
|
|
1324
1398
|
return tt;
|
|
1325
1399
|
};
|
|
@@ -1330,13 +1404,13 @@ function genFalcon(opts) {
|
|
|
1330
1404
|
cleanBytes(tt);
|
|
1331
1405
|
return res2;
|
|
1332
1406
|
}
|
|
1333
|
-
function completePrivate(f, g,
|
|
1407
|
+
function completePrivate(f, g, F2) {
|
|
1334
1408
|
let t1 = intPoly.toMontgomery(intPoly.ntt(signedCoder.decode(g)));
|
|
1335
|
-
const t2 = intPoly.ntt(signedCoder.decode(
|
|
1409
|
+
const t2 = intPoly.ntt(signedCoder.decode(F2));
|
|
1336
1410
|
const tt = invertF(f);
|
|
1337
1411
|
t1 = intPoly.div(intPoly.mul(t1, t2), tt);
|
|
1338
|
-
const G = new Int8Array(
|
|
1339
|
-
for (let u = 0; u <
|
|
1412
|
+
const G = new Int8Array(N3);
|
|
1413
|
+
for (let u = 0; u < N3; u++) {
|
|
1340
1414
|
let w = t1[u];
|
|
1341
1415
|
w -= Q2 & ~-(w - Qhalf >>> 31);
|
|
1342
1416
|
const gi = w | 0;
|
|
@@ -1351,9 +1425,9 @@ function genFalcon(opts) {
|
|
|
1351
1425
|
}
|
|
1352
1426
|
function HashToPoint(nonce, msg) {
|
|
1353
1427
|
const h = import_sha32.shake256.create().update(nonce).update(msg);
|
|
1354
|
-
const c = new Uint16Array(
|
|
1428
|
+
const c = new Uint16Array(N3);
|
|
1355
1429
|
const kQ = 5 * Q2;
|
|
1356
|
-
for (let i = 0; i <
|
|
1430
|
+
for (let i = 0; i < N3; ) {
|
|
1357
1431
|
const tmp = h.xof(2);
|
|
1358
1432
|
let w = tmp[0] << 8 | tmp[1];
|
|
1359
1433
|
if (w < kQ) c[i++] = w % Q2;
|
|
@@ -1608,15 +1682,15 @@ function genFalcon(opts) {
|
|
|
1608
1682
|
const seed = rnd(48);
|
|
1609
1683
|
(0, import_utils4.abytes)(seed, 48, "seed");
|
|
1610
1684
|
try {
|
|
1611
|
-
const [f, g,
|
|
1685
|
+
const [f, g, F2] = secretKeyCoder.decode(sk);
|
|
1612
1686
|
try {
|
|
1613
|
-
const G = completePrivate(f, g,
|
|
1687
|
+
const G = completePrivate(f, g, F2);
|
|
1614
1688
|
const b00 = floatPoly.FFT(floatPoly.convSmall(g));
|
|
1615
1689
|
const b01 = floatPoly.FFT(floatPoly.neg(floatPoly.convSmall(f)));
|
|
1616
1690
|
const b10 = floatPoly.FFT(floatPoly.convSmall(G));
|
|
1617
|
-
const b11 = floatPoly.FFT(floatPoly.neg(floatPoly.convSmall(
|
|
1691
|
+
const b11 = floatPoly.FFT(floatPoly.neg(floatPoly.convSmall(F2)));
|
|
1618
1692
|
const sampler = new FFSampler(logn, seed, b00, b01, b10, b11);
|
|
1619
|
-
const s2 = new Int16Array(
|
|
1693
|
+
const s2 = new Int16Array(N3);
|
|
1620
1694
|
try {
|
|
1621
1695
|
while (true) {
|
|
1622
1696
|
const { t0, t1 } = sampler.sample(hm);
|
|
@@ -1624,7 +1698,7 @@ function genFalcon(opts) {
|
|
|
1624
1698
|
const t3 = floatPoly.mul(t0, b01);
|
|
1625
1699
|
const t4 = floatPoly.iFFT(t2);
|
|
1626
1700
|
const t5 = floatPoly.iFFT(floatPoly.add(floatPoly.mul(t1, b11), t3));
|
|
1627
|
-
const hn =
|
|
1701
|
+
const hn = N3 >> 1;
|
|
1628
1702
|
let sqn = 0;
|
|
1629
1703
|
for (let i = 0; i < hn; i++) {
|
|
1630
1704
|
sqn += (hm[i] - (Math.round(t4[i].re) | 0)) ** 2;
|
|
@@ -1638,7 +1712,7 @@ function genFalcon(opts) {
|
|
|
1638
1712
|
}
|
|
1639
1713
|
cleanCPoly(t0, t1, t2, t3, t4, t5);
|
|
1640
1714
|
if (!(sqn <= L2BOUND[logn])) continue;
|
|
1641
|
-
const s2comp = compCoder(
|
|
1715
|
+
const s2comp = compCoder(N3).encode(s2);
|
|
1642
1716
|
if (s2comp.length > maxLen) {
|
|
1643
1717
|
cleanBytes(s2comp);
|
|
1644
1718
|
continue;
|
|
@@ -1652,14 +1726,14 @@ function genFalcon(opts) {
|
|
|
1652
1726
|
cleanBytes(G);
|
|
1653
1727
|
}
|
|
1654
1728
|
} finally {
|
|
1655
|
-
cleanBytes(f, g,
|
|
1729
|
+
cleanBytes(f, g, F2);
|
|
1656
1730
|
}
|
|
1657
1731
|
} finally {
|
|
1658
1732
|
cleanBytes(seed);
|
|
1659
1733
|
}
|
|
1660
1734
|
};
|
|
1661
1735
|
const verifyRaw = (pk, s2comp, nonce, msg) => {
|
|
1662
|
-
const s2 = compCoder(
|
|
1736
|
+
const s2 = compCoder(N3).decode(s2comp);
|
|
1663
1737
|
const c0 = HashToPoint(nonce, msg);
|
|
1664
1738
|
const h = intPoly.toMontgomery(intPoly.ntt(publicKeyCoder.decode(pk)));
|
|
1665
1739
|
const s1 = intPoly.intt(intPoly.mul(intPoly.ntt(signedCoder.decode(s2)), h));
|
|
@@ -1673,54 +1747,54 @@ function genFalcon(opts) {
|
|
|
1673
1747
|
secretKey: secretKeyCoder.bytesLen
|
|
1674
1748
|
});
|
|
1675
1749
|
const FALCON_SIG_OPT_KEYS = [...SIG_OPT_KEYS, "random"];
|
|
1676
|
-
const getRnd = (
|
|
1677
|
-
|
|
1678
|
-
if (
|
|
1679
|
-
if (
|
|
1680
|
-
throw new TypeError('"opts.random" expected function, got type=' + typeof
|
|
1681
|
-
if (
|
|
1682
|
-
if (
|
|
1683
|
-
const seed =
|
|
1750
|
+
const getRnd = (opts3 = {}) => {
|
|
1751
|
+
opts3 = validateSigOpts(opts3, FALCON_SIG_OPT_KEYS);
|
|
1752
|
+
if (opts3.context !== void 0) throw new Error("context is not supported");
|
|
1753
|
+
if (opts3.random !== void 0 && typeof opts3.random !== "function")
|
|
1754
|
+
throw new TypeError('"opts.random" expected function, got type=' + typeof opts3.random);
|
|
1755
|
+
if (opts3.random !== void 0) return opts3.random;
|
|
1756
|
+
if (opts3.extraEntropy === void 0) return import_utils4.randomBytes;
|
|
1757
|
+
const seed = opts3.extraEntropy === false ? new Uint8Array(48) : opts3.extraEntropy;
|
|
1684
1758
|
(0, import_utils4.abytes)(seed, 48, "opts.extraEntropy");
|
|
1685
1759
|
const drbg = (0, import_aes.rngAesCtrDrbg256)(seed);
|
|
1686
1760
|
return (len = 0) => drbg.randomBytes(len);
|
|
1687
1761
|
};
|
|
1688
|
-
const checkVerOpts = (
|
|
1689
|
-
const normalized = validateVerOpts(
|
|
1762
|
+
const checkVerOpts = (opts3 = {}) => {
|
|
1763
|
+
const normalized = validateVerOpts(opts3);
|
|
1690
1764
|
if (normalized.context !== void 0) throw new Error("context is not supported");
|
|
1691
1765
|
};
|
|
1692
1766
|
const tests = Object.freeze({
|
|
1693
1767
|
publicKeyCoder: Object.freeze(publicKeyCoder),
|
|
1694
1768
|
privateKeyCoder: Object.freeze(secretKeyCoder),
|
|
1695
|
-
maxS2Len:
|
|
1769
|
+
maxS2Len: opts2.maxS2Len
|
|
1696
1770
|
});
|
|
1697
1771
|
const attachedLengths = Object.freeze({ ...keyLengths, signRand: 48 });
|
|
1698
|
-
const lengths =
|
|
1772
|
+
const lengths = opts2.padded ? Object.freeze({ ...attachedLengths, signature: opts2.sigLen }) : attachedLengths;
|
|
1699
1773
|
const keygen = (seed) => {
|
|
1700
1774
|
const randSeed = seed === void 0;
|
|
1701
1775
|
if (randSeed) seed = (0, import_utils4.randomBytes)(48);
|
|
1702
1776
|
(0, import_utils4.abytes)(seed, 48, "seed");
|
|
1703
|
-
const [f, g,
|
|
1704
|
-
const sk = secretKeyCoder.encode([f, g,
|
|
1777
|
+
const [f, g, F2, _G, pub] = new NTRU(logn, seed).generate();
|
|
1778
|
+
const sk = secretKeyCoder.encode([f, g, F2]);
|
|
1705
1779
|
const pk = publicKeyCoder.encode(pub);
|
|
1706
1780
|
if (randSeed) cleanBytes(seed);
|
|
1707
|
-
cleanBytes(f, g,
|
|
1781
|
+
cleanBytes(f, g, F2, _G);
|
|
1708
1782
|
return { publicKey: pk, secretKey: sk };
|
|
1709
1783
|
};
|
|
1710
1784
|
const getPublicKey2 = (sk) => {
|
|
1711
1785
|
(0, import_utils4.abytes)(sk, secretKeyCoder.bytesLen, "secretKey");
|
|
1712
|
-
const [f, g,
|
|
1786
|
+
const [f, g, F2] = secretKeyCoder.decode(sk);
|
|
1713
1787
|
try {
|
|
1714
1788
|
const h = computePublic(f, g);
|
|
1715
|
-
cleanBytes(f, g,
|
|
1789
|
+
cleanBytes(f, g, F2);
|
|
1716
1790
|
return publicKeyCoder.encode(h);
|
|
1717
1791
|
} catch (e) {
|
|
1718
|
-
cleanBytes(f, g,
|
|
1792
|
+
cleanBytes(f, g, F2);
|
|
1719
1793
|
throw e;
|
|
1720
1794
|
}
|
|
1721
1795
|
};
|
|
1722
1796
|
const sign = (msg, sk, sigOpts = {}) => {
|
|
1723
|
-
const { s2, nonce } = signRaw(sk, msg,
|
|
1797
|
+
const { s2, nonce } = signRaw(sk, msg, opts2.maxS2Len, getRnd(sigOpts));
|
|
1724
1798
|
return SignatureCoderDetached(logn).encode({ nonce, s2 });
|
|
1725
1799
|
};
|
|
1726
1800
|
const verify2 = (sig, msg, pk, verOpts = {}) => {
|
|
@@ -1741,7 +1815,7 @@ function genFalcon(opts) {
|
|
|
1741
1815
|
keygen,
|
|
1742
1816
|
getPublicKey: getPublicKey2,
|
|
1743
1817
|
seal(msg, sk, sigOpts = {}) {
|
|
1744
|
-
const { s2, nonce } = signRaw(sk, msg,
|
|
1818
|
+
const { s2, nonce } = signRaw(sk, msg, opts2.maxS2Len, getRnd(sigOpts));
|
|
1745
1819
|
return SignatureCoder.encode({ msg, nonce, s2 });
|
|
1746
1820
|
},
|
|
1747
1821
|
open(sig, pk, verOpts = {}) {
|
|
@@ -1767,9 +1841,9 @@ function genFalcon(opts) {
|
|
|
1767
1841
|
});
|
|
1768
1842
|
const INTERNAL_MAX_ITERATIONS = 1e3;
|
|
1769
1843
|
const checkHashPoint = (hashPoint) => {
|
|
1770
|
-
if (!(hashPoint instanceof Uint16Array) || hashPoint.length !==
|
|
1771
|
-
throw new Error(`hashPoint: expected Uint16Array(${
|
|
1772
|
-
for (let i = 0; i <
|
|
1844
|
+
if (!(hashPoint instanceof Uint16Array) || hashPoint.length !== N3)
|
|
1845
|
+
throw new Error(`hashPoint: expected Uint16Array(${N3})`);
|
|
1846
|
+
for (let i = 0; i < N3; i++)
|
|
1773
1847
|
if (hashPoint[i] >= Q2) throw new Error("hashPoint: coefficient out of range");
|
|
1774
1848
|
};
|
|
1775
1849
|
const internal = Object.freeze({
|
|
@@ -1782,15 +1856,15 @@ function genFalcon(opts) {
|
|
|
1782
1856
|
const seed = rnd(48);
|
|
1783
1857
|
(0, import_utils4.abytes)(seed, 48, "seed");
|
|
1784
1858
|
try {
|
|
1785
|
-
const [f, g,
|
|
1859
|
+
const [f, g, F2] = secretKeyCoder.decode(sk);
|
|
1786
1860
|
try {
|
|
1787
|
-
const G = completePrivate(f, g,
|
|
1861
|
+
const G = completePrivate(f, g, F2);
|
|
1788
1862
|
const b00 = floatPoly.FFT(floatPoly.convSmall(g));
|
|
1789
1863
|
const b01 = floatPoly.FFT(floatPoly.neg(floatPoly.convSmall(f)));
|
|
1790
1864
|
const b10 = floatPoly.FFT(floatPoly.convSmall(G));
|
|
1791
|
-
const b11 = floatPoly.FFT(floatPoly.neg(floatPoly.convSmall(
|
|
1865
|
+
const b11 = floatPoly.FFT(floatPoly.neg(floatPoly.convSmall(F2)));
|
|
1792
1866
|
const sampler = new FFSampler(logn, seed, b00, b01, b10, b11);
|
|
1793
|
-
const s2 = new Int16Array(
|
|
1867
|
+
const s2 = new Int16Array(N3);
|
|
1794
1868
|
try {
|
|
1795
1869
|
for (let iteration = 0; iteration < maxIterations; iteration++) {
|
|
1796
1870
|
const { t0, t1 } = sampler.sample(hm);
|
|
@@ -1798,7 +1872,7 @@ function genFalcon(opts) {
|
|
|
1798
1872
|
const t3 = floatPoly.mul(t0, b01);
|
|
1799
1873
|
const t4 = floatPoly.iFFT(t2);
|
|
1800
1874
|
const t5 = floatPoly.iFFT(floatPoly.add(floatPoly.mul(t1, b11), t3));
|
|
1801
|
-
const hn =
|
|
1875
|
+
const hn = N3 >> 1;
|
|
1802
1876
|
let sqn = 0;
|
|
1803
1877
|
for (let i = 0; i < hn; i++) {
|
|
1804
1878
|
sqn += (hm[i] - (Math.round(t4[i].re) | 0)) ** 2;
|
|
@@ -1821,7 +1895,7 @@ function genFalcon(opts) {
|
|
|
1821
1895
|
cleanBytes(G);
|
|
1822
1896
|
}
|
|
1823
1897
|
} finally {
|
|
1824
|
-
cleanBytes(f, g,
|
|
1898
|
+
cleanBytes(f, g, F2);
|
|
1825
1899
|
}
|
|
1826
1900
|
} finally {
|
|
1827
1901
|
cleanBytes(seed);
|
|
@@ -1829,8 +1903,8 @@ function genFalcon(opts) {
|
|
|
1829
1903
|
},
|
|
1830
1904
|
verify(s2, hashPoint, pk) {
|
|
1831
1905
|
checkHashPoint(hashPoint);
|
|
1832
|
-
if (!(s2 instanceof Int16Array) || s2.length !==
|
|
1833
|
-
throw new Error(`s2: expected Int16Array(${
|
|
1906
|
+
if (!(s2 instanceof Int16Array) || s2.length !== N3)
|
|
1907
|
+
throw new Error(`s2: expected Int16Array(${N3})`);
|
|
1834
1908
|
(0, import_utils4.abytes)(pk, publicKeyCoder.bytesLen, "publicKey");
|
|
1835
1909
|
const h = intPoly.toMontgomery(intPoly.ntt(publicKeyCoder.decode(pk)));
|
|
1836
1910
|
const s1 = intPoly.intt(intPoly.mul(intPoly.ntt(signedCoder.decode(s2)), h));
|
|
@@ -1864,6 +1938,380 @@ var falcon512opts = {
|
|
|
1864
1938
|
};
|
|
1865
1939
|
var falcon512 = /* @__PURE__ */ (() => genFalcon({ ...falcon512opts, maxS2Len: 711 }))();
|
|
1866
1940
|
|
|
1941
|
+
// src/falcon/engine/noble/ml-kem.ts
|
|
1942
|
+
var import_sha33 = require("@noble/hashes/sha3.js");
|
|
1943
|
+
var import_utils6 = require("@noble/hashes/utils.js");
|
|
1944
|
+
var N2 = 256;
|
|
1945
|
+
var Q3 = 3329;
|
|
1946
|
+
var F = 3303;
|
|
1947
|
+
var ROOT_OF_UNITY = 17;
|
|
1948
|
+
var crystals = /* @__PURE__ */ genCrystals({
|
|
1949
|
+
N: N2,
|
|
1950
|
+
Q: Q3,
|
|
1951
|
+
F,
|
|
1952
|
+
ROOT_OF_UNITY,
|
|
1953
|
+
newPoly: (n) => new Uint16Array(n),
|
|
1954
|
+
brvBits: 7,
|
|
1955
|
+
isKyber: true
|
|
1956
|
+
});
|
|
1957
|
+
var PARAMS = /* @__PURE__ */ (() => Object.freeze({
|
|
1958
|
+
512: Object.freeze({ N: N2, Q: Q3, K: 2, ETA1: 3, ETA2: 2, du: 10, dv: 4, RBGstrength: 128 }),
|
|
1959
|
+
768: Object.freeze({ N: N2, Q: Q3, K: 3, ETA1: 2, ETA2: 2, du: 10, dv: 4, RBGstrength: 192 }),
|
|
1960
|
+
1024: Object.freeze({ N: N2, Q: Q3, K: 4, ETA1: 2, ETA2: 2, du: 11, dv: 5, RBGstrength: 256 })
|
|
1961
|
+
}))();
|
|
1962
|
+
var compress = (d) => {
|
|
1963
|
+
if (d >= 12) return { encode: (i) => i, decode: (i) => i >= Q3 ? i - Q3 : i };
|
|
1964
|
+
const a = 2 ** (d - 1);
|
|
1965
|
+
return {
|
|
1966
|
+
// This only matches standalone Compress_d after bitsCoder masks the result into Z_(2^d).
|
|
1967
|
+
encode: (i) => ((i << d) + Q3 / 2) / Q3,
|
|
1968
|
+
// const decompress = (i: number) => round((Q / 2 ** d) * i);
|
|
1969
|
+
decode: (i) => i * Q3 + a >>> d
|
|
1970
|
+
};
|
|
1971
|
+
};
|
|
1972
|
+
var byteCoder = (d) => crystals.bitsCoder(
|
|
1973
|
+
d,
|
|
1974
|
+
d === 12 ? { encode: (i) => i, decode: (i) => i >= Q3 ? i - Q3 : i } : { encode: (i) => i, decode: (i) => i }
|
|
1975
|
+
);
|
|
1976
|
+
var polyCoder = (d) => d === 12 ? byteCoder(12) : crystals.bitsCoder(d, compress(d));
|
|
1977
|
+
function polyAdd(a_, b_) {
|
|
1978
|
+
const a = a_;
|
|
1979
|
+
const b = b_;
|
|
1980
|
+
for (let i = 0; i < N2; i++) {
|
|
1981
|
+
const r = a[i] + b[i];
|
|
1982
|
+
a[i] = r >= Q3 ? r - Q3 : r;
|
|
1983
|
+
}
|
|
1984
|
+
}
|
|
1985
|
+
function polySub(a_, b_) {
|
|
1986
|
+
const a = a_;
|
|
1987
|
+
const b = b_;
|
|
1988
|
+
for (let i = 0; i < N2; i++) {
|
|
1989
|
+
const r = a[i] - b[i];
|
|
1990
|
+
a[i] = r < 0 ? r + Q3 : r;
|
|
1991
|
+
}
|
|
1992
|
+
}
|
|
1993
|
+
function BaseCaseMultiply(a0, a1, b0, b1, zeta) {
|
|
1994
|
+
const c0 = crystals.mod(crystals.mod(a1 * b1) * zeta + a0 * b0);
|
|
1995
|
+
const c1 = crystals.mod(a0 * b1 + a1 * b0);
|
|
1996
|
+
return { c0, c1 };
|
|
1997
|
+
}
|
|
1998
|
+
function MultiplyNTTs(f_, g_) {
|
|
1999
|
+
const f = f_;
|
|
2000
|
+
const g = g_;
|
|
2001
|
+
for (let i = 0; i < N2 / 2; i++) {
|
|
2002
|
+
let z = crystals.nttZetas[64 + (i >> 1)];
|
|
2003
|
+
if (i & 1) z = -z;
|
|
2004
|
+
const { c0, c1 } = BaseCaseMultiply(f[2 * i + 0], f[2 * i + 1], g[2 * i + 0], g[2 * i + 1], z);
|
|
2005
|
+
f[2 * i + 0] = c0;
|
|
2006
|
+
f[2 * i + 1] = c1;
|
|
2007
|
+
}
|
|
2008
|
+
return f;
|
|
2009
|
+
}
|
|
2010
|
+
function SampleNTT(xof_) {
|
|
2011
|
+
const xof = xof_;
|
|
2012
|
+
const r = new Uint16Array(N2);
|
|
2013
|
+
for (let j = 0; j < N2; ) {
|
|
2014
|
+
const b = xof();
|
|
2015
|
+
if (b.length % 3) throw new Error("SampleNTT: unaligned block");
|
|
2016
|
+
for (let i = 0; j < N2 && i + 3 <= b.length; i += 3) {
|
|
2017
|
+
const d1 = (b[i + 0] >> 0 | b[i + 1] << 8) & 4095;
|
|
2018
|
+
const d2 = (b[i + 1] >> 4 | b[i + 2] << 4) & 4095;
|
|
2019
|
+
if (d1 < Q3) r[j++] = d1;
|
|
2020
|
+
if (j < N2 && d2 < Q3) r[j++] = d2;
|
|
2021
|
+
}
|
|
2022
|
+
}
|
|
2023
|
+
return r;
|
|
2024
|
+
}
|
|
2025
|
+
var sampleCBDBytes = (buf, eta) => {
|
|
2026
|
+
const r = new Uint16Array(N2);
|
|
2027
|
+
const b32 = (0, import_utils6.u32)(buf);
|
|
2028
|
+
(0, import_utils6.swap32IfBE)(b32);
|
|
2029
|
+
let len = 0;
|
|
2030
|
+
for (let i = 0, p = 0, bb = 0, t0 = 0; i < b32.length; i++) {
|
|
2031
|
+
let b = b32[i];
|
|
2032
|
+
for (let j = 0; j < 32; j++) {
|
|
2033
|
+
bb += b & 1;
|
|
2034
|
+
b >>= 1;
|
|
2035
|
+
len += 1;
|
|
2036
|
+
if (len === eta) {
|
|
2037
|
+
t0 = bb;
|
|
2038
|
+
bb = 0;
|
|
2039
|
+
} else if (len === 2 * eta) {
|
|
2040
|
+
r[p++] = crystals.mod(t0 - bb);
|
|
2041
|
+
bb = 0;
|
|
2042
|
+
len = 0;
|
|
2043
|
+
}
|
|
2044
|
+
}
|
|
2045
|
+
}
|
|
2046
|
+
(0, import_utils6.swap32IfBE)(b32);
|
|
2047
|
+
if (len) throw new Error(`sampleCBD: leftover bits: ${len}`);
|
|
2048
|
+
return r;
|
|
2049
|
+
};
|
|
2050
|
+
function sampleCBD(PRF_, seed, nonce, eta) {
|
|
2051
|
+
const PRF = PRF_;
|
|
2052
|
+
return sampleCBDBytes(PRF(eta * N2 / 4, seed, nonce), eta);
|
|
2053
|
+
}
|
|
2054
|
+
var genKPKE = (opts_) => {
|
|
2055
|
+
const opts2 = opts_;
|
|
2056
|
+
const { K, PRF, XOF, HASH512, ETA1, ETA2, du, dv } = opts2;
|
|
2057
|
+
const poly1 = polyCoder(1);
|
|
2058
|
+
const polyV = polyCoder(dv);
|
|
2059
|
+
const polyU = polyCoder(du);
|
|
2060
|
+
const publicCoder = splitCoder("publicKey", vecCoder(polyCoder(12), K), 32);
|
|
2061
|
+
const secretCoder = vecCoder(polyCoder(12), K);
|
|
2062
|
+
const cipherCoder = splitCoder("ciphertext", vecCoder(polyU, K), polyV);
|
|
2063
|
+
const seedCoder = splitCoder("seed", 32, 32);
|
|
2064
|
+
const encryptCore = (tHat, getA, msg, seed) => {
|
|
2065
|
+
const rHat = [];
|
|
2066
|
+
for (let i = 0; i < K; i++) rHat.push(crystals.NTT.encode(sampleCBD(PRF, seed, i, ETA1)));
|
|
2067
|
+
const tmp2 = new Uint16Array(N2);
|
|
2068
|
+
const u = [];
|
|
2069
|
+
for (let i = 0; i < K; i++) {
|
|
2070
|
+
const e1 = sampleCBD(PRF, seed, K + i, ETA2);
|
|
2071
|
+
const tmp = new Uint16Array(N2);
|
|
2072
|
+
for (let j = 0; j < K; j++) {
|
|
2073
|
+
const aij = getA(i, j);
|
|
2074
|
+
polyAdd(tmp, MultiplyNTTs(aij, rHat[j]));
|
|
2075
|
+
}
|
|
2076
|
+
polyAdd(e1, crystals.NTT.decode(tmp));
|
|
2077
|
+
u.push(e1);
|
|
2078
|
+
polyAdd(tmp2, MultiplyNTTs(tHat[i], rHat[i]));
|
|
2079
|
+
cleanBytes(tmp);
|
|
2080
|
+
}
|
|
2081
|
+
const e2 = sampleCBD(PRF, seed, 2 * K, ETA2);
|
|
2082
|
+
polyAdd(e2, crystals.NTT.decode(tmp2));
|
|
2083
|
+
const v = poly1.decode(msg);
|
|
2084
|
+
polyAdd(v, e2);
|
|
2085
|
+
cleanBytes(tHat, rHat, tmp2, e2);
|
|
2086
|
+
return cipherCoder.encode([u, v]);
|
|
2087
|
+
};
|
|
2088
|
+
return {
|
|
2089
|
+
secretCoder,
|
|
2090
|
+
lengths: {
|
|
2091
|
+
secretKey: secretCoder.bytesLen,
|
|
2092
|
+
publicKey: publicCoder.bytesLen,
|
|
2093
|
+
cipherText: cipherCoder.bytesLen
|
|
2094
|
+
},
|
|
2095
|
+
keygen: (seed) => {
|
|
2096
|
+
abytesDoc(seed, 32, "seed");
|
|
2097
|
+
const seedDst = new Uint8Array(33);
|
|
2098
|
+
seedDst.set(seed);
|
|
2099
|
+
seedDst[32] = K;
|
|
2100
|
+
const seedHash = HASH512(seedDst);
|
|
2101
|
+
const [rho, sigma] = seedCoder.decode(seedHash);
|
|
2102
|
+
const sHat = [];
|
|
2103
|
+
const tHat = [];
|
|
2104
|
+
for (let i = 0; i < K; i++) sHat.push(crystals.NTT.encode(sampleCBD(PRF, sigma, i, ETA1)));
|
|
2105
|
+
const x = XOF(rho);
|
|
2106
|
+
for (let i = 0; i < K; i++) {
|
|
2107
|
+
const e = crystals.NTT.encode(sampleCBD(PRF, sigma, K + i, ETA1));
|
|
2108
|
+
for (let j = 0; j < K; j++) {
|
|
2109
|
+
const aji = SampleNTT(x.get(j, i));
|
|
2110
|
+
polyAdd(e, MultiplyNTTs(aji, sHat[j]));
|
|
2111
|
+
}
|
|
2112
|
+
tHat.push(e);
|
|
2113
|
+
}
|
|
2114
|
+
x.clean();
|
|
2115
|
+
const res = {
|
|
2116
|
+
publicKey: publicCoder.encode([tHat, rho]),
|
|
2117
|
+
secretKey: secretCoder.encode(sHat)
|
|
2118
|
+
};
|
|
2119
|
+
cleanBytes(rho, sigma, sHat, tHat, seedDst, seedHash);
|
|
2120
|
+
return res;
|
|
2121
|
+
},
|
|
2122
|
+
encrypt: (publicKey, msg, seed) => {
|
|
2123
|
+
const [tHat, rho] = publicCoder.decode(publicKey);
|
|
2124
|
+
const x = XOF(rho);
|
|
2125
|
+
const res = encryptCore(tHat, (i, j) => SampleNTT(x.get(i, j)), msg, seed);
|
|
2126
|
+
x.clean();
|
|
2127
|
+
return res;
|
|
2128
|
+
},
|
|
2129
|
+
// Expands the full  matrix (public data derived from rho) once, so repeated encryptions
|
|
2130
|
+
// against the same ek skip the K² SampleNTT XOF expansions. Cached polys are copied per
|
|
2131
|
+
// call because encryptCore mutates its inputs in place.
|
|
2132
|
+
prepare: (publicKey) => {
|
|
2133
|
+
const [tHat, rho] = publicCoder.decode(publicKey);
|
|
2134
|
+
const x = XOF(rho);
|
|
2135
|
+
const A = [];
|
|
2136
|
+
for (let i = 0; i < K; i++)
|
|
2137
|
+
for (let j = 0; j < K; j++) A.push(SampleNTT(x.get(i, j)));
|
|
2138
|
+
x.clean();
|
|
2139
|
+
return {
|
|
2140
|
+
encrypt: (msg, seed) => encryptCore(
|
|
2141
|
+
tHat.map((p) => p.slice()),
|
|
2142
|
+
(i, j) => A[i * K + j].slice(),
|
|
2143
|
+
msg,
|
|
2144
|
+
seed
|
|
2145
|
+
),
|
|
2146
|
+
clean: () => cleanBytes(tHat, A)
|
|
2147
|
+
};
|
|
2148
|
+
},
|
|
2149
|
+
decrypt: (cipherText, privateKey) => {
|
|
2150
|
+
const [u, v] = cipherCoder.decode(cipherText);
|
|
2151
|
+
const sk = secretCoder.decode(privateKey);
|
|
2152
|
+
const tmp = new Uint16Array(N2);
|
|
2153
|
+
for (let i = 0; i < K; i++) polyAdd(tmp, MultiplyNTTs(sk[i], crystals.NTT.encode(u[i])));
|
|
2154
|
+
polySub(v, crystals.NTT.decode(tmp));
|
|
2155
|
+
const res = poly1.encode(v);
|
|
2156
|
+
cleanBytes(tmp, sk, u, v);
|
|
2157
|
+
return res;
|
|
2158
|
+
}
|
|
2159
|
+
};
|
|
2160
|
+
};
|
|
2161
|
+
function createKyber(opts2) {
|
|
2162
|
+
const rawOpts = opts2;
|
|
2163
|
+
const KPKE = genKPKE(rawOpts);
|
|
2164
|
+
const { HASH256, HASH512, KDF } = rawOpts;
|
|
2165
|
+
const { secretCoder: KPKESecretCoder, lengths } = KPKE;
|
|
2166
|
+
const secretCoder = splitCoder("secretKey", lengths.secretKey, lengths.publicKey, 32, 32);
|
|
2167
|
+
const msgLen = 32;
|
|
2168
|
+
const seedLen = 64;
|
|
2169
|
+
const validateModulus = (publicKey, fn) => {
|
|
2170
|
+
const eke = publicKey.subarray(0, 384 * rawOpts.K);
|
|
2171
|
+
const ek = KPKESecretCoder.encode(KPKESecretCoder.decode(copyBytes(eke)));
|
|
2172
|
+
const ok = equalBytes(ek, eke);
|
|
2173
|
+
cleanBytes(ek);
|
|
2174
|
+
if (!ok) throw new Error(`ML-KEM.${fn}: wrong publicKey modulus`);
|
|
2175
|
+
};
|
|
2176
|
+
const kemLengths = Object.freeze({
|
|
2177
|
+
...lengths,
|
|
2178
|
+
seed: 64,
|
|
2179
|
+
msg: msgLen,
|
|
2180
|
+
msgRand: msgLen,
|
|
2181
|
+
secretKey: secretCoder.bytesLen
|
|
2182
|
+
});
|
|
2183
|
+
return Object.freeze({
|
|
2184
|
+
info: Object.freeze({ type: "ml-kem" }),
|
|
2185
|
+
lengths: kemLengths,
|
|
2186
|
+
keygen: (seed) => {
|
|
2187
|
+
const ownSeed = seed === void 0;
|
|
2188
|
+
const s = ownSeed ? randomBytes(seedLen) : seed;
|
|
2189
|
+
let sk;
|
|
2190
|
+
let publicKeyHash;
|
|
2191
|
+
try {
|
|
2192
|
+
abytesDoc(s, seedLen, "seed");
|
|
2193
|
+
const keys = KPKE.keygen(s.subarray(0, 32));
|
|
2194
|
+
const publicKey = keys.publicKey;
|
|
2195
|
+
sk = keys.secretKey;
|
|
2196
|
+
publicKeyHash = HASH256(publicKey);
|
|
2197
|
+
const secretKey = secretCoder.encode([sk, publicKey, publicKeyHash, s.subarray(32)]);
|
|
2198
|
+
return {
|
|
2199
|
+
publicKey,
|
|
2200
|
+
secretKey
|
|
2201
|
+
};
|
|
2202
|
+
} finally {
|
|
2203
|
+
if (sk !== void 0) cleanBytes(sk);
|
|
2204
|
+
if (publicKeyHash !== void 0) cleanBytes(publicKeyHash);
|
|
2205
|
+
if (ownSeed) cleanBytes(s);
|
|
2206
|
+
}
|
|
2207
|
+
},
|
|
2208
|
+
getPublicKey: (secretKey) => {
|
|
2209
|
+
const [_sk, publicKey, _publicKeyHash, _z] = secretCoder.decode(secretKey);
|
|
2210
|
+
return Uint8Array.from(publicKey);
|
|
2211
|
+
},
|
|
2212
|
+
encapsulate: (publicKey, msg) => {
|
|
2213
|
+
const ownMsg = msg === void 0;
|
|
2214
|
+
const m = ownMsg ? randomBytes(msgLen) : msg;
|
|
2215
|
+
let kr;
|
|
2216
|
+
try {
|
|
2217
|
+
abytesDoc(publicKey, lengths.publicKey, "publicKey");
|
|
2218
|
+
abytesDoc(m, msgLen, "message");
|
|
2219
|
+
validateModulus(publicKey, "encapsulate");
|
|
2220
|
+
kr = HASH512.create().update(m).update(HASH256(publicKey)).digest();
|
|
2221
|
+
const cipherText = KPKE.encrypt(publicKey, m, kr.subarray(32, 64));
|
|
2222
|
+
return {
|
|
2223
|
+
cipherText,
|
|
2224
|
+
sharedSecret: kr.subarray(0, 32)
|
|
2225
|
+
};
|
|
2226
|
+
} finally {
|
|
2227
|
+
if (kr !== void 0) cleanBytes(kr.subarray(32));
|
|
2228
|
+
if (ownMsg) cleanBytes(m);
|
|
2229
|
+
}
|
|
2230
|
+
},
|
|
2231
|
+
decapsulate: (cipherText, secretKey) => {
|
|
2232
|
+
abytesDoc(secretKey, secretCoder.bytesLen, "secretKey");
|
|
2233
|
+
abytesDoc(cipherText, lengths.cipherText, "cipherText");
|
|
2234
|
+
const k768 = secretCoder.bytesLen - 96;
|
|
2235
|
+
const start = k768 + 32;
|
|
2236
|
+
const test = HASH256(secretKey.subarray(k768 / 2, start));
|
|
2237
|
+
if (!equalBytes(test, secretKey.subarray(start, start + 32)))
|
|
2238
|
+
throw new Error("invalid secretKey: hash check failed");
|
|
2239
|
+
const [sk, publicKey, publicKeyHash, z] = secretCoder.decode(secretKey);
|
|
2240
|
+
const msg = KPKE.decrypt(cipherText, sk);
|
|
2241
|
+
const kr = HASH512.create().update(msg).update(publicKeyHash).digest();
|
|
2242
|
+
const Khat = kr.subarray(0, 32);
|
|
2243
|
+
const cipherText2 = KPKE.encrypt(publicKey, msg, kr.subarray(32, 64));
|
|
2244
|
+
const isValid = equalBytes(cipherText, cipherText2);
|
|
2245
|
+
const Kbar = KDF.create({ dkLen: 32 }).update(z).update(cipherText).digest();
|
|
2246
|
+
cleanBytes(msg, cipherText2, kr.subarray(32), !isValid ? Khat : Kbar);
|
|
2247
|
+
return isValid ? Khat : Kbar;
|
|
2248
|
+
},
|
|
2249
|
+
/**
|
|
2250
|
+
* Experimental prototype: pre-expand a public key so repeated encapsulate/decapsulate
|
|
2251
|
+
* against the same key skip re-validation, H(ek), t̂ decoding and the K² SampleNTT
|
|
2252
|
+
* XOF expansions of Â. Only public data is cached; see {@link KEMPrepared}.
|
|
2253
|
+
*/
|
|
2254
|
+
prepare: (publicKey) => {
|
|
2255
|
+
abytesDoc(publicKey, lengths.publicKey, "publicKey");
|
|
2256
|
+
validateModulus(publicKey, "prepare");
|
|
2257
|
+
const ek = copyBytes(publicKey);
|
|
2258
|
+
const publicKeyHash = HASH256(ek);
|
|
2259
|
+
const cached = KPKE.prepare(ek);
|
|
2260
|
+
return Object.freeze({
|
|
2261
|
+
publicKey: ek,
|
|
2262
|
+
encapsulate: (msg) => {
|
|
2263
|
+
const ownMsg = msg === void 0;
|
|
2264
|
+
const m = ownMsg ? randomBytes(msgLen) : msg;
|
|
2265
|
+
let kr;
|
|
2266
|
+
try {
|
|
2267
|
+
abytesDoc(m, msgLen, "message");
|
|
2268
|
+
kr = HASH512.create().update(m).update(publicKeyHash).digest();
|
|
2269
|
+
const cipherText = cached.encrypt(m, kr.subarray(32, 64));
|
|
2270
|
+
return {
|
|
2271
|
+
cipherText,
|
|
2272
|
+
sharedSecret: kr.subarray(0, 32)
|
|
2273
|
+
};
|
|
2274
|
+
} finally {
|
|
2275
|
+
if (kr !== void 0) cleanBytes(kr.subarray(32));
|
|
2276
|
+
if (ownMsg) cleanBytes(m);
|
|
2277
|
+
}
|
|
2278
|
+
},
|
|
2279
|
+
decapsulate: (cipherText, secretKey) => {
|
|
2280
|
+
abytesDoc(secretKey, secretCoder.bytesLen, "secretKey");
|
|
2281
|
+
abytesDoc(cipherText, lengths.cipherText, "cipherText");
|
|
2282
|
+
const [sk, ekEmbedded, storedHash, z] = secretCoder.decode(secretKey);
|
|
2283
|
+
if (!equalBytes(ekEmbedded, ek) || !equalBytes(storedHash, publicKeyHash))
|
|
2284
|
+
throw new Error("ML-KEM.decapsulate: secretKey does not match prepared publicKey");
|
|
2285
|
+
const msg = KPKE.decrypt(cipherText, sk);
|
|
2286
|
+
const kr = HASH512.create().update(msg).update(publicKeyHash).digest();
|
|
2287
|
+
const Khat = kr.subarray(0, 32);
|
|
2288
|
+
const cipherText2 = cached.encrypt(msg, kr.subarray(32, 64));
|
|
2289
|
+
const isValid = equalBytes(cipherText, cipherText2);
|
|
2290
|
+
const Kbar = KDF.create({ dkLen: 32 }).update(z).update(cipherText).digest();
|
|
2291
|
+
cleanBytes(msg, cipherText2, kr.subarray(32), !isValid ? Khat : Kbar);
|
|
2292
|
+
return isValid ? Khat : Kbar;
|
|
2293
|
+
},
|
|
2294
|
+
clean: cached.clean
|
|
2295
|
+
});
|
|
2296
|
+
}
|
|
2297
|
+
});
|
|
2298
|
+
}
|
|
2299
|
+
function shakePRF(dkLen, key, nonce) {
|
|
2300
|
+
return import_sha33.shake256.create({ dkLen }).update(key).update(new Uint8Array([nonce])).digest();
|
|
2301
|
+
}
|
|
2302
|
+
var opts = /* @__PURE__ */ (() => ({
|
|
2303
|
+
HASH256: import_sha33.sha3_256,
|
|
2304
|
+
HASH512: import_sha33.sha3_512,
|
|
2305
|
+
KDF: import_sha33.shake256,
|
|
2306
|
+
XOF: XOF128,
|
|
2307
|
+
PRF: shakePRF
|
|
2308
|
+
}))();
|
|
2309
|
+
var mk = (params) => createKyber({
|
|
2310
|
+
...opts,
|
|
2311
|
+
...params
|
|
2312
|
+
});
|
|
2313
|
+
var ml_kem768 = /* @__PURE__ */ (() => mk(PARAMS[768]))();
|
|
2314
|
+
|
|
1867
2315
|
// src/falcon/engine/engine.ts
|
|
1868
2316
|
var nobleEngine = Object.freeze({
|
|
1869
2317
|
keygen: (seed) => falcon512.keygen(seed),
|
|
@@ -3057,7 +3505,7 @@ function unpackPoly(felts) {
|
|
|
3057
3505
|
}
|
|
3058
3506
|
|
|
3059
3507
|
// src/falcon/s2morrow/signature.ts
|
|
3060
|
-
var
|
|
3508
|
+
var import_utils8 = require("@noble/hashes/utils.js");
|
|
3061
3509
|
var starknet5 = __toESM(require("starknet"));
|
|
3062
3510
|
|
|
3063
3511
|
// src/falcon/s2morrow/hashToPoint.ts
|
|
@@ -3091,7 +3539,7 @@ function hashToPoint(message, salt) {
|
|
|
3091
3539
|
}
|
|
3092
3540
|
|
|
3093
3541
|
// src/falcon/s2morrow/signature.ts
|
|
3094
|
-
var defaultDeps = { engine: nobleEngine, randomBytes:
|
|
3542
|
+
var defaultDeps = { engine: nobleEngine, randomBytes: import_utils8.randomBytes };
|
|
3095
3543
|
function computeMulHint(s1, pkNtt) {
|
|
3096
3544
|
const s1Ntt = ntt(s1);
|
|
3097
3545
|
return intt(s1Ntt.map((v, i) => v * pkNtt[i] % Q));
|
|
@@ -3139,7 +3587,7 @@ function parseSignature(signature) {
|
|
|
3139
3587
|
mulHint: unpackPoly(felts.slice(saltStart + SALT_FELTS))
|
|
3140
3588
|
};
|
|
3141
3589
|
}
|
|
3142
|
-
var randomSaltFelt = (
|
|
3590
|
+
var randomSaltFelt = (randomBytes4) => BigInt(`0x${starknet5.encode.buf2hex(randomBytes4(31))}`);
|
|
3143
3591
|
function signHash(msgHash, secretKey, pkNtt, deps = defaultDeps) {
|
|
3144
3592
|
assertFelt(msgHash, "message hash");
|
|
3145
3593
|
const salt = [randomSaltFelt(deps.randomBytes), randomSaltFelt(deps.randomBytes)];
|
|
@@ -3171,7 +3619,7 @@ function verifyHash(msgHash, signature, pkNtt) {
|
|
|
3171
3619
|
}
|
|
3172
3620
|
|
|
3173
3621
|
// src/falcon/oz/hashToPoint.ts
|
|
3174
|
-
var
|
|
3622
|
+
var import_sha34 = require("@noble/hashes/sha3.js");
|
|
3175
3623
|
var SALT_BYTES = 20;
|
|
3176
3624
|
var SALT_LIMIT = 1n << BigInt(8 * SALT_BYTES);
|
|
3177
3625
|
var KQ = 5 * Q;
|
|
@@ -3197,7 +3645,7 @@ function hashToPointShake(msgHash, saltA, saltB) {
|
|
|
3197
3645
|
assertFelt(msgHash, "message hash");
|
|
3198
3646
|
const message = new Uint8Array(32);
|
|
3199
3647
|
writeLittleEndian(msgHash, message, 0, 32);
|
|
3200
|
-
const xof =
|
|
3648
|
+
const xof = import_sha34.shake256.create().update(saltFeltsToBytes(saltA, saltB)).update(message);
|
|
3201
3649
|
const out = new Uint16Array(N);
|
|
3202
3650
|
for (let i = 0; i < N; ) {
|
|
3203
3651
|
const [high, low] = xof.xof(2);
|
|
@@ -3215,7 +3663,7 @@ var OZ_SIGNATURE_FELTS = Object.freeze({
|
|
|
3215
3663
|
hint: 2 * PACKED_SLOTS + 2,
|
|
3216
3664
|
direct: PACKED_SLOTS + 2
|
|
3217
3665
|
});
|
|
3218
|
-
var defaultDeps2 = { engine: nobleEngine, randomBytes:
|
|
3666
|
+
var defaultDeps2 = { engine: nobleEngine, randomBytes: import_utils9.randomBytes };
|
|
3219
3667
|
var readLittleEndian = (bytes) => bytes.reduceRight((acc, byte) => acc * 256n + BigInt(byte), 0n);
|
|
3220
3668
|
function formatOzSignature(sig, variant) {
|
|
3221
3669
|
const felts = [...packPoly(sig.s1), sig.saltA, sig.saltB];
|
|
@@ -3275,7 +3723,7 @@ function verifyHashOz(msgHash, signature, pkNtt, variant) {
|
|
|
3275
3723
|
}
|
|
3276
3724
|
|
|
3277
3725
|
// src/falcon/s2morrow/keys.ts
|
|
3278
|
-
var
|
|
3726
|
+
var import_utils10 = require("@noble/hashes/utils.js");
|
|
3279
3727
|
var starknet7 = __toESM(require("starknet"));
|
|
3280
3728
|
var SECRET_KEY_LENGTH = 1281;
|
|
3281
3729
|
var PUBLIC_KEY_LENGTH = 897;
|
|
@@ -3290,7 +3738,7 @@ var FG_MAX = 31;
|
|
|
3290
3738
|
var CAPITAL_FG_MAX = 127;
|
|
3291
3739
|
var FG_BYTES = N * FG_BITS / 8;
|
|
3292
3740
|
function toBytes(input, expectedLength, label) {
|
|
3293
|
-
if ((0,
|
|
3741
|
+
if ((0, import_utils10.isBytes)(input)) {
|
|
3294
3742
|
if (input.length !== expectedLength) {
|
|
3295
3743
|
throw new Error(`Falcon512: ${label} must be ${expectedLength} bytes, got ${input.length}`);
|
|
3296
3744
|
}
|
|
@@ -3397,8 +3845,8 @@ function checkRange(poly, max, label) {
|
|
|
3397
3845
|
}
|
|
3398
3846
|
}
|
|
3399
3847
|
}
|
|
3400
|
-
function completeG(f, g,
|
|
3401
|
-
const gF = mulZq(g,
|
|
3848
|
+
function completeG(f, g, F2) {
|
|
3849
|
+
const gF = mulZq(g, F2);
|
|
3402
3850
|
let quotient = [];
|
|
3403
3851
|
let G = [];
|
|
3404
3852
|
try {
|
|
@@ -3410,9 +3858,9 @@ function completeG(f, g, F) {
|
|
|
3410
3858
|
wipe(gF, quotient, G);
|
|
3411
3859
|
}
|
|
3412
3860
|
}
|
|
3413
|
-
function checkNtruEquation({ f, g, F, G }) {
|
|
3861
|
+
function checkNtruEquation({ f, g, F: F2, G }) {
|
|
3414
3862
|
const fG = mulNegacyclicInt(f, G);
|
|
3415
|
-
const gF = mulNegacyclicInt(g,
|
|
3863
|
+
const gF = mulNegacyclicInt(g, F2);
|
|
3416
3864
|
try {
|
|
3417
3865
|
for (let i = 0; i < N; i++) {
|
|
3418
3866
|
if (fG[i] - gF[i] !== (i === 0 ? Q : 0)) {
|
|
@@ -3447,11 +3895,11 @@ function decodeSecretKey(secretKey) {
|
|
|
3447
3895
|
parts.push(f);
|
|
3448
3896
|
const g = decodeSigned(bytes.subarray(1 + FG_BYTES, 1 + 2 * FG_BYTES), FG_BITS, "g");
|
|
3449
3897
|
parts.push(g);
|
|
3450
|
-
const
|
|
3451
|
-
parts.push(
|
|
3452
|
-
const G = completeG(f, g,
|
|
3898
|
+
const F2 = decodeSigned(bytes.subarray(1 + 2 * FG_BYTES), CAPITAL_FG_BITS, "F");
|
|
3899
|
+
parts.push(F2);
|
|
3900
|
+
const G = completeG(f, g, F2);
|
|
3453
3901
|
parts.push(G);
|
|
3454
|
-
const polys = { f, g, F, G };
|
|
3902
|
+
const polys = { f, g, F: F2, G };
|
|
3455
3903
|
checkNtruEquation(polys);
|
|
3456
3904
|
return polys;
|
|
3457
3905
|
} catch (error) {
|
|
@@ -3461,13 +3909,13 @@ function decodeSecretKey(secretKey) {
|
|
|
3461
3909
|
wipe(bytes);
|
|
3462
3910
|
}
|
|
3463
3911
|
}
|
|
3464
|
-
function encodeSecretKey({ f, g, F }) {
|
|
3912
|
+
function encodeSecretKey({ f, g, F: F2 }) {
|
|
3465
3913
|
checkRange(f, FG_MAX, "f");
|
|
3466
3914
|
checkRange(g, FG_MAX, "g");
|
|
3467
|
-
checkRange(
|
|
3915
|
+
checkRange(F2, CAPITAL_FG_MAX, "F");
|
|
3468
3916
|
const fBits = Array.from(f, (v) => v & 63);
|
|
3469
3917
|
const gBits = Array.from(g, (v) => v & 63);
|
|
3470
|
-
const capitalFBits = Array.from(
|
|
3918
|
+
const capitalFBits = Array.from(F2, (v) => v & 255);
|
|
3471
3919
|
const encoded = [
|
|
3472
3920
|
encodeBitsMSB(fBits, FG_BITS),
|
|
3473
3921
|
encodeBitsMSB(gBits, FG_BITS),
|
|
@@ -3508,7 +3956,7 @@ function encodePublicKey(h) {
|
|
|
3508
3956
|
return out;
|
|
3509
3957
|
}
|
|
3510
3958
|
function generateKeyPair(seed) {
|
|
3511
|
-
if (seed !== void 0 && (!(0,
|
|
3959
|
+
if (seed !== void 0 && (!(0, import_utils10.isBytes)(seed) || seed.length !== SEED_LENGTH)) {
|
|
3512
3960
|
throw new Error(`Falcon512: seed must be a Uint8Array of ${SEED_LENGTH} bytes`);
|
|
3513
3961
|
}
|
|
3514
3962
|
return nobleEngine.keygen(seed);
|
|
@@ -3532,7 +3980,7 @@ function importFalconRsSecretKey(secretKey) {
|
|
|
3532
3980
|
const parts = [];
|
|
3533
3981
|
try {
|
|
3534
3982
|
const names = ["f", "g", "F", "G"];
|
|
3535
|
-
const [f, g,
|
|
3983
|
+
const [f, g, F2, G] = names.map((name, k) => {
|
|
3536
3984
|
const chunk = bytes.subarray(k * FALCON_RS_POLY_LENGTH, (k + 1) * FALCON_RS_POLY_LENGTH);
|
|
3537
3985
|
const decoded = decode14LSB(chunk);
|
|
3538
3986
|
parts.push(decoded);
|
|
@@ -3543,13 +3991,13 @@ function importFalconRsSecretKey(secretKey) {
|
|
|
3543
3991
|
parts.push(p);
|
|
3544
3992
|
return p;
|
|
3545
3993
|
});
|
|
3546
|
-
const recomputed = completeG(f, g,
|
|
3994
|
+
const recomputed = completeG(f, g, F2);
|
|
3547
3995
|
parts.push(recomputed);
|
|
3548
3996
|
if (recomputed.some((v, i) => v !== G[i])) {
|
|
3549
3997
|
throw new Error("Falcon512: invalid falcon-rs secret key (G does not match f, g, F)");
|
|
3550
3998
|
}
|
|
3551
|
-
checkNtruEquation({ f, g, F, G });
|
|
3552
|
-
return encodeSecretKey({ f, g, F });
|
|
3999
|
+
checkNtruEquation({ f, g, F: F2, G });
|
|
4000
|
+
return encodeSecretKey({ f, g, F: F2 });
|
|
3553
4001
|
} finally {
|
|
3554
4002
|
wipe(bytes, ...parts);
|
|
3555
4003
|
}
|
|
@@ -3967,10 +4415,241 @@ function verifyMessage(message, signature, fullPublicKey, accountAddressOrOption
|
|
|
3967
4415
|
const hashOptions = typeof accountAddressOrOptions === "object" && accountAddressOrOptions !== null && !Array.isArray(accountAddressOrOptions) ? accountAddressOrOptions : void 0;
|
|
3968
4416
|
return verify(signature, message, fullPublicKey, hashOptions);
|
|
3969
4417
|
}
|
|
4418
|
+
|
|
4419
|
+
// src/falcon/mlkem/index.ts
|
|
4420
|
+
var mlkem_exports = {};
|
|
4421
|
+
__export(mlkem_exports, {
|
|
4422
|
+
createKey: () => createKey,
|
|
4423
|
+
decapsulate: () => decapsulate,
|
|
4424
|
+
encapsulate: () => encapsulate
|
|
4425
|
+
});
|
|
4426
|
+
|
|
4427
|
+
// src/falcon/mlkem/exchange.ts
|
|
4428
|
+
var import_hkdf = require("@noble/hashes/hkdf.js");
|
|
4429
|
+
var import_sha2 = require("@noble/hashes/sha2.js");
|
|
4430
|
+
var import_utils12 = require("@noble/hashes/utils.js");
|
|
4431
|
+
var starknet13 = __toESM(require("starknet"));
|
|
4432
|
+
|
|
4433
|
+
// src/falcon/mlkem/messages.ts
|
|
4434
|
+
var starknet10 = __toESM(require("starknet"));
|
|
4435
|
+
var DOMAIN_NAME = "ML-KEM key exchange";
|
|
4436
|
+
var DOMAIN_VERSION = "1";
|
|
4437
|
+
var ALGORITHM = "ML-KEM-768";
|
|
4438
|
+
function messageDomain(chainId) {
|
|
4439
|
+
return {
|
|
4440
|
+
type: [
|
|
4441
|
+
{ name: "name", type: "shortstring" },
|
|
4442
|
+
{ name: "version", type: "shortstring" },
|
|
4443
|
+
{ name: "chainId", type: "shortstring" },
|
|
4444
|
+
{ name: "revision", type: "shortstring" }
|
|
4445
|
+
],
|
|
4446
|
+
domain: {
|
|
4447
|
+
name: DOMAIN_NAME,
|
|
4448
|
+
version: DOMAIN_VERSION,
|
|
4449
|
+
chainId,
|
|
4450
|
+
revision: starknet10.TypedDataRevision.ACTIVE
|
|
4451
|
+
}
|
|
4452
|
+
};
|
|
4453
|
+
}
|
|
4454
|
+
function publicKeyMessage(chainId, keyHash, validUntil) {
|
|
4455
|
+
const { type, domain } = messageDomain(chainId);
|
|
4456
|
+
return {
|
|
4457
|
+
types: {
|
|
4458
|
+
StarknetDomain: type,
|
|
4459
|
+
MlKemPublicKey: [
|
|
4460
|
+
{ name: "Algorithm", type: "shortstring" },
|
|
4461
|
+
{ name: "Key hash", type: "felt" },
|
|
4462
|
+
{ name: "Valid until", type: "timestamp" }
|
|
4463
|
+
]
|
|
4464
|
+
},
|
|
4465
|
+
primaryType: "MlKemPublicKey",
|
|
4466
|
+
domain,
|
|
4467
|
+
message: { Algorithm: ALGORITHM, "Key hash": keyHash, "Valid until": validUntil }
|
|
4468
|
+
};
|
|
4469
|
+
}
|
|
4470
|
+
function capsuleMessage(chainId, keyOwnerAddress, keyHash, capsuleHash, timestamp) {
|
|
4471
|
+
const { type, domain } = messageDomain(chainId);
|
|
4472
|
+
return {
|
|
4473
|
+
types: {
|
|
4474
|
+
StarknetDomain: type,
|
|
4475
|
+
MlKemCapsule: [
|
|
4476
|
+
{ name: "Key owner", type: "ContractAddress" },
|
|
4477
|
+
{ name: "Key hash", type: "felt" },
|
|
4478
|
+
{ name: "Capsule hash", type: "felt" },
|
|
4479
|
+
{ name: "Timestamp", type: "timestamp" }
|
|
4480
|
+
]
|
|
4481
|
+
},
|
|
4482
|
+
primaryType: "MlKemCapsule",
|
|
4483
|
+
domain,
|
|
4484
|
+
message: {
|
|
4485
|
+
"Key owner": starknet10.num.toHex(keyOwnerAddress),
|
|
4486
|
+
"Key hash": keyHash,
|
|
4487
|
+
"Capsule hash": capsuleHash,
|
|
4488
|
+
Timestamp: timestamp
|
|
4489
|
+
}
|
|
4490
|
+
};
|
|
4491
|
+
}
|
|
4492
|
+
|
|
4493
|
+
// src/falcon/mlkem/signatures.ts
|
|
4494
|
+
var starknet11 = __toESM(require("starknet"));
|
|
4495
|
+
async function checkSignature(provider, typedData3, signature, accountAddress) {
|
|
4496
|
+
const address = starknet11.num.toHex(parseFelt(accountAddress, "ML-KEM account address"));
|
|
4497
|
+
let answer;
|
|
4498
|
+
try {
|
|
4499
|
+
answer = await provider.callContract({
|
|
4500
|
+
contractAddress: address,
|
|
4501
|
+
entrypoint: "get_public_key"
|
|
4502
|
+
});
|
|
4503
|
+
} catch (error) {
|
|
4504
|
+
throw new Error(
|
|
4505
|
+
`ML-KEM: cannot read the public key of the account ${address}. The account must be deployed, and must be a Falcon-512 account of OpenZeppelin.`,
|
|
4506
|
+
{ cause: error }
|
|
4507
|
+
);
|
|
4508
|
+
}
|
|
4509
|
+
if (answer.length !== PACKED_SLOTS + 1 || BigInt(answer[0]) !== BigInt(PACKED_SLOTS)) {
|
|
4510
|
+
throw new Error(`ML-KEM: the account ${address} is not a Falcon-512 account of OpenZeppelin.`);
|
|
4511
|
+
}
|
|
4512
|
+
const length = Array.isArray(signature) ? signature.length : 0;
|
|
4513
|
+
let accountType;
|
|
4514
|
+
if (length === 60) {
|
|
4515
|
+
accountType = "oz-hint";
|
|
4516
|
+
} else if (length === 31) {
|
|
4517
|
+
accountType = "oz-direct";
|
|
4518
|
+
} else {
|
|
4519
|
+
throw new Error(
|
|
4520
|
+
`ML-KEM: the signature of the account ${address} is not a Falcon-512 signature.`
|
|
4521
|
+
);
|
|
4522
|
+
}
|
|
4523
|
+
if (!verifyMessage(typedData3, signature, answer.slice(1), address, { accountType })) {
|
|
4524
|
+
throw new Error(`ML-KEM: the signature of the account ${address} is not valid.`);
|
|
4525
|
+
}
|
|
4526
|
+
}
|
|
4527
|
+
|
|
4528
|
+
// src/falcon/mlkem/utils/bytes.ts
|
|
4529
|
+
var import_utils11 = require("@noble/hashes/utils.js");
|
|
4530
|
+
var starknet12 = __toESM(require("starknet"));
|
|
4531
|
+
function checkBytes(value, size, name) {
|
|
4532
|
+
if (!(0, import_utils11.isBytes)(value) || value.length !== size) {
|
|
4533
|
+
throw new Error(`ML-KEM: the ${name} must be a Uint8Array of ${size} bytes.`);
|
|
4534
|
+
}
|
|
4535
|
+
return value;
|
|
4536
|
+
}
|
|
4537
|
+
function hashBytes(bytes) {
|
|
4538
|
+
const groupSize = starknet12.constants.TEXT_TO_FELT_MAX_LEN;
|
|
4539
|
+
const felts = [];
|
|
4540
|
+
for (let start = 0; start < bytes.length; start += groupSize) {
|
|
4541
|
+
const group = bytes.subarray(start, start + groupSize);
|
|
4542
|
+
felts.push(starknet12.encode.addHexPrefix(starknet12.encode.buf2hex(group)));
|
|
4543
|
+
}
|
|
4544
|
+
return starknet12.hash.computePoseidonHashOnElements(felts);
|
|
4545
|
+
}
|
|
4546
|
+
|
|
4547
|
+
// src/falcon/mlkem/utils/time.ts
|
|
4548
|
+
var MAX_TIME = 4294967295;
|
|
4549
|
+
function nowInSeconds() {
|
|
4550
|
+
return Math.floor(Date.now() / 1e3);
|
|
4551
|
+
}
|
|
4552
|
+
function checkTime(value, name) {
|
|
4553
|
+
if (typeof value !== "number" || !Number.isSafeInteger(value) || value < 0 || value > MAX_TIME) {
|
|
4554
|
+
throw new Error(
|
|
4555
|
+
`ML-KEM: ${name} must be a time in seconds, from 0 to ${MAX_TIME}. Note: Date.now() gives milliseconds, so divide it by 1000.`
|
|
4556
|
+
);
|
|
4557
|
+
}
|
|
4558
|
+
return value;
|
|
4559
|
+
}
|
|
4560
|
+
|
|
4561
|
+
// src/falcon/mlkem/exchange.ts
|
|
4562
|
+
var PUBLIC_KEY_SIZE = 1184;
|
|
4563
|
+
var CAPSULE_SIZE = 1088;
|
|
4564
|
+
var SEED_SIZE = 64;
|
|
4565
|
+
var SHARED_SECRET_SIZE = 32;
|
|
4566
|
+
function finalSecret(mlKemSecret, context) {
|
|
4567
|
+
const contextHash = starknet13.hash.computePoseidonHashOnElements([
|
|
4568
|
+
starknet13.CairoBytes31.fromText(DOMAIN_NAME).toBigInt(),
|
|
4569
|
+
starknet13.CairoBytes31.fromText(DOMAIN_VERSION).toBigInt(),
|
|
4570
|
+
context.chainId,
|
|
4571
|
+
context.keyOwnerAddress,
|
|
4572
|
+
context.senderAddress,
|
|
4573
|
+
context.keyHash,
|
|
4574
|
+
context.capsuleHash
|
|
4575
|
+
]);
|
|
4576
|
+
const info = starknet13.num.hexToBytes(starknet13.num.toHex64(contextHash));
|
|
4577
|
+
return (0, import_hkdf.hkdf)(import_sha2.sha256, mlKemSecret, void 0, info, SHARED_SECRET_SIZE);
|
|
4578
|
+
}
|
|
4579
|
+
function createKey(chainId, validUntil) {
|
|
4580
|
+
if (typeof chainId !== "string" || chainId === "") {
|
|
4581
|
+
throw new Error("ML-KEM: chainId must be the chain id, as provider.getChainId() returns it.");
|
|
4582
|
+
}
|
|
4583
|
+
checkTime(validUntil, "validUntil");
|
|
4584
|
+
if (validUntil <= nowInSeconds()) throw new Error("ML-KEM: validUntil must be in the future.");
|
|
4585
|
+
const seed = (0, import_utils12.randomBytes)(SEED_SIZE);
|
|
4586
|
+
const { publicKey, secretKey } = ml_kem768.keygen(seed);
|
|
4587
|
+
secretKey.fill(0);
|
|
4588
|
+
const typedData3 = publicKeyMessage(chainId, hashBytes(publicKey), validUntil);
|
|
4589
|
+
return { seed, publicKey, typedData: typedData3 };
|
|
4590
|
+
}
|
|
4591
|
+
async function encapsulate(provider, signedKey, senderAddress) {
|
|
4592
|
+
checkBytes(signedKey.publicKey, PUBLIC_KEY_SIZE, "public key");
|
|
4593
|
+
checkTime(signedKey.validUntil, "validUntil");
|
|
4594
|
+
const aliceAddress = parseFelt(signedKey.keyOwnerAddress, "ML-KEM key owner address");
|
|
4595
|
+
const bobAddress = parseFelt(senderAddress, "ML-KEM sender address");
|
|
4596
|
+
if (signedKey.validUntil <= nowInSeconds()) {
|
|
4597
|
+
const owner = starknet13.num.toHex(aliceAddress);
|
|
4598
|
+
throw new Error(`ML-KEM: the key of the account ${owner} has expired.`);
|
|
4599
|
+
}
|
|
4600
|
+
const chainId = await provider.getChainId();
|
|
4601
|
+
const keyHash = hashBytes(signedKey.publicKey);
|
|
4602
|
+
const keyMessage = publicKeyMessage(chainId, keyHash, signedKey.validUntil);
|
|
4603
|
+
await checkSignature(provider, keyMessage, signedKey.signature, aliceAddress);
|
|
4604
|
+
const { cipherText: capsule, sharedSecret: mlKemSecret } = ml_kem768.encapsulate(
|
|
4605
|
+
signedKey.publicKey
|
|
4606
|
+
);
|
|
4607
|
+
const capsuleHash = hashBytes(capsule);
|
|
4608
|
+
const timestamp = nowInSeconds();
|
|
4609
|
+
const sharedSecret = finalSecret(mlKemSecret, {
|
|
4610
|
+
chainId,
|
|
4611
|
+
keyOwnerAddress: aliceAddress,
|
|
4612
|
+
senderAddress: bobAddress,
|
|
4613
|
+
keyHash,
|
|
4614
|
+
capsuleHash
|
|
4615
|
+
});
|
|
4616
|
+
mlKemSecret.fill(0);
|
|
4617
|
+
const typedData3 = capsuleMessage(chainId, aliceAddress, keyHash, capsuleHash, timestamp);
|
|
4618
|
+
return { sharedSecret, capsule, timestamp, typedData: typedData3 };
|
|
4619
|
+
}
|
|
4620
|
+
async function decapsulate(provider, signedCapsule, keyOwnerAddress, seed) {
|
|
4621
|
+
checkBytes(signedCapsule.capsule, CAPSULE_SIZE, "capsule");
|
|
4622
|
+
checkTime(signedCapsule.timestamp, "timestamp");
|
|
4623
|
+
checkBytes(seed, SEED_SIZE, "seed");
|
|
4624
|
+
const aliceAddress = parseFelt(keyOwnerAddress, "ML-KEM key owner address");
|
|
4625
|
+
const bobAddress = parseFelt(signedCapsule.senderAddress, "ML-KEM sender address");
|
|
4626
|
+
const { publicKey, secretKey } = ml_kem768.keygen(seed);
|
|
4627
|
+
try {
|
|
4628
|
+
const chainId = await provider.getChainId();
|
|
4629
|
+
const keyHash = hashBytes(publicKey);
|
|
4630
|
+
const capsuleHash = hashBytes(signedCapsule.capsule);
|
|
4631
|
+
const { timestamp } = signedCapsule;
|
|
4632
|
+
const typedData3 = capsuleMessage(chainId, aliceAddress, keyHash, capsuleHash, timestamp);
|
|
4633
|
+
await checkSignature(provider, typedData3, signedCapsule.signature, bobAddress);
|
|
4634
|
+
const mlKemSecret = ml_kem768.decapsulate(signedCapsule.capsule, secretKey);
|
|
4635
|
+
const sharedSecret = finalSecret(mlKemSecret, {
|
|
4636
|
+
chainId,
|
|
4637
|
+
keyOwnerAddress: aliceAddress,
|
|
4638
|
+
senderAddress: bobAddress,
|
|
4639
|
+
keyHash,
|
|
4640
|
+
capsuleHash
|
|
4641
|
+
});
|
|
4642
|
+
mlKemSecret.fill(0);
|
|
4643
|
+
return sharedSecret;
|
|
4644
|
+
} finally {
|
|
4645
|
+
secretKey.fill(0);
|
|
4646
|
+
}
|
|
4647
|
+
}
|
|
3970
4648
|
// Annotate the CommonJS export names for ESM import in node:
|
|
3971
4649
|
0 && (module.exports = {
|
|
3972
4650
|
Falcon512Signer,
|
|
3973
|
-
falcon512
|
|
4651
|
+
falcon512,
|
|
4652
|
+
mlkem
|
|
3974
4653
|
});
|
|
3975
4654
|
/*! noble-post-quantum - MIT License (c) 2024 Paul Miller (paulmillr.com) */
|
|
3976
4655
|
//# sourceMappingURL=index.js.map
|