-
Notifications
You must be signed in to change notification settings - Fork 0
/
noble-ed25519.js
838 lines (833 loc) · 30.7 KB
/
noble-ed25519.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
typeof define === 'function' && define.amd ? define(['exports'], factory) :
(global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.nobleEd25519 = {}));
})(this, (function (exports) { 'use strict';
const nodeCrypto = {};
/*! noble-ed25519 - MIT License (c) 2019 Paul Miller (paulmillr.com) */
const _0n = BigInt(0);
const _1n = BigInt(1);
const _2n = BigInt(2);
const _255n = BigInt(255);
const CURVE_ORDER = _2n ** BigInt(252) + BigInt('27742317777372353535851937790883648493');
const CURVE = {
a: BigInt(-1),
d: BigInt('37095705934669439343138083508754565189542113879843219016388785533085940283555'),
P: _2n ** _255n - BigInt(19),
l: CURVE_ORDER,
n: CURVE_ORDER,
h: BigInt(8),
Gx: BigInt('15112221349535400772501151409588531511454012693041857206046113283949847762202'),
Gy: BigInt('46316835694926478169428394003475163141307993866256225615783033603165251855960'),
};
const MAX_256B = _2n ** BigInt(256);
const SQRT_M1 = BigInt('19681161376707505956807079304988542015446066515923890162744021073123829784752');
BigInt('6853475219497561581579357271197624642482790079785650197046958215289687604742');
const SQRT_AD_MINUS_ONE = BigInt('25063068953384623474111414158702152701244531502492656460079210482610430750235');
const INVSQRT_A_MINUS_D = BigInt('54469307008909316920995813868745141605393597292927456921205312896311721017578');
const ONE_MINUS_D_SQ = BigInt('1159843021668779879193775521855586647937357759715417654439879720876111806838');
const D_MINUS_ONE_SQ = BigInt('40440834346308536858101042469323190826248399146238708352240133220865137265952');
class ExtendedPoint {
constructor(x, y, z, t) {
this.x = x;
this.y = y;
this.z = z;
this.t = t;
}
static fromAffine(p) {
if (!(p instanceof Point)) {
throw new TypeError('ExtendedPoint#fromAffine: expected Point');
}
if (p.equals(Point.ZERO))
return ExtendedPoint.ZERO;
return new ExtendedPoint(p.x, p.y, _1n, mod(p.x * p.y));
}
static toAffineBatch(points) {
const toInv = invertBatch(points.map((p) => p.z));
return points.map((p, i) => p.toAffine(toInv[i]));
}
static normalizeZ(points) {
return this.toAffineBatch(points).map(this.fromAffine);
}
equals(other) {
assertExtPoint(other);
const { x: X1, y: Y1, z: Z1 } = this;
const { x: X2, y: Y2, z: Z2 } = other;
const X1Z2 = mod(X1 * Z2);
const X2Z1 = mod(X2 * Z1);
const Y1Z2 = mod(Y1 * Z2);
const Y2Z1 = mod(Y2 * Z1);
return X1Z2 === X2Z1 && Y1Z2 === Y2Z1;
}
negate() {
return new ExtendedPoint(mod(-this.x), this.y, this.z, mod(-this.t));
}
double() {
const { x: X1, y: Y1, z: Z1 } = this;
const { a } = CURVE;
const A = mod(X1 ** _2n);
const B = mod(Y1 ** _2n);
const C = mod(_2n * mod(Z1 ** _2n));
const D = mod(a * A);
const E = mod(mod((X1 + Y1) ** _2n) - A - B);
const G = D + B;
const F = G - C;
const H = D - B;
const X3 = mod(E * F);
const Y3 = mod(G * H);
const T3 = mod(E * H);
const Z3 = mod(F * G);
return new ExtendedPoint(X3, Y3, Z3, T3);
}
add(other) {
assertExtPoint(other);
const { x: X1, y: Y1, z: Z1, t: T1 } = this;
const { x: X2, y: Y2, z: Z2, t: T2 } = other;
const A = mod((Y1 - X1) * (Y2 + X2));
const B = mod((Y1 + X1) * (Y2 - X2));
const F = mod(B - A);
if (F === _0n)
return this.double();
const C = mod(Z1 * _2n * T2);
const D = mod(T1 * _2n * Z2);
const E = D + C;
const G = B + A;
const H = D - C;
const X3 = mod(E * F);
const Y3 = mod(G * H);
const T3 = mod(E * H);
const Z3 = mod(F * G);
return new ExtendedPoint(X3, Y3, Z3, T3);
}
subtract(other) {
return this.add(other.negate());
}
precomputeWindow(W) {
const windows = 1 + 256 / W;
const points = [];
let p = this;
let base = p;
for (let window = 0; window < windows; window++) {
base = p;
points.push(base);
for (let i = 1; i < 2 ** (W - 1); i++) {
base = base.add(p);
points.push(base);
}
p = base.double();
}
return points;
}
wNAF(n, affinePoint) {
if (!affinePoint && this.equals(ExtendedPoint.BASE))
affinePoint = Point.BASE;
const W = (affinePoint && affinePoint._WINDOW_SIZE) || 1;
if (256 % W) {
throw new Error('Point#wNAF: Invalid precomputation window, must be power of 2');
}
let precomputes = affinePoint && pointPrecomputes.get(affinePoint);
if (!precomputes) {
precomputes = this.precomputeWindow(W);
if (affinePoint && W !== 1) {
precomputes = ExtendedPoint.normalizeZ(precomputes);
pointPrecomputes.set(affinePoint, precomputes);
}
}
let p = ExtendedPoint.ZERO;
let f = ExtendedPoint.ZERO;
const windows = 1 + 256 / W;
const windowSize = 2 ** (W - 1);
const mask = BigInt(2 ** W - 1);
const maxNumber = 2 ** W;
const shiftBy = BigInt(W);
for (let window = 0; window < windows; window++) {
const offset = window * windowSize;
let wbits = Number(n & mask);
n >>= shiftBy;
if (wbits > windowSize) {
wbits -= maxNumber;
n += _1n;
}
if (wbits === 0) {
let pr = precomputes[offset];
if (window % 2)
pr = pr.negate();
f = f.add(pr);
}
else {
let cached = precomputes[offset + Math.abs(wbits) - 1];
if (wbits < 0)
cached = cached.negate();
p = p.add(cached);
}
}
return ExtendedPoint.normalizeZ([p, f])[0];
}
multiply(scalar, affinePoint) {
return this.wNAF(normalizeScalar(scalar, CURVE.l), affinePoint);
}
multiplyUnsafe(scalar) {
let n = normalizeScalar(scalar, CURVE.l, false);
const G = ExtendedPoint.BASE;
const P0 = ExtendedPoint.ZERO;
if (n === _0n)
return P0;
if (this.equals(P0) || n === _1n)
return this;
if (this.equals(G))
return this.wNAF(n);
let p = P0;
let d = this;
while (n > _0n) {
if (n & _1n)
p = p.add(d);
d = d.double();
n >>= _1n;
}
return p;
}
isSmallOrder() {
return this.multiplyUnsafe(CURVE.h).equals(ExtendedPoint.ZERO);
}
isTorsionFree() {
return this.multiplyUnsafe(CURVE.l).equals(ExtendedPoint.ZERO);
}
toAffine(invZ = invert(this.z)) {
const { x, y, z } = this;
const ax = mod(x * invZ);
const ay = mod(y * invZ);
const zz = mod(z * invZ);
if (zz !== _1n)
throw new Error('invZ was invalid');
return new Point(ax, ay);
}
fromRistrettoBytes() {
legacyRist();
}
toRistrettoBytes() {
legacyRist();
}
fromRistrettoHash() {
legacyRist();
}
}
ExtendedPoint.BASE = new ExtendedPoint(CURVE.Gx, CURVE.Gy, _1n, mod(CURVE.Gx * CURVE.Gy));
ExtendedPoint.ZERO = new ExtendedPoint(_0n, _1n, _1n, _0n);
function assertExtPoint(other) {
if (!(other instanceof ExtendedPoint))
throw new TypeError('ExtendedPoint expected');
}
function assertRstPoint(other) {
if (!(other instanceof RistrettoPoint))
throw new TypeError('RistrettoPoint expected');
}
function legacyRist() {
throw new Error('Legacy method: switch to RistrettoPoint');
}
class RistrettoPoint {
constructor(ep) {
this.ep = ep;
}
static calcElligatorRistrettoMap(r0) {
const { d } = CURVE;
const r = mod(SQRT_M1 * r0 * r0);
const Ns = mod((r + _1n) * ONE_MINUS_D_SQ);
let c = BigInt(-1);
const D = mod((c - d * r) * mod(r + d));
let { isValid: Ns_D_is_sq, value: s } = uvRatio(Ns, D);
let s_ = mod(s * r0);
if (!edIsNegative(s_))
s_ = mod(-s_);
if (!Ns_D_is_sq)
s = s_;
if (!Ns_D_is_sq)
c = r;
const Nt = mod(c * (r - _1n) * D_MINUS_ONE_SQ - D);
const s2 = s * s;
const W0 = mod((s + s) * D);
const W1 = mod(Nt * SQRT_AD_MINUS_ONE);
const W2 = mod(_1n - s2);
const W3 = mod(_1n + s2);
return new ExtendedPoint(mod(W0 * W3), mod(W2 * W1), mod(W1 * W3), mod(W0 * W2));
}
static hashToCurve(hex) {
hex = ensureBytes(hex, 64);
const r1 = bytes255ToNumberLE(hex.slice(0, 32));
const R1 = this.calcElligatorRistrettoMap(r1);
const r2 = bytes255ToNumberLE(hex.slice(32, 64));
const R2 = this.calcElligatorRistrettoMap(r2);
return new RistrettoPoint(R1.add(R2));
}
static fromHex(hex) {
hex = ensureBytes(hex, 32);
const { a, d } = CURVE;
const emsg = 'RistrettoPoint.fromHex: the hex is not valid encoding of RistrettoPoint';
const s = bytes255ToNumberLE(hex);
if (!equalBytes(numberTo32BytesLE(s), hex) || edIsNegative(s))
throw new Error(emsg);
const s2 = mod(s * s);
const u1 = mod(_1n + a * s2);
const u2 = mod(_1n - a * s2);
const u1_2 = mod(u1 * u1);
const u2_2 = mod(u2 * u2);
const v = mod(a * d * u1_2 - u2_2);
const { isValid, value: I } = invertSqrt(mod(v * u2_2));
const Dx = mod(I * u2);
const Dy = mod(I * Dx * v);
let x = mod((s + s) * Dx);
if (edIsNegative(x))
x = mod(-x);
const y = mod(u1 * Dy);
const t = mod(x * y);
if (!isValid || edIsNegative(t) || y === _0n)
throw new Error(emsg);
return new RistrettoPoint(new ExtendedPoint(x, y, _1n, t));
}
toRawBytes() {
let { x, y, z, t } = this.ep;
const u1 = mod(mod(z + y) * mod(z - y));
const u2 = mod(x * y);
const { value: invsqrt } = invertSqrt(mod(u1 * u2 ** _2n));
const D1 = mod(invsqrt * u1);
const D2 = mod(invsqrt * u2);
const zInv = mod(D1 * D2 * t);
let D;
if (edIsNegative(t * zInv)) {
let _x = mod(y * SQRT_M1);
let _y = mod(x * SQRT_M1);
x = _x;
y = _y;
D = mod(D1 * INVSQRT_A_MINUS_D);
}
else {
D = D2;
}
if (edIsNegative(x * zInv))
y = mod(-y);
let s = mod((z - y) * D);
if (edIsNegative(s))
s = mod(-s);
return numberTo32BytesLE(s);
}
toHex() {
return bytesToHex(this.toRawBytes());
}
toString() {
return this.toHex();
}
equals(other) {
assertRstPoint(other);
const a = this.ep;
const b = other.ep;
const one = mod(a.x * b.y) === mod(a.y * b.x);
const two = mod(a.y * b.y) === mod(a.x * b.x);
return one || two;
}
add(other) {
assertRstPoint(other);
return new RistrettoPoint(this.ep.add(other.ep));
}
subtract(other) {
assertRstPoint(other);
return new RistrettoPoint(this.ep.subtract(other.ep));
}
multiply(scalar) {
return new RistrettoPoint(this.ep.multiply(scalar));
}
multiplyUnsafe(scalar) {
return new RistrettoPoint(this.ep.multiplyUnsafe(scalar));
}
}
RistrettoPoint.BASE = new RistrettoPoint(ExtendedPoint.BASE);
RistrettoPoint.ZERO = new RistrettoPoint(ExtendedPoint.ZERO);
const pointPrecomputes = new WeakMap();
class Point {
constructor(x, y) {
this.x = x;
this.y = y;
}
_setWindowSize(windowSize) {
this._WINDOW_SIZE = windowSize;
pointPrecomputes.delete(this);
}
static fromHex(hex, strict = true) {
const { d, P } = CURVE;
hex = ensureBytes(hex, 32);
const normed = hex.slice();
normed[31] = hex[31] & ~0x80;
const y = bytesToNumberLE(normed);
if (strict && y >= P)
throw new Error('Expected 0 < hex < P');
if (!strict && y >= MAX_256B)
throw new Error('Expected 0 < hex < 2**256');
const y2 = mod(y * y);
const u = mod(y2 - _1n);
const v = mod(d * y2 + _1n);
let { isValid, value: x } = uvRatio(u, v);
if (!isValid)
throw new Error('Point.fromHex: invalid y coordinate');
const isXOdd = (x & _1n) === _1n;
const isLastByteOdd = (hex[31] & 0x80) !== 0;
if (isLastByteOdd !== isXOdd) {
x = mod(-x);
}
return new Point(x, y);
}
static async fromPrivateKey(privateKey) {
return (await getExtendedPublicKey(privateKey)).point;
}
toRawBytes() {
const bytes = numberTo32BytesLE(this.y);
bytes[31] |= this.x & _1n ? 0x80 : 0;
return bytes;
}
toHex() {
return bytesToHex(this.toRawBytes());
}
toX25519() {
const { y } = this;
const u = mod((_1n + y) * invert(_1n - y));
return numberTo32BytesLE(u);
}
isTorsionFree() {
return ExtendedPoint.fromAffine(this).isTorsionFree();
}
equals(other) {
return this.x === other.x && this.y === other.y;
}
negate() {
return new Point(mod(-this.x), this.y);
}
add(other) {
return ExtendedPoint.fromAffine(this).add(ExtendedPoint.fromAffine(other)).toAffine();
}
subtract(other) {
return this.add(other.negate());
}
multiply(scalar) {
return ExtendedPoint.fromAffine(this).multiply(scalar, this).toAffine();
}
}
Point.BASE = new Point(CURVE.Gx, CURVE.Gy);
Point.ZERO = new Point(_0n, _1n);
class Signature {
constructor(r, s) {
this.r = r;
this.s = s;
this.assertValidity();
}
static fromHex(hex) {
const bytes = ensureBytes(hex, 64);
const r = Point.fromHex(bytes.slice(0, 32), false);
const s = bytesToNumberLE(bytes.slice(32, 64));
return new Signature(r, s);
}
assertValidity() {
const { r, s } = this;
if (!(r instanceof Point))
throw new Error('Expected Point instance');
normalizeScalar(s, CURVE.l, false);
return this;
}
toRawBytes() {
const u8 = new Uint8Array(64);
u8.set(this.r.toRawBytes());
u8.set(numberTo32BytesLE(this.s), 32);
return u8;
}
toHex() {
return bytesToHex(this.toRawBytes());
}
}
function concatBytes(...arrays) {
if (!arrays.every((a) => a instanceof Uint8Array))
throw new Error('Expected Uint8Array list');
if (arrays.length === 1)
return arrays[0];
const length = arrays.reduce((a, arr) => a + arr.length, 0);
const result = new Uint8Array(length);
for (let i = 0, pad = 0; i < arrays.length; i++) {
const arr = arrays[i];
result.set(arr, pad);
pad += arr.length;
}
return result;
}
const hexes = Array.from({ length: 256 }, (v, i) => i.toString(16).padStart(2, '0'));
function bytesToHex(uint8a) {
if (!(uint8a instanceof Uint8Array))
throw new Error('Uint8Array expected');
let hex = '';
for (let i = 0; i < uint8a.length; i++) {
hex += hexes[uint8a[i]];
}
return hex;
}
function hexToBytes(hex) {
if (typeof hex !== 'string') {
throw new TypeError('hexToBytes: expected string, got ' + typeof hex);
}
if (hex.length % 2)
throw new Error('hexToBytes: received invalid unpadded hex');
const array = new Uint8Array(hex.length / 2);
for (let i = 0; i < array.length; i++) {
const j = i * 2;
const hexByte = hex.slice(j, j + 2);
const byte = Number.parseInt(hexByte, 16);
if (Number.isNaN(byte) || byte < 0)
throw new Error('Invalid byte sequence');
array[i] = byte;
}
return array;
}
function numberTo32BytesBE(num) {
const length = 32;
const hex = num.toString(16).padStart(length * 2, '0');
return hexToBytes(hex);
}
function numberTo32BytesLE(num) {
return numberTo32BytesBE(num).reverse();
}
function edIsNegative(num) {
return (mod(num) & _1n) === _1n;
}
function bytesToNumberLE(uint8a) {
if (!(uint8a instanceof Uint8Array))
throw new Error('Expected Uint8Array');
return BigInt('0x' + bytesToHex(Uint8Array.from(uint8a).reverse()));
}
function bytes255ToNumberLE(bytes) {
return mod(bytesToNumberLE(bytes) & (_2n ** _255n - _1n));
}
function mod(a, b = CURVE.P) {
const res = a % b;
return res >= _0n ? res : b + res;
}
function invert(number, modulo = CURVE.P) {
if (number === _0n || modulo <= _0n) {
throw new Error(`invert: expected positive integers, got n=${number} mod=${modulo}`);
}
let a = mod(number, modulo);
let b = modulo;
let x = _0n, u = _1n;
while (a !== _0n) {
const q = b / a;
const r = b % a;
const m = x - u * q;
b = a, a = r, x = u, u = m;
}
const gcd = b;
if (gcd !== _1n)
throw new Error('invert: does not exist');
return mod(x, modulo);
}
function invertBatch(nums, p = CURVE.P) {
const tmp = new Array(nums.length);
const lastMultiplied = nums.reduce((acc, num, i) => {
if (num === _0n)
return acc;
tmp[i] = acc;
return mod(acc * num, p);
}, _1n);
const inverted = invert(lastMultiplied, p);
nums.reduceRight((acc, num, i) => {
if (num === _0n)
return acc;
tmp[i] = mod(acc * tmp[i], p);
return mod(acc * num, p);
}, inverted);
return tmp;
}
function pow2(x, power) {
const { P } = CURVE;
let res = x;
while (power-- > _0n) {
res *= res;
res %= P;
}
return res;
}
function pow_2_252_3(x) {
const { P } = CURVE;
const _5n = BigInt(5);
const _10n = BigInt(10);
const _20n = BigInt(20);
const _40n = BigInt(40);
const _80n = BigInt(80);
const x2 = (x * x) % P;
const b2 = (x2 * x) % P;
const b4 = (pow2(b2, _2n) * b2) % P;
const b5 = (pow2(b4, _1n) * x) % P;
const b10 = (pow2(b5, _5n) * b5) % P;
const b20 = (pow2(b10, _10n) * b10) % P;
const b40 = (pow2(b20, _20n) * b20) % P;
const b80 = (pow2(b40, _40n) * b40) % P;
const b160 = (pow2(b80, _80n) * b80) % P;
const b240 = (pow2(b160, _80n) * b80) % P;
const b250 = (pow2(b240, _10n) * b10) % P;
const pow_p_5_8 = (pow2(b250, _2n) * x) % P;
return { pow_p_5_8, b2 };
}
function uvRatio(u, v) {
const v3 = mod(v * v * v);
const v7 = mod(v3 * v3 * v);
const pow = pow_2_252_3(u * v7).pow_p_5_8;
let x = mod(u * v3 * pow);
const vx2 = mod(v * x * x);
const root1 = x;
const root2 = mod(x * SQRT_M1);
const useRoot1 = vx2 === u;
const useRoot2 = vx2 === mod(-u);
const noRoot = vx2 === mod(-u * SQRT_M1);
if (useRoot1)
x = root1;
if (useRoot2 || noRoot)
x = root2;
if (edIsNegative(x))
x = mod(-x);
return { isValid: useRoot1 || useRoot2, value: x };
}
function invertSqrt(number) {
return uvRatio(_1n, number);
}
async function sha512ModqLE(...args) {
const hash = await utils.sha512(concatBytes(...args));
const value = bytesToNumberLE(hash);
return mod(value, CURVE.l);
}
function equalBytes(b1, b2) {
if (b1.length !== b2.length) {
return false;
}
for (let i = 0; i < b1.length; i++) {
if (b1[i] !== b2[i]) {
return false;
}
}
return true;
}
function ensureBytes(hex, expectedLength) {
const bytes = hex instanceof Uint8Array ? Uint8Array.from(hex) : hexToBytes(hex);
if (typeof expectedLength === 'number' && bytes.length !== expectedLength)
throw new Error(`Expected ${expectedLength} bytes`);
return bytes;
}
function normalizeScalar(num, max, strict = true) {
if (!max)
throw new TypeError('Specify max value');
if (typeof num === 'number' && Number.isSafeInteger(num))
num = BigInt(num);
if (typeof num === 'bigint' && num < max) {
if (strict) {
if (_0n < num)
return num;
}
else {
if (_0n <= num)
return num;
}
}
throw new TypeError('Expected valid scalar: 0 < scalar < max');
}
function adjustBytes25519(bytes) {
bytes[0] &= 248;
bytes[31] &= 127;
bytes[31] |= 64;
return bytes;
}
function decodeScalar25519(n) {
return bytesToNumberLE(adjustBytes25519(ensureBytes(n, 32)));
}
async function getExtendedPublicKey(key) {
key =
typeof key === 'bigint' || typeof key === 'number'
? numberTo32BytesBE(normalizeScalar(key, MAX_256B))
: ensureBytes(key);
if (key.length !== 32)
throw new Error(`Expected 32 bytes`);
const hashed = await utils.sha512(key);
const head = adjustBytes25519(hashed.slice(0, 32));
const prefix = hashed.slice(32, 64);
const scalar = mod(bytesToNumberLE(head), CURVE.l);
const point = Point.BASE.multiply(scalar);
const pointBytes = point.toRawBytes();
return { head, prefix, scalar, point, pointBytes };
}
async function getPublicKey(privateKey) {
return (await getExtendedPublicKey(privateKey)).pointBytes;
}
async function sign(message, privateKey) {
message = ensureBytes(message);
const { prefix, scalar, pointBytes } = await getExtendedPublicKey(privateKey);
const r = await sha512ModqLE(prefix, message);
const R = Point.BASE.multiply(r);
const k = await sha512ModqLE(R.toRawBytes(), pointBytes, message);
const s = mod(r + k * scalar, CURVE.l);
return new Signature(R, s).toRawBytes();
}
async function verify(sig, message, publicKey) {
message = ensureBytes(message);
if (!(publicKey instanceof Point))
publicKey = Point.fromHex(publicKey, false);
const { r, s } = sig instanceof Signature ? sig.assertValidity() : Signature.fromHex(sig);
const SB = ExtendedPoint.BASE.multiplyUnsafe(s);
const k = await sha512ModqLE(r.toRawBytes(), publicKey.toRawBytes(), message);
const kA = ExtendedPoint.fromAffine(publicKey).multiplyUnsafe(k);
const RkA = ExtendedPoint.fromAffine(r).add(kA);
return RkA.subtract(SB).multiplyUnsafe(CURVE.h).equals(ExtendedPoint.ZERO);
}
async function getSharedSecret(privateKey, publicKey) {
const { head } = await getExtendedPublicKey(privateKey);
const u = Point.fromHex(publicKey).toX25519();
return curve25519.scalarMult(head, u);
}
Point.BASE._setWindowSize(8);
function cswap(swap, x_2, x_3) {
const dummy = mod(swap * (x_2 - x_3));
x_2 = mod(x_2 - dummy);
x_3 = mod(x_3 + dummy);
return [x_2, x_3];
}
function montgomeryLadder(pointU, scalar) {
const { P } = CURVE;
const u = normalizeScalar(pointU, P);
const k = normalizeScalar(scalar, P);
const a24 = BigInt(121665);
const x_1 = u;
let x_2 = _1n;
let z_2 = _0n;
let x_3 = u;
let z_3 = _1n;
let swap = _0n;
let sw;
for (let t = BigInt(255 - 1); t >= _0n; t--) {
const k_t = (k >> t) & _1n;
swap ^= k_t;
sw = cswap(swap, x_2, x_3);
x_2 = sw[0];
x_3 = sw[1];
sw = cswap(swap, z_2, z_3);
z_2 = sw[0];
z_3 = sw[1];
swap = k_t;
const A = x_2 + z_2;
const AA = mod(A * A);
const B = x_2 - z_2;
const BB = mod(B * B);
const E = AA - BB;
const C = x_3 + z_3;
const D = x_3 - z_3;
const DA = mod(D * A);
const CB = mod(C * B);
x_3 = mod((DA + CB) ** _2n);
z_3 = mod(x_1 * (DA - CB) ** _2n);
x_2 = mod(AA * BB);
z_2 = mod(E * (AA + mod(a24 * E)));
}
sw = cswap(swap, x_2, x_3);
x_2 = sw[0];
x_3 = sw[1];
sw = cswap(swap, z_2, z_3);
z_2 = sw[0];
z_3 = sw[1];
const { pow_p_5_8, b2 } = pow_2_252_3(z_2);
const xp2 = mod(pow2(pow_p_5_8, BigInt(3)) * b2);
return mod(x_2 * xp2);
}
function encodeUCoordinate(u) {
return numberTo32BytesLE(mod(u, CURVE.P));
}
function decodeUCoordinate(uEnc) {
const u = ensureBytes(uEnc, 32);
u[31] &= 127;
return bytesToNumberLE(u);
}
const curve25519 = {
BASE_POINT_U: '0900000000000000000000000000000000000000000000000000000000000000',
scalarMult(privateKey, publicKey) {
const u = decodeUCoordinate(publicKey);
const p = decodeScalar25519(privateKey);
const pu = montgomeryLadder(u, p);
if (pu === _0n)
throw new Error('Invalid private or public key received');
return encodeUCoordinate(pu);
},
scalarMultBase(privateKey) {
return curve25519.scalarMult(privateKey, curve25519.BASE_POINT_U);
},
};
const crypto = {
node: nodeCrypto,
web: typeof self === 'object' && 'crypto' in self ? self.crypto : undefined,
};
const utils = {
TORSION_SUBGROUP: [
'0100000000000000000000000000000000000000000000000000000000000000',
'c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac037a',
'0000000000000000000000000000000000000000000000000000000000000080',
'26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc05',
'ecffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f',
'26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc85',
'0000000000000000000000000000000000000000000000000000000000000000',
'c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac03fa',
],
bytesToHex,
getExtendedPublicKey,
mod,
invert,
hashToPrivateScalar: (hash) => {
hash = ensureBytes(hash);
if (hash.length < 40 || hash.length > 1024)
throw new Error('Expected 40-1024 bytes of private key as per FIPS 186');
const num = mod(bytesToNumberLE(hash), CURVE.l);
if (num === _0n || num === _1n)
throw new Error('Invalid private key');
return num;
},
randomBytes: (bytesLength = 32) => {
if (crypto.web) {
return crypto.web.getRandomValues(new Uint8Array(bytesLength));
}
else if (crypto.node) {
const { randomBytes } = crypto.node;
return new Uint8Array(randomBytes(bytesLength).buffer);
}
else {
throw new Error("The environment doesn't have randomBytes function");
}
},
randomPrivateKey: () => {
return utils.randomBytes(32);
},
sha512: async (message) => {
if (crypto.web) {
const buffer = await crypto.web.subtle.digest('SHA-512', message.buffer);
return new Uint8Array(buffer);
}
else if (crypto.node) {
return Uint8Array.from(crypto.node.createHash('sha512').update(message).digest());
}
else {
throw new Error("The environment doesn't have sha512 function");
}
},
precompute(windowSize = 8, point = Point.BASE) {
const cached = point.equals(Point.BASE) ? point : new Point(point.x, point.y);
cached._setWindowSize(windowSize);
cached.multiply(_2n);
return cached;
},
};
exports.CURVE = CURVE;
exports.ExtendedPoint = ExtendedPoint;
exports.Point = Point;
exports.RistrettoPoint = RistrettoPoint;
exports.Signature = Signature;
exports.curve25519 = curve25519;
exports.getPublicKey = getPublicKey;
exports.getSharedSecret = getSharedSecret;
exports.sign = sign;
exports.utils = utils;
exports.verify = verify;
Object.defineProperty(exports, '__esModule', { value: true });
}));