forked from paulmillr/noble-ed25519
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
823 lines (745 loc) · 28.3 KB
/
index.ts
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
/*! noble-ed25519 - MIT License (c) Paul Miller (paulmillr.com) */
// Thanks DJB https://ed25519.cr.yp.to
// https://tools.ietf.org/html/rfc8032, https://en.wikipedia.org/wiki/EdDSA
// Includes Ristretto https://ristretto.group
// Curve formula is −x² + y² = 1 − (121665/121666) * x² * y²
const CURVE = {
// Params: a, b
a: -1n,
// Equal to -121665/121666 over finite field.
// Negative number is P - number, and division is invert(number, P)
d: 37095705934669439343138083508754565189542113879843219016388785533085940283555n,
// Finite field 𝔽p over which we'll do calculations
P: 2n ** 255n - 19n,
// Subgroup order aka C
n: 2n ** 252n + 27742317777372353535851937790883648493n,
// Cofactor
h: 8n,
// Base point (x, y) aka generator point
Gx: 15112221349535400772501151409588531511454012693041857206046113283949847762202n,
Gy: 46316835694926478169428394003475163141307993866256225615783033603165251855960n,
};
// Cleaner output this way.
export { CURVE };
type Hex = Uint8Array | string;
type PrivKey = Hex | bigint | number;
type PubKey = Hex | Point;
type SigType = Hex | Signature;
const B32 = 32;
// √(-1) aka √(a) aka 2^((p-1)/4)
const SQRT_M1 = 19681161376707505956807079304988542015446066515923890162744021073123829784752n;
// √(ad - 1)
const SQRT_AD_MINUS_ONE =
25063068953384623474111414158702152701244531502492656460079210482610430750235n;
// 1 / √(a-d)
const INVSQRT_A_MINUS_D =
54469307008909316920995813868745141605393597292927456921205312896311721017578n;
// 1-d²
const ONE_MINUS_D_SQ =
1159843021668779879193775521855586647937357759715417654439879720876111806838n;
// (d-1)²
const D_MINUS_ONE_SQ =
40440834346308536858101042469323190826248399146238708352240133220865137265952n;
// Default Point works in default aka affine coordinates: (x, y)
// Extended Point works in extended coordinates: (x, y, z, t) ∋ (x=x/z, y=y/z, t=xy)
// https://en.wikipedia.org/wiki/Twisted_Edwards_curve#Extended_coordinates
class ExtendedPoint {
constructor(public x: bigint, public y: bigint, public z: bigint, public t: bigint) {}
static BASE = new ExtendedPoint(CURVE.Gx, CURVE.Gy, 1n, mod(CURVE.Gx * CURVE.Gy));
static ZERO = new ExtendedPoint(0n, 1n, 1n, 0n);
static fromAffine(p: Point): ExtendedPoint {
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));
}
// Takes a bunch of Jacobian Points but executes only one
// invert on all of them. invert is very slow operation,
// so this improves performance massively.
static toAffineBatch(points: ExtendedPoint[]): Point[] {
const toInv = invertBatch(points.map((p) => p.z));
return points.map((p, i) => p.toAffine(toInv[i]));
}
static normalizeZ(points: ExtendedPoint[]): ExtendedPoint[] {
return this.toAffineBatch(points).map(this.fromAffine);
}
// Ristretto-related methods.
// The hash-to-group operation applies Elligator twice and adds the results.
// https://ristretto.group/formulas/elligator.html
static fromRistrettoHash(hash: Uint8Array): ExtendedPoint {
const r1 = bytes255ToNumberLE(hash.slice(0, B32));
// const h = hash.slice(0, B32);
const R1 = this.calcElligatorRistrettoMap(r1);
const r2 = bytes255ToNumberLE(hash.slice(B32, B32 * 2));
const R2 = this.calcElligatorRistrettoMap(r2);
return R1.add(R2);
}
// Computes Elligator map for Ristretto
// https://ristretto.group/formulas/elligator.html
private static calcElligatorRistrettoMap(r0: bigint) {
const { d } = CURVE;
const r = mod(SQRT_M1 * r0 * r0); // 1
const Ns = mod((r + 1n) * ONE_MINUS_D_SQ); // 2
let c = -1n; // 3
const D = mod((c - d * r) * mod(r + d)); // 4
let { isValid: Ns_D_is_sq, value: s } = uvRatio(Ns, D); // 5
let s_ = mod(s * r0); // 6
if (!edIsNegative(s_)) s_ = mod(-s_);
if (!Ns_D_is_sq) s = s_; // 7
if (!Ns_D_is_sq) c = r; // 8
const Nt = mod(c * (r - 1n) * D_MINUS_ONE_SQ - D); // 9
const s2 = s * s;
const W0 = mod((s + s) * D); // 10
const W1 = mod(Nt * SQRT_AD_MINUS_ONE); // 11
const W2 = mod(1n - s2); // 12
const W3 = mod(1n + s2); // 13
return new ExtendedPoint(mod(W0 * W3), mod(W2 * W1), mod(W1 * W3), mod(W0 * W2));
}
// Ristretto: Decoding to Extended Coordinates
// https://ristretto.group/formulas/decoding.html
static fromRistrettoBytes(bytes: Uint8Array): ExtendedPoint {
const { a, d } = CURVE;
const emsg = 'ExtendedPoint.fromRistrettoBytes: Cannot convert bytes to Ristretto Point';
const s = bytes255ToNumberLE(bytes);
// 1. Check that s_bytes is the canonical encoding of a field element, or else abort.
// 3. Check that s is non-negative, or else abort
if (!equalBytes(numberToBytesPadded(s, B32), bytes) || edIsNegative(s)) throw new Error(emsg);
const s2 = mod(s * s);
const u1 = mod(1n + a * s2); // 4 (a is -1)
const u2 = mod(1n - a * s2); // 5
const u1_2 = mod(u1 * u1);
const u2_2 = mod(u2 * u2);
const v = mod(a * d * u1_2 - u2_2); // 6
const { isValid, value: I } = invertSqrt(mod(v * u2_2)); // 7
const Dx = mod(I * u2); // 8
const Dy = mod(I * Dx * v); // 9
let x = mod((s + s) * Dx); // 10
if (edIsNegative(x)) x = mod(-x); // 10
const y = mod(u1 * Dy); // 11
const t = mod(x * y); // 12
if (!isValid || edIsNegative(t) || y === 0n) throw new Error(emsg);
return new ExtendedPoint(x, y, 1n, t);
}
// Ristretto: Encoding from Extended Coordinates
// https://ristretto.group/formulas/encoding.html
toRistrettoBytes(): Uint8Array {
let { x, y, z, t } = this;
const u1 = mod(mod(z + y) * mod(z - y)); // 1
const u2 = mod(x * y); // 2
// Square root always exists
const { value: invsqrt } = invertSqrt(mod(u1 * u2 ** 2n)); // 3
const D1 = mod(invsqrt * u1); // 4
const D2 = mod(invsqrt * u2); // 5
const zInv = mod(D1 * D2 * t); // 6
let D: bigint; // 7
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; // 8
}
if (edIsNegative(x * zInv)) y = mod(-y); // 9
let s = mod((z - y) * D); // 10 (check footer's note, no sqrt(-a))
if (edIsNegative(s)) s = mod(-s);
return numberToBytesPadded(s, B32); // 11
}
// Ristretto methods end.
// Compare one point to another.
equals(other: ExtendedPoint): boolean {
const a = this;
const b = other;
return mod(a.t * b.z) === mod(b.t * a.z);
}
// Inverses point to one corresponding to (x, -y) in Affine coordinates.
negate(): ExtendedPoint {
return new ExtendedPoint(mod(-this.x), this.y, this.z, mod(-this.t));
}
// Fast algo for doubling Extended Point when curve's a=-1.
// http://hyperelliptic.org/EFD/g1p/auto-twisted-extended-1.html#doubling-dbl-2008-hwcd
// Cost: 3M + 4S + 1*a + 7add + 1*2.
double(): ExtendedPoint {
const X1 = this.x;
const Y1 = this.y;
const Z1 = this.z;
const { a } = CURVE;
const A = mod(X1 ** 2n);
const B = mod(Y1 ** 2n);
const C = mod(2n * Z1 ** 2n);
const D = mod(a * A);
const E = mod((X1 + Y1) ** 2n - A - B);
const G = mod(D + B);
const F = mod(G - C);
const H = mod(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);
}
// Fast algo for adding 2 Extended Points when curve's a=-1.
// http://hyperelliptic.org/EFD/g1p/auto-twisted-extended-1.html#addition-add-2008-hwcd-4
// Cost: 8M + 8add + 2*2.
add(other: ExtendedPoint): ExtendedPoint {
const X1 = this.x;
const Y1 = this.y;
const Z1 = this.z;
const T1 = this.t;
const X2 = other.x;
const Y2 = other.y;
const Z2 = other.z;
const T2 = other.t;
const A = mod((Y1 - X1) * (Y2 + X2));
const B = mod((Y1 + X1) * (Y2 - X2));
const F = mod(B - A);
if (F === 0n) {
// Same point.
return this.double();
}
const C = mod(Z1 * 2n * T2);
const D = mod(T1 * 2n * Z2);
const E = mod(D + C);
const G = mod(B + A);
const H = mod(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: ExtendedPoint): ExtendedPoint {
return this.add(other.negate());
}
// Non-constant-time multiplication. Uses double-and-add algorithm.
// It's faster, but should only be used when you don't care about
// an exposed private key e.g. sig verification.
multiplyUnsafe(scalar: number | bigint): ExtendedPoint {
let n = normalizeScalar(scalar);
if (n === 1n) return this;
let p = ExtendedPoint.ZERO;
let d: ExtendedPoint = this;
while (n > 0n) {
if (n & 1n) p = p.add(d);
d = d.double();
n >>= 1n;
}
return p;
}
private precomputeWindow(W: number): ExtendedPoint[] {
const windows = 256 / W + 1;
let points: ExtendedPoint[] = [];
let p: ExtendedPoint = 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;
}
private wNAF(n: bigint, affinePoint?: Point): [ExtendedPoint, ExtendedPoint] {
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 = 256 / W + 1;
const windowSize = 2 ** (W - 1);
const mask = BigInt(2 ** W - 1); // Create mask with W ones: 0b1111 for W=4 etc.
const maxNumber = 2 ** W;
const shiftBy = BigInt(W);
for (let window = 0; window < windows; window++) {
const offset = window * windowSize;
// Extract W bits.
let wbits = Number(n & mask);
// Shift number by W bits.
n >>= shiftBy;
// If the bits are bigger than max size, we'll split those.
// +224 => 256 - 32
if (wbits > windowSize) {
wbits -= maxNumber;
n += 1n;
}
// Check if we're onto Zero point.
// Add random point inside current window to f.
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 [p, f];
}
// Constant time multiplication.
// Uses wNAF method. Windowed method may be 10% faster,
// but takes 2x longer to generate and consumes 2x memory.
multiply(scalar: number | bigint, affinePoint?: Point): ExtendedPoint {
const n = normalizeScalar(scalar);
return ExtendedPoint.normalizeZ(this.wNAF(n, affinePoint))[0];
}
// Converts Extended point to default (x, y) coordinates.
// Can accept precomputed Z^-1 - for example, from invertBatch.
toAffine(invZ: bigint = invert(this.z)): Point {
const x = mod(this.x * invZ);
const y = mod(this.y * invZ);
return new Point(x, y);
}
}
// Stores precomputed values for points.
const pointPrecomputes = new WeakMap<Point, ExtendedPoint[]>();
// Default Point works in default aka affine coordinates: (x, y)
class Point {
// Base point aka generator
// public_key = Point.BASE * private_key
static BASE: Point = new Point(CURVE.Gx, CURVE.Gy);
// Identity point aka point at infinity
// point = point + zero_point
static ZERO: Point = new Point(0n, 1n);
// We calculate precomputes for elliptic curve point multiplication
// using windowed method. This specifies window size and
// stores precomputed values. Usually only base point would be precomputed.
_WINDOW_SIZE?: number;
constructor(public x: bigint, public y: bigint) {}
// "Private method", don't use it directly.
_setWindowSize(windowSize: number) {
this._WINDOW_SIZE = windowSize;
pointPrecomputes.delete(this);
}
// Converts hash string or Uint8Array to Point.
// Uses algo from RFC8032 5.1.3.
static fromHex(hash: Hex) {
const { d, P } = CURVE;
const bytes = hash instanceof Uint8Array ? hash : hexToBytes(hash);
if (bytes.length !== 32) throw new Error('Point.fromHex: expected 32 bytes');
// 1. First, interpret the string as an integer in little-endian
// representation. Bit 255 of this number is the least significant
// bit of the x-coordinate and denote this value x_0. The
// y-coordinate is recovered simply by clearing this bit. If the
// resulting value is >= p, decoding fails.
const last = bytes[31];
const normedLast = last & ~0x80;
const isLastByteOdd = (last & 0x80) !== 0;
const normed = Uint8Array.from(Array.from(bytes.slice(0, 31)).concat(normedLast));
const y = bytesToNumberLE(normed);
if (y >= P) throw new Error('Point.fromHex expects hex <= Fp');
// 2. To recover the x-coordinate, the curve equation implies
// x² = (y² - 1) / (d y² + 1) (mod p). The denominator is always
// non-zero mod p. Let u = y² - 1 and v = d y² + 1.
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');
// 4. Finally, use the x_0 bit to select the right square root. If
// x = 0, and x_0 = 1, decoding fails. Otherwise, if x_0 != x mod
// 2, set x <-- p - x. Return the decoded point (x,y).
const isXOdd = (x & 1n) === 1n;
if (isLastByteOdd !== isXOdd) {
x = mod(-x);
}
return new Point(x, y);
}
static async fromPrivateKey(privateKey: PrivKey) {
const privBytes = await utils.sha512(normalizePrivateKey(privateKey));
return Point.BASE.multiply(encodePrivate(privBytes));
}
/**
* Converts point to compressed representation of its Y.
* ECDSA uses `04${x}${y}` to represent long form and
* `02${x}` / `03${x}` to represent short form,
* where leading bit signifies positive or negative Y.
* EDDSA (ed25519) uses short form.
*/
toRawBytes(): Uint8Array {
const hex = numberToHex(this.y);
const u8 = new Uint8Array(B32);
for (let i = hex.length - 2, j = 0; j < B32 && i >= 0; i -= 2, j++) {
u8[j] = Number.parseInt(hex[i] + hex[i + 1], 16);
}
const mask = this.x & 1n ? 0x80 : 0;
u8[B32 - 1] |= mask;
return u8;
}
// Same as toRawBytes, but returns string.
toHex(): string {
return bytesToHex(this.toRawBytes());
}
// Converts to Montgomery; aka x coordinate of curve25519.
// We don't have fromX25519, because we don't know sign!
toX25519() {
// curve25519 is birationally equivalent to ed25519
// x, y: ed25519 coordinates
// u, v: x25519 coordinates
// u = (1 + y) / (1 - y)
// See https://blog.filippo.io/using-ed25519-keys-for-encryption
return mod((1n + this.y) * invert(1n - this.y));
}
equals(other: Point): boolean {
return this.x === other.x && this.y === other.y;
}
negate() {
return new Point(mod(-this.x), this.y);
}
add(other: Point) {
return ExtendedPoint.fromAffine(this).add(ExtendedPoint.fromAffine(other)).toAffine();
}
subtract(other: Point) {
return this.add(other.negate());
}
// Constant time multiplication.
multiply(scalar: number | bigint): Point {
return ExtendedPoint.fromAffine(this).multiply(scalar, this).toAffine();
}
}
class Signature {
constructor(public r: Point, public s: bigint) {}
static fromHex(hex: Hex) {
hex = ensureBytes(hex);
const r = Point.fromHex(hex.slice(0, 32));
const s = bytesToNumberLE(hex.slice(32));
if (!isWithinCurveOrder(s)) throw new Error('Signature.fromHex expects s <= CURVE.n');
return new Signature(r, s);
}
toRawBytes() {
const numberBytes = hexToBytes(numberToHex(this.s)).reverse();
const sBytes = new Uint8Array(B32);
sBytes.set(numberBytes);
const res = new Uint8Array(B32 * 2);
res.set(this.r.toRawBytes());
res.set(sBytes, 32);
return res;
// return concatTypedArrays(this.r.toRawBytes(), sBytes);
}
toHex() {
return bytesToHex(this.toRawBytes());
}
}
export { ExtendedPoint, Point, Signature, Signature as SignResult };
function concatBytes(...arrays: Uint8Array[]): Uint8Array {
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;
}
// Convert between types
// ---------------------
function bytesToHex(uint8a: Uint8Array): string {
// pre-caching chars could speed this up 6x.
let hex = '';
for (let i = 0; i < uint8a.length; i++) {
hex += uint8a[i].toString(16).padStart(2, '0');
}
return hex;
}
function hexToBytes(hex: string): Uint8Array {
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;
array[i] = Number.parseInt(hex.slice(j, j + 2), 16);
}
return array;
}
function numberToHex(num: number | bigint): string {
const hex = num.toString(16);
return hex.length & 1 ? `0${hex}` : hex;
}
function numberToBytesPadded(num: bigint, length: number = B32) {
const hex = numberToHex(num).padStart(length * 2, '0');
return hexToBytes(hex).reverse();
}
// Little-endian check for first LE bit (last BE bit);
function edIsNegative(num: bigint) {
return (mod(num) & 1n) === 1n;
}
// Little Endian
function bytesToNumberLE(uint8a: Uint8Array): bigint {
let value = 0n;
for (let i = 0; i < uint8a.length; i++) {
value += BigInt(uint8a[i]) << (8n * BigInt(i));
}
return value;
}
function bytes255ToNumberLE(bytes: Uint8Array): bigint {
return mod(bytesToNumberLE(bytes) & (2n ** 255n - 1n));
}
// -------------------------
function mod(a: bigint, b: bigint = CURVE.P) {
const res = a % b;
return res >= 0n ? res : b + res;
}
// Note: this egcd-based invert is faster than powMod-based one.
// Inverses number over modulo
function invert(number: bigint, modulo: bigint = CURVE.P): bigint {
if (number === 0n || modulo <= 0n) {
throw new Error(`invert: expected positive integers, got n=${number} mod=${modulo}`);
}
// Eucledian GCD https://brilliant.org/wiki/extended-euclidean-algorithm/
let a = mod(number, modulo);
let b = modulo;
// prettier-ignore
let x = 0n, y = 1n, u = 1n, v = 0n;
while (a !== 0n) {
const q = b / a;
const r = b % a;
const m = x - u * q;
const n = y - v * q;
// prettier-ignore
b = a, a = r, x = u, y = v, u = m, v = n;
}
const gcd = b;
if (gcd !== 1n) throw new Error('invert: does not exist');
return mod(x, modulo);
}
function invertBatch(nums: bigint[], n: bigint = CURVE.P): bigint[] {
const len = nums.length;
const scratch = new Array(len);
let acc = 1n;
for (let i = 0; i < len; i++) {
if (nums[i] === 0n) continue;
scratch[i] = acc;
acc = mod(acc * nums[i], n);
}
acc = invert(acc, n);
for (let i = len - 1; i >= 0; i--) {
if (nums[i] === 0n) continue;
let tmp = mod(acc * nums[i], n);
nums[i] = mod(acc * scratch[i], n);
acc = tmp;
}
return nums;
}
// Does x ^ (2 ^ power) mod p. pow2(30, 4) == 30 ^ (2 ^ 4)
function pow2(x: bigint, power: bigint): bigint {
const { P } = CURVE;
let res = x;
while (power-- > 0n) {
res *= res;
res %= P;
}
return res;
}
// Power to (p-5)/8 aka x^(2^252-3)
// Used to calculate y - the square root of y².
// Exponentiates it to very big number.
// We are unwrapping the loop because it's 2x faster.
// (2n**252n-3n).toString(2) would produce bits [250x 1, 0, 1]
// We are multiplying it bit-by-bit
function pow_2_252_3(x: bigint): bigint {
const { P } = CURVE;
const x2 = (x * x) % P;
const b2 = (x2 * x) % P; // x^3, 11
const b4 = (pow2(b2, 2n) * b2) % P; // x^15, 1111
const b5 = (pow2(b4, 1n) * x) % P; // x^31
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;
// ^ To pow to (p+3)/8, multiply it by x.
return pow_p_5_8;
}
// Ratio of u to v. Allows us to combine inversion and square root. Uses algo from RFC8032 5.1.3.
// prettier-ignore
function uvRatio(u: bigint, v: bigint): {isValid: boolean, value: bigint} {
const v3 = mod(v * v * v); // v³
const v7 = mod(v3 * v3 * v); // v⁷
let x = mod(u * v3 * pow_2_252_3(u * v7)); // (uv³)(uv⁷)^(p-5)/8
const vx2 = mod(v * x * x); // vx²
const root1 = x; // First root candidate
const root2 = mod(x * SQRT_M1); // Second root candidate
const useRoot1 = vx2 === u; // If vx² = u (mod p), x is a square root
const useRoot2 = vx2 === mod(-u); // If vx² = -u, set x <-- x * 2^((p-1)/4)
const noRoot = vx2 === mod(-u * SQRT_M1); // There is no valid root, vx² = -u√(-1)
if (useRoot1) x = root1;
if (useRoot2 || noRoot) x = root2; // We return root2 anyway, for const-time
if (edIsNegative(x)) x = mod(-x);
return { isValid: useRoot1 || useRoot2, value: x };
}
// Calculates 1/√(number)
function invertSqrt(number: bigint) {
return uvRatio(1n, number);
}
// Math end
async function sha512ToNumberLE(...args: Uint8Array[]): Promise<bigint> {
const messageArray = concatBytes(...args);
const hash = await utils.sha512(messageArray);
const value = bytesToNumberLE(hash);
return mod(value, CURVE.n);
}
function keyPrefix(privateBytes: Uint8Array) {
return privateBytes.slice(B32);
}
function encodePrivate(privateBytes: Uint8Array): bigint {
const last = B32 - 1;
const head = privateBytes.slice(0, B32);
head[0] &= 248;
head[last] &= 127;
head[last] |= 64;
return mod(bytesToNumberLE(head), CURVE.n);
}
function equalBytes(b1: Uint8Array, b2: Uint8Array) {
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(hash: Hex): Uint8Array {
return hash instanceof Uint8Array ? hash : hexToBytes(hash);
}
function isWithinCurveOrder(num: bigint): boolean {
return 0 < num && num < CURVE.n;
}
function normalizePrivateKey(key: PrivKey): Uint8Array {
let num: bigint;
if (typeof key === 'bigint' || (typeof key === 'number' && Number.isSafeInteger(key))) {
num = BigInt(key);
if (num < 0n || num > 2n ** 256n) throw new Error('Expected 32 bytes of private key');
key = num.toString(16).padStart(B32 * 2, '0');
}
if (typeof key === 'string') {
if (key.length !== 64) throw new Error('Expected 32 bytes of private key');
return hexToBytes(key);
} else if (key instanceof Uint8Array) {
if (key.length !== 32) throw new Error('Expected 32 bytes of private key');
return key;
} else {
throw new TypeError('Expected valid private key');
}
}
function normalizeScalar(num: number | bigint): bigint {
if (typeof num === 'number' && num > 0 && Number.isSafeInteger(num)) return BigInt(num);
if (typeof num === 'bigint' && isWithinCurveOrder(num)) return num;
throw new TypeError('Expected valid private scalar: 0 < scalar < curve.n');
}
export function getPublicKey(privateKey: Uint8Array | bigint | number): Promise<Uint8Array>;
export function getPublicKey(privateKey: string): Promise<string>;
export async function getPublicKey(privateKey: PrivKey) {
const key = await Point.fromPrivateKey(privateKey);
return typeof privateKey === 'string' ? key.toHex() : key.toRawBytes();
}
export function sign(hash: Uint8Array, privateKey: Hex): Promise<Uint8Array>;
export function sign(hash: string, privateKey: Hex): Promise<string>;
export async function sign(hash: Hex, privateKey: Hex) {
const privBytes = await utils.sha512(normalizePrivateKey(privateKey));
const p = encodePrivate(privBytes);
const P = Point.BASE.multiply(p);
const msg = ensureBytes(hash);
const r = await sha512ToNumberLE(keyPrefix(privBytes), msg);
const R = Point.BASE.multiply(r);
const h = await sha512ToNumberLE(R.toRawBytes(), P.toRawBytes(), msg);
const S = mod(r + h * p, CURVE.n);
const sig = new Signature(R, S);
return typeof hash === 'string' ? sig.toHex() : sig.toRawBytes();
}
export async function verify(signature: SigType, hash: Hex, publicKey: PubKey): Promise<boolean> {
hash = ensureBytes(hash);
if (!(publicKey instanceof Point)) publicKey = Point.fromHex(publicKey);
if (!(signature instanceof Signature)) signature = Signature.fromHex(signature);
const hs = await sha512ToNumberLE(signature.r.toRawBytes(), publicKey.toRawBytes(), hash);
const Ph = ExtendedPoint.fromAffine(publicKey).multiplyUnsafe(hs);
const Gs = ExtendedPoint.BASE.multiply(signature.s);
const RPh = ExtendedPoint.fromAffine(signature.r).add(Ph);
return RPh.subtract(Gs).multiplyUnsafe(8n).equals(ExtendedPoint.ZERO);
}
// Enable precomputes. Slows down first publicKey computation by 20ms.
Point.BASE._setWindowSize(8);
// Global symbol available in browsers only
declare const self: Record<string, any> | undefined;
const crypto: { node?: any; web?: any } = (() => {
const webCrypto = typeof self === 'object' && 'crypto' in self ? self.crypto : undefined;
const nodeRequire = typeof module !== 'undefined' && typeof require === 'function';
return {
node: nodeRequire && !webCrypto ? require('crypto') : undefined,
web: webCrypto,
};
})();
export const utils = {
// The 8-torsion subgroup ℰ8.
// Those are "buggy" points, if you multiply them by 8, you'll receive Point.ZERO.
// Ported from curve25519-dalek.
TORSION_SUBGROUP: [
'0100000000000000000000000000000000000000000000000000000000000000',
'c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac037a',
'0000000000000000000000000000000000000000000000000000000000000080',
'26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc05',
'ecffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f',
'26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc85',
'0000000000000000000000000000000000000000000000000000000000000000',
'c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac03fa',
],
randomBytes: (bytesLength: number = 32): Uint8Array => {
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");
}
},
// NIST SP 800-56A rev 3, section 5.6.1.2.2
// https://research.kudelskisecurity.com/2020/07/28/the-definitive-guide-to-modulo-bias-and-how-to-avoid-it/
randomPrivateKey: (): Uint8Array => {
let i = 1024;
while (i--) {
const b32 = utils.randomBytes(32);
const num = bytesToNumberLE(b32);
if (num > 1n && num < CURVE.n) return b32;
}
throw new Error('Valid private key was not found in 1024 iterations. PRNG is broken');
},
sha512: async (message: Uint8Array): Promise<Uint8Array> => {
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): Point {
const cached = point.equals(Point.BASE) ? point : new Point(point.x, point.y);
cached._setWindowSize(windowSize);
cached.multiply(1n);
return cached;
},
};