@decryption/curves 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +75 -0
- package/abstract/bls.d.ts +410 -0
- package/abstract/bls.js +433 -0
- package/abstract/curve.d.ts +441 -0
- package/abstract/curve.js +622 -0
- package/abstract/edwards.d.ts +319 -0
- package/abstract/edwards.js +697 -0
- package/abstract/fft.d.ts +438 -0
- package/abstract/fft.js +580 -0
- package/abstract/frost.d.ts +292 -0
- package/abstract/frost.js +705 -0
- package/abstract/hash-to-curve.d.ts +238 -0
- package/abstract/hash-to-curve.js +353 -0
- package/abstract/modular.d.ts +550 -0
- package/abstract/modular.js +872 -0
- package/abstract/montgomery.d.ts +95 -0
- package/abstract/montgomery.js +180 -0
- package/abstract/oprf.d.ts +354 -0
- package/abstract/oprf.js +358 -0
- package/abstract/poseidon.d.ts +198 -0
- package/abstract/poseidon.js +471 -0
- package/abstract/tower.d.ts +213 -0
- package/abstract/tower.js +963 -0
- package/abstract/weierstrass.d.ts +587 -0
- package/abstract/weierstrass.js +1421 -0
- package/bls12-381.d.ts +23 -0
- package/bls12-381.js +680 -0
- package/bn254.d.ts +74 -0
- package/bn254.js +248 -0
- package/ed25519.d.ts +211 -0
- package/ed25519.js +626 -0
- package/ed448.d.ts +184 -0
- package/ed448.js +596 -0
- package/esm/abstract/bls.js +429 -0
- package/esm/abstract/curve.js +610 -0
- package/esm/abstract/edwards.js +691 -0
- package/esm/abstract/fft.js +567 -0
- package/esm/abstract/frost.js +702 -0
- package/esm/abstract/hash-to-curve.js +345 -0
- package/esm/abstract/modular.js +849 -0
- package/esm/abstract/montgomery.js +177 -0
- package/esm/abstract/oprf.js +355 -0
- package/esm/abstract/poseidon.js +462 -0
- package/esm/abstract/tower.js +925 -0
- package/esm/abstract/weierstrass.js +1411 -0
- package/esm/bls12-381.js +677 -0
- package/esm/bn254.js +244 -0
- package/esm/ed25519.js +622 -0
- package/esm/ed448.js +593 -0
- package/esm/index.js +38 -0
- package/esm/misc.js +211 -0
- package/esm/nist.js +266 -0
- package/esm/secp256k1.js +465 -0
- package/esm/utils.js +597 -0
- package/esm/webcrypto.js +362 -0
- package/index.d.ts +0 -0
- package/index.js +38 -0
- package/misc.d.ts +113 -0
- package/misc.js +216 -0
- package/nist.d.ts +136 -0
- package/nist.js +269 -0
- package/package.json +46 -0
- package/secp256k1.d.ts +152 -0
- package/secp256k1.js +468 -0
- package/utils.d.ts +535 -0
- package/utils.js +626 -0
- package/webcrypto.d.ts +240 -0
- package/webcrypto.js +365 -0
|
@@ -0,0 +1,697 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.PrimeEdwardsPoint = void 0;
|
|
4
|
+
exports.edwards = edwards;
|
|
5
|
+
exports.eddsa = eddsa;
|
|
6
|
+
/**
|
|
7
|
+
* Twisted Edwards curve. The formula is: ax² + y² = 1 + dx²y².
|
|
8
|
+
* For design rationale of types / exports, see weierstrass module documentation.
|
|
9
|
+
* Untwisted Edwards curves exist, but they aren't used in real-world protocols.
|
|
10
|
+
* @module
|
|
11
|
+
*/
|
|
12
|
+
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
|
|
13
|
+
const utils_1 = require("../utils");
|
|
14
|
+
const curve_1 = require("./curve");
|
|
15
|
+
// Be friendly to bad ECMAScript parsers by not using bigint literals
|
|
16
|
+
// prettier-ignore
|
|
17
|
+
const _0n = /* @__PURE__ */ BigInt(0), _1n = /* @__PURE__ */ BigInt(1), _2n = /* @__PURE__ */ BigInt(2), _8n = /* @__PURE__ */ BigInt(8);
|
|
18
|
+
// Affine Edwards-equation check only; this does not prove subgroup membership, canonical
|
|
19
|
+
// encoding, prime-order base-point requirements, or identity exclusion.
|
|
20
|
+
function isEdValidXY(Fp, CURVE, x, y) {
|
|
21
|
+
const x2 = Fp.sqr(x);
|
|
22
|
+
const y2 = Fp.sqr(y);
|
|
23
|
+
const left = Fp.add(Fp.mul(CURVE.a, x2), y2);
|
|
24
|
+
const right = Fp.add(Fp.ONE, Fp.mul(CURVE.d, Fp.mul(x2, y2)));
|
|
25
|
+
return Fp.eql(left, right);
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* @param params - Curve parameters. See {@link EdwardsOpts}.
|
|
29
|
+
* @param extraOpts - Optional helpers and overrides. See {@link EdwardsExtraOpts}.
|
|
30
|
+
* @returns Edwards point constructor. Generator validation here only checks
|
|
31
|
+
* that `(Gx, Gy)` satisfies the affine Edwards equation.
|
|
32
|
+
* RFC 8032 base-point constraints like `B != (0,1)` and `[L]B = 0`
|
|
33
|
+
* are left to the caller's chosen parameters, since eager subgroup
|
|
34
|
+
* validation here adds about 10-15ms to heavyweight imports like ed448.
|
|
35
|
+
* The returned constructor also eagerly marks `Point.BASE` for W=8
|
|
36
|
+
* precompute caching. Some code paths still assume
|
|
37
|
+
* `Fp.BYTES === Fn.BYTES`, so mismatched byte lengths are not fully audited here.
|
|
38
|
+
* @throws If the curve parameters or Edwards overrides are invalid. {@link Error}
|
|
39
|
+
* @example
|
|
40
|
+
* ```ts
|
|
41
|
+
* import { edwards } from './edwards';
|
|
42
|
+
* import { jubjub } from '../misc';
|
|
43
|
+
* // Build a point constructor from explicit curve parameters, then use its base point.
|
|
44
|
+
* const Point = edwards(jubjub.Point.CURVE());
|
|
45
|
+
* Point.BASE.toHex();
|
|
46
|
+
* ```
|
|
47
|
+
*/
|
|
48
|
+
function edwards(params, extraOpts = {}) {
|
|
49
|
+
const opts = extraOpts;
|
|
50
|
+
const validated = (0, curve_1.createCurveFields)('edwards', params, opts, opts.FpFnLE);
|
|
51
|
+
const { Fp, Fn } = validated;
|
|
52
|
+
let CURVE = validated.CURVE;
|
|
53
|
+
const { h: cofactor } = CURVE;
|
|
54
|
+
(0, utils_1.validateObject)(opts, {}, { uvRatio: 'function' });
|
|
55
|
+
// Important:
|
|
56
|
+
// There are some places where Fp.BYTES is used instead of nByteLength.
|
|
57
|
+
// So far, everything has been tested with curves of Fp.BYTES == nByteLength.
|
|
58
|
+
// TODO: test and find curves which behave otherwise.
|
|
59
|
+
const MASK = _2n << (BigInt(Fn.BYTES * 8) - _1n);
|
|
60
|
+
const modP = (n) => Fp.create(n); // Function overrides
|
|
61
|
+
// sqrt(u/v)
|
|
62
|
+
const uvRatio = opts.uvRatio === undefined
|
|
63
|
+
? (u, v) => {
|
|
64
|
+
try {
|
|
65
|
+
return { isValid: true, value: Fp.sqrt(Fp.div(u, v)) };
|
|
66
|
+
}
|
|
67
|
+
catch (e) {
|
|
68
|
+
return { isValid: false, value: _0n };
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
: opts.uvRatio;
|
|
72
|
+
// Validate whether the passed curve params are valid.
|
|
73
|
+
// equation ax² + y² = 1 + dx²y² should work for generator point.
|
|
74
|
+
if (!isEdValidXY(Fp, CURVE, CURVE.Gx, CURVE.Gy))
|
|
75
|
+
throw new Error('bad curve params: generator point');
|
|
76
|
+
/**
|
|
77
|
+
* Asserts coordinate is valid: 0 <= n < MASK.
|
|
78
|
+
* Coordinates >= Fp.ORDER are allowed for zip215.
|
|
79
|
+
*/
|
|
80
|
+
function acoord(title, n, banZero = false) {
|
|
81
|
+
const min = banZero ? _1n : _0n;
|
|
82
|
+
(0, utils_1.aInRange)('coordinate ' + title, n, min, MASK);
|
|
83
|
+
return n;
|
|
84
|
+
}
|
|
85
|
+
function aedpoint(other) {
|
|
86
|
+
if (!(other instanceof Point))
|
|
87
|
+
throw new Error('EdwardsPoint expected');
|
|
88
|
+
}
|
|
89
|
+
// Extended Point works in extended coordinates: (X, Y, Z, T) ∋ (x=X/Z, y=Y/Z, T=xy).
|
|
90
|
+
// https://en.wikipedia.org/wiki/Twisted_Edwards_curve#Extended_coordinates
|
|
91
|
+
class Point {
|
|
92
|
+
// base / generator point
|
|
93
|
+
static BASE = new Point(CURVE.Gx, CURVE.Gy, _1n, modP(CURVE.Gx * CURVE.Gy));
|
|
94
|
+
// zero / infinity / identity point
|
|
95
|
+
static ZERO = new Point(_0n, _1n, _1n, _0n); // 0, 1, 1, 0
|
|
96
|
+
// math field
|
|
97
|
+
static Fp = Fp;
|
|
98
|
+
// scalar field
|
|
99
|
+
static Fn = Fn;
|
|
100
|
+
X;
|
|
101
|
+
Y;
|
|
102
|
+
Z;
|
|
103
|
+
T;
|
|
104
|
+
constructor(X, Y, Z, T) {
|
|
105
|
+
this.X = acoord('x', X);
|
|
106
|
+
this.Y = acoord('y', Y);
|
|
107
|
+
this.Z = acoord('z', Z, true);
|
|
108
|
+
this.T = acoord('t', T);
|
|
109
|
+
Object.freeze(this);
|
|
110
|
+
}
|
|
111
|
+
static CURVE() {
|
|
112
|
+
return CURVE;
|
|
113
|
+
}
|
|
114
|
+
/**
|
|
115
|
+
* Create one extended Edwards point from affine coordinates.
|
|
116
|
+
* Does NOT validate that the point is on-curve or torsion-free.
|
|
117
|
+
* Use `.assertValidity()` on adversarial inputs.
|
|
118
|
+
*/
|
|
119
|
+
static fromAffine(p) {
|
|
120
|
+
if (p instanceof Point)
|
|
121
|
+
throw new Error('extended point not allowed');
|
|
122
|
+
const { x, y } = p || {};
|
|
123
|
+
acoord('x', x);
|
|
124
|
+
acoord('y', y);
|
|
125
|
+
return new Point(x, y, _1n, modP(x * y));
|
|
126
|
+
}
|
|
127
|
+
// Uses algo from RFC8032 5.1.3.
|
|
128
|
+
static fromBytes(bytes, zip215 = false) {
|
|
129
|
+
const len = Fp.BYTES;
|
|
130
|
+
const { a, d } = CURVE;
|
|
131
|
+
bytes = (0, utils_1.copyBytes)((0, utils_1.abytes)(bytes, len, 'point'));
|
|
132
|
+
(0, utils_1.abool)(zip215, 'zip215');
|
|
133
|
+
const normed = (0, utils_1.copyBytes)(bytes); // copy again, we'll manipulate it
|
|
134
|
+
const lastByte = bytes[len - 1]; // select last byte
|
|
135
|
+
normed[len - 1] = lastByte & ~0x80; // clear last bit
|
|
136
|
+
const y = (0, utils_1.bytesToNumberLE)(normed);
|
|
137
|
+
// zip215=true is good for consensus-critical apps. =false follows RFC8032 / NIST186-5.
|
|
138
|
+
// RFC8032 prohibits >= p, but ZIP215 doesn't
|
|
139
|
+
// zip215=true: 0 <= y < MASK (2^256 for ed25519)
|
|
140
|
+
// zip215=false: 0 <= y < P (2^255-19 for ed25519)
|
|
141
|
+
const max = zip215 ? MASK : Fp.ORDER;
|
|
142
|
+
(0, utils_1.aInRange)('point.y', y, _0n, max);
|
|
143
|
+
// Ed25519: x² = (y²-1)/(dy²+1) mod p. Ed448: x² = (y²-1)/(dy²-1) mod p. Generic case:
|
|
144
|
+
// ax²+y²=1+dx²y² => y²-1=dx²y²-ax² => y²-1=x²(dy²-a) => x²=(y²-1)/(dy²-a)
|
|
145
|
+
const y2 = modP(y * y); // denominator is always non-0 mod p.
|
|
146
|
+
const u = modP(y2 - _1n); // u = y² - 1
|
|
147
|
+
const v = modP(d * y2 - a); // v = d y² + 1.
|
|
148
|
+
let { isValid, value: x } = uvRatio(u, v); // √(u/v)
|
|
149
|
+
if (!isValid)
|
|
150
|
+
throw new Error('bad point: invalid y coordinate');
|
|
151
|
+
const isXOdd = (x & _1n) === _1n; // There are 2 square roots. Use x_0 bit to select proper
|
|
152
|
+
const isLastByteOdd = (lastByte & 0x80) !== 0; // x_0, last bit
|
|
153
|
+
if (!zip215 && x === _0n && isLastByteOdd)
|
|
154
|
+
// if x=0 and x_0 = 1, fail
|
|
155
|
+
throw new Error('bad point: x=0 and x_0=1');
|
|
156
|
+
if (isLastByteOdd !== isXOdd)
|
|
157
|
+
x = modP(-x); // if x_0 != x mod 2, set x = p-x
|
|
158
|
+
return Point.fromAffine({ x, y });
|
|
159
|
+
}
|
|
160
|
+
static fromHex(hex, zip215 = false) {
|
|
161
|
+
return Point.fromBytes((0, utils_1.hexToBytes)(hex), zip215);
|
|
162
|
+
}
|
|
163
|
+
get x() {
|
|
164
|
+
return this.toAffine().x;
|
|
165
|
+
}
|
|
166
|
+
get y() {
|
|
167
|
+
return this.toAffine().y;
|
|
168
|
+
}
|
|
169
|
+
precompute(windowSize = 8, isLazy = true) {
|
|
170
|
+
wnaf.createCache(this, windowSize);
|
|
171
|
+
if (!isLazy)
|
|
172
|
+
this.multiply(_2n); // random number
|
|
173
|
+
return this;
|
|
174
|
+
}
|
|
175
|
+
// Useful in fromAffine() - not for fromBytes(), which always created valid points.
|
|
176
|
+
assertValidity() {
|
|
177
|
+
const p = this;
|
|
178
|
+
const { a, d } = CURVE;
|
|
179
|
+
// Keep generic Edwards validation fail-closed on the neutral point.
|
|
180
|
+
// Even though ZERO is algebraically valid and can roundtrip through encodings, higher-level
|
|
181
|
+
// callers often reach it only through broken hash/scalar plumbing; rejecting it here avoids
|
|
182
|
+
// silently treating that degenerate state as an ordinary public point.
|
|
183
|
+
if (p.is0())
|
|
184
|
+
throw new Error('bad point: ZERO'); // TODO: optimize, with vars below?
|
|
185
|
+
// Equation in affine coordinates: ax² + y² = 1 + dx²y²
|
|
186
|
+
// Equation in projective coordinates (X/Z, Y/Z, Z): (aX² + Y²)Z² = Z⁴ + dX²Y²
|
|
187
|
+
const { X, Y, Z, T } = p;
|
|
188
|
+
const X2 = modP(X * X); // X²
|
|
189
|
+
const Y2 = modP(Y * Y); // Y²
|
|
190
|
+
const Z2 = modP(Z * Z); // Z²
|
|
191
|
+
const Z4 = modP(Z2 * Z2); // Z⁴
|
|
192
|
+
const aX2 = modP(X2 * a); // aX²
|
|
193
|
+
const left = modP(Z2 * modP(aX2 + Y2)); // (aX² + Y²)Z²
|
|
194
|
+
const right = modP(Z4 + modP(d * modP(X2 * Y2))); // Z⁴ + dX²Y²
|
|
195
|
+
if (left !== right)
|
|
196
|
+
throw new Error('bad point: equation left != right (1)');
|
|
197
|
+
// In Extended coordinates we also have T, which is x*y=T/Z: check X*Y == Z*T
|
|
198
|
+
const XY = modP(X * Y);
|
|
199
|
+
const ZT = modP(Z * T);
|
|
200
|
+
if (XY !== ZT)
|
|
201
|
+
throw new Error('bad point: equation left != right (2)');
|
|
202
|
+
}
|
|
203
|
+
// Compare one point to another.
|
|
204
|
+
equals(other) {
|
|
205
|
+
aedpoint(other);
|
|
206
|
+
const { X: X1, Y: Y1, Z: Z1 } = this;
|
|
207
|
+
const { X: X2, Y: Y2, Z: Z2 } = other;
|
|
208
|
+
const X1Z2 = modP(X1 * Z2);
|
|
209
|
+
const X2Z1 = modP(X2 * Z1);
|
|
210
|
+
const Y1Z2 = modP(Y1 * Z2);
|
|
211
|
+
const Y2Z1 = modP(Y2 * Z1);
|
|
212
|
+
return X1Z2 === X2Z1 && Y1Z2 === Y2Z1;
|
|
213
|
+
}
|
|
214
|
+
is0() {
|
|
215
|
+
return this.equals(Point.ZERO);
|
|
216
|
+
}
|
|
217
|
+
negate() {
|
|
218
|
+
// Flips point sign to a negative one (-x, y in affine coords)
|
|
219
|
+
return new Point(modP(-this.X), this.Y, this.Z, modP(-this.T));
|
|
220
|
+
}
|
|
221
|
+
// Fast algo for doubling Extended Point.
|
|
222
|
+
// https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#doubling-dbl-2008-hwcd
|
|
223
|
+
// Cost: 4M + 4S + 1*a + 6add + 1*2.
|
|
224
|
+
double() {
|
|
225
|
+
const { a } = CURVE;
|
|
226
|
+
const { X: X1, Y: Y1, Z: Z1 } = this;
|
|
227
|
+
const A = modP(X1 * X1); // A = X12
|
|
228
|
+
const B = modP(Y1 * Y1); // B = Y12
|
|
229
|
+
const C = modP(_2n * modP(Z1 * Z1)); // C = 2*Z12
|
|
230
|
+
const D = modP(a * A); // D = a*A
|
|
231
|
+
const x1y1 = X1 + Y1;
|
|
232
|
+
const E = modP(modP(x1y1 * x1y1) - A - B); // E = (X1+Y1)2-A-B
|
|
233
|
+
const G = D + B; // G = D+B
|
|
234
|
+
const F = G - C; // F = G-C
|
|
235
|
+
const H = D - B; // H = D-B
|
|
236
|
+
const X3 = modP(E * F); // X3 = E*F
|
|
237
|
+
const Y3 = modP(G * H); // Y3 = G*H
|
|
238
|
+
const T3 = modP(E * H); // T3 = E*H
|
|
239
|
+
const Z3 = modP(F * G); // Z3 = F*G
|
|
240
|
+
return new Point(X3, Y3, Z3, T3);
|
|
241
|
+
}
|
|
242
|
+
// Fast algo for adding 2 Extended Points.
|
|
243
|
+
// https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#addition-add-2008-hwcd
|
|
244
|
+
// Cost: 9M + 1*a + 1*d + 7add.
|
|
245
|
+
add(other) {
|
|
246
|
+
aedpoint(other);
|
|
247
|
+
const { a, d } = CURVE;
|
|
248
|
+
const { X: X1, Y: Y1, Z: Z1, T: T1 } = this;
|
|
249
|
+
const { X: X2, Y: Y2, Z: Z2, T: T2 } = other;
|
|
250
|
+
const A = modP(X1 * X2); // A = X1*X2
|
|
251
|
+
const B = modP(Y1 * Y2); // B = Y1*Y2
|
|
252
|
+
const C = modP(T1 * d * T2); // C = T1*d*T2
|
|
253
|
+
const D = modP(Z1 * Z2); // D = Z1*Z2
|
|
254
|
+
const E = modP((X1 + Y1) * (X2 + Y2) - A - B); // E = (X1+Y1)*(X2+Y2)-A-B
|
|
255
|
+
const F = D - C; // F = D-C
|
|
256
|
+
const G = D + C; // G = D+C
|
|
257
|
+
const H = modP(B - a * A); // H = B-a*A
|
|
258
|
+
const X3 = modP(E * F); // X3 = E*F
|
|
259
|
+
const Y3 = modP(G * H); // Y3 = G*H
|
|
260
|
+
const T3 = modP(E * H); // T3 = E*H
|
|
261
|
+
const Z3 = modP(F * G); // Z3 = F*G
|
|
262
|
+
return new Point(X3, Y3, Z3, T3);
|
|
263
|
+
}
|
|
264
|
+
subtract(other) {
|
|
265
|
+
// Validate before calling `negate()` so wrong inputs fail with the point guard
|
|
266
|
+
// instead of leaking a foreign `negate()` error.
|
|
267
|
+
aedpoint(other);
|
|
268
|
+
return this.add(other.negate());
|
|
269
|
+
}
|
|
270
|
+
// Constant-time multiplication.
|
|
271
|
+
multiply(scalar) {
|
|
272
|
+
// 1 <= scalar < L
|
|
273
|
+
// Keep the subgroup-scalar contract strict instead of reducing 0 / n to ZERO.
|
|
274
|
+
// In keygen/signing-style callers, those values usually mean broken hash/scalar plumbing,
|
|
275
|
+
// and failing closed is safer than silently producing the identity point.
|
|
276
|
+
if (!Fn.isValidNot0(scalar))
|
|
277
|
+
throw new RangeError('invalid scalar: expected 1 <= sc < curve.n');
|
|
278
|
+
const { p, f } = wnaf.cached(this, scalar, (p) => (0, curve_1.normalizeZ)(Point, p));
|
|
279
|
+
return (0, curve_1.normalizeZ)(Point, [p, f])[0];
|
|
280
|
+
}
|
|
281
|
+
// Non-constant-time multiplication. Uses double-and-add algorithm.
|
|
282
|
+
// It's faster, but should only be used when you don't care about
|
|
283
|
+
// an exposed private key e.g. sig verification.
|
|
284
|
+
// Keeps the same subgroup-scalar contract: 0 is allowed for public-scalar callers, but
|
|
285
|
+
// n and larger values are rejected instead of being reduced mod n to the identity point.
|
|
286
|
+
multiplyUnsafe(scalar) {
|
|
287
|
+
// 0 <= scalar < L
|
|
288
|
+
if (!Fn.isValid(scalar))
|
|
289
|
+
throw new RangeError('invalid scalar: expected 0 <= sc < curve.n');
|
|
290
|
+
if (scalar === _0n)
|
|
291
|
+
return Point.ZERO;
|
|
292
|
+
if (this.is0() || scalar === _1n)
|
|
293
|
+
return this;
|
|
294
|
+
return wnaf.unsafe(this, scalar, (p) => (0, curve_1.normalizeZ)(Point, p));
|
|
295
|
+
}
|
|
296
|
+
// Checks if point is of small order.
|
|
297
|
+
// If you add something to small order point, you will have "dirty"
|
|
298
|
+
// point with torsion component.
|
|
299
|
+
// Clears cofactor and checks if the result is 0.
|
|
300
|
+
isSmallOrder() {
|
|
301
|
+
return this.clearCofactor().is0();
|
|
302
|
+
}
|
|
303
|
+
// Multiplies point by curve order and checks if the result is 0.
|
|
304
|
+
// Returns `false` is the point is dirty.
|
|
305
|
+
isTorsionFree() {
|
|
306
|
+
return wnaf.unsafe(this, CURVE.n).is0();
|
|
307
|
+
}
|
|
308
|
+
// Converts Extended point to default (x, y) coordinates.
|
|
309
|
+
// Can accept precomputed Z^-1 - for example, from invertBatch.
|
|
310
|
+
toAffine(invertedZ) {
|
|
311
|
+
const p = this;
|
|
312
|
+
let iz = invertedZ;
|
|
313
|
+
const { X, Y, Z } = p;
|
|
314
|
+
const is0 = p.is0();
|
|
315
|
+
if (iz == null)
|
|
316
|
+
iz = is0 ? _8n : Fp.inv(Z); // 8 was chosen arbitrarily
|
|
317
|
+
const x = modP(X * iz);
|
|
318
|
+
const y = modP(Y * iz);
|
|
319
|
+
const zz = Fp.mul(Z, iz);
|
|
320
|
+
if (is0)
|
|
321
|
+
return { x: _0n, y: _1n };
|
|
322
|
+
if (zz !== _1n)
|
|
323
|
+
throw new Error('invZ was invalid');
|
|
324
|
+
return { x, y };
|
|
325
|
+
}
|
|
326
|
+
clearCofactor() {
|
|
327
|
+
if (cofactor === _1n)
|
|
328
|
+
return this;
|
|
329
|
+
return this.multiplyUnsafe(cofactor);
|
|
330
|
+
}
|
|
331
|
+
toBytes() {
|
|
332
|
+
const { x, y } = this.toAffine();
|
|
333
|
+
// Fp.toBytes() allows non-canonical encoding of y (>= p).
|
|
334
|
+
const bytes = Fp.toBytes(y);
|
|
335
|
+
// Each y has 2 valid points: (x, y), (x,-y).
|
|
336
|
+
// When compressing, it's enough to store y and use the last byte to encode sign of x
|
|
337
|
+
bytes[bytes.length - 1] |= x & _1n ? 0x80 : 0;
|
|
338
|
+
return bytes;
|
|
339
|
+
}
|
|
340
|
+
toHex() {
|
|
341
|
+
return (0, utils_1.bytesToHex)(this.toBytes());
|
|
342
|
+
}
|
|
343
|
+
toString() {
|
|
344
|
+
return `<Point ${this.is0() ? 'ZERO' : this.toHex()}>`;
|
|
345
|
+
}
|
|
346
|
+
}
|
|
347
|
+
const wnaf = new curve_1.wNAF(Point, Fn.BITS);
|
|
348
|
+
// Keep constructor work cheap: subgroup/generator validation belongs to the caller's curve
|
|
349
|
+
// parameters, and doing the extra checks here adds about 10-15ms to heavy module imports.
|
|
350
|
+
// Callers that construct custom curves are responsible for supplying the correct base point.
|
|
351
|
+
// try {
|
|
352
|
+
// Point.BASE.assertValidity();
|
|
353
|
+
// if (!Point.BASE.isTorsionFree()) throw new Error('bad point: not in prime-order subgroup');
|
|
354
|
+
// } catch {
|
|
355
|
+
// throw new Error('bad curve params: generator point');
|
|
356
|
+
// }
|
|
357
|
+
// Tiny toy curves can have scalar fields narrower than 8 bits. Skip the
|
|
358
|
+
// eager W=8 cache there instead of rejecting an otherwise valid constructor.
|
|
359
|
+
if (Fn.BITS >= 8)
|
|
360
|
+
Point.BASE.precompute(8); // Enable precomputes. Slows down first publicKey computation by 20ms.
|
|
361
|
+
Object.freeze(Point.prototype);
|
|
362
|
+
Object.freeze(Point);
|
|
363
|
+
return Point;
|
|
364
|
+
}
|
|
365
|
+
/**
|
|
366
|
+
* Base class for prime-order points like Ristretto255 and Decaf448.
|
|
367
|
+
* These points eliminate cofactor issues by representing equivalence classes
|
|
368
|
+
* of Edwards curve points. Multiple Edwards representatives can describe the
|
|
369
|
+
* same abstract wrapper element, so wrapper validity is not the same thing as
|
|
370
|
+
* the hidden representative being torsion-free.
|
|
371
|
+
* @param ep - Backing Edwards point.
|
|
372
|
+
* @example
|
|
373
|
+
* Base class for prime-order points like Ristretto255 and Decaf448.
|
|
374
|
+
*
|
|
375
|
+
* ```ts
|
|
376
|
+
* import { ristretto255 } from '../ed25519';
|
|
377
|
+
* const point = ristretto255.Point.BASE.multiply(2n);
|
|
378
|
+
* ```
|
|
379
|
+
*/
|
|
380
|
+
class PrimeEdwardsPoint {
|
|
381
|
+
static BASE;
|
|
382
|
+
static ZERO;
|
|
383
|
+
static Fp;
|
|
384
|
+
static Fn;
|
|
385
|
+
ep;
|
|
386
|
+
/**
|
|
387
|
+
* Wrap one internal Edwards representative directly.
|
|
388
|
+
* This is not a canonical encoding boundary: alternate Edwards
|
|
389
|
+
* representatives may still describe the same abstract wrapper element.
|
|
390
|
+
*/
|
|
391
|
+
constructor(ep) {
|
|
392
|
+
this.ep = ep;
|
|
393
|
+
}
|
|
394
|
+
// Static methods that must be implemented by subclasses
|
|
395
|
+
static fromBytes(_bytes) {
|
|
396
|
+
(0, utils_1.notImplemented)();
|
|
397
|
+
}
|
|
398
|
+
static fromHex(_hex) {
|
|
399
|
+
(0, utils_1.notImplemented)();
|
|
400
|
+
}
|
|
401
|
+
get x() {
|
|
402
|
+
return this.toAffine().x;
|
|
403
|
+
}
|
|
404
|
+
get y() {
|
|
405
|
+
return this.toAffine().y;
|
|
406
|
+
}
|
|
407
|
+
// Common implementations
|
|
408
|
+
clearCofactor() {
|
|
409
|
+
// no-op for the abstract prime-order wrapper group; this is about the
|
|
410
|
+
// wrapper element, not the hidden Edwards representative.
|
|
411
|
+
return this;
|
|
412
|
+
}
|
|
413
|
+
assertValidity() {
|
|
414
|
+
// Keep wrapper validity at the abstract-group boundary. Canonical decode
|
|
415
|
+
// may choose Edwards representatives that differ by small torsion, so
|
|
416
|
+
// checking `this.ep.isTorsionFree()` here would reject valid wrapper points.
|
|
417
|
+
this.ep.assertValidity();
|
|
418
|
+
}
|
|
419
|
+
/**
|
|
420
|
+
* Return affine coordinates of the current internal Edwards representative.
|
|
421
|
+
* This is a convenience helper, not a canonical Ristretto/Decaf encoding.
|
|
422
|
+
* Equal abstract elements may expose different `x` / `y`; use
|
|
423
|
+
* `toBytes()` / `fromBytes()` for canonical roundtrips.
|
|
424
|
+
*/
|
|
425
|
+
toAffine(invertedZ) {
|
|
426
|
+
return this.ep.toAffine(invertedZ);
|
|
427
|
+
}
|
|
428
|
+
toHex() {
|
|
429
|
+
return (0, utils_1.bytesToHex)(this.toBytes());
|
|
430
|
+
}
|
|
431
|
+
toString() {
|
|
432
|
+
return this.toHex();
|
|
433
|
+
}
|
|
434
|
+
isTorsionFree() {
|
|
435
|
+
// Abstract Ristretto/Decaf elements are already prime-order even when the
|
|
436
|
+
// hidden Edwards representative is not torsion-free.
|
|
437
|
+
return true;
|
|
438
|
+
}
|
|
439
|
+
isSmallOrder() {
|
|
440
|
+
return false;
|
|
441
|
+
}
|
|
442
|
+
add(other) {
|
|
443
|
+
this.assertSame(other);
|
|
444
|
+
return this.init(this.ep.add(other.ep));
|
|
445
|
+
}
|
|
446
|
+
subtract(other) {
|
|
447
|
+
this.assertSame(other);
|
|
448
|
+
return this.init(this.ep.subtract(other.ep));
|
|
449
|
+
}
|
|
450
|
+
multiply(scalar) {
|
|
451
|
+
return this.init(this.ep.multiply(scalar));
|
|
452
|
+
}
|
|
453
|
+
multiplyUnsafe(scalar) {
|
|
454
|
+
return this.init(this.ep.multiplyUnsafe(scalar));
|
|
455
|
+
}
|
|
456
|
+
double() {
|
|
457
|
+
return this.init(this.ep.double());
|
|
458
|
+
}
|
|
459
|
+
negate() {
|
|
460
|
+
return this.init(this.ep.negate());
|
|
461
|
+
}
|
|
462
|
+
precompute(windowSize, isLazy) {
|
|
463
|
+
this.ep.precompute(windowSize, isLazy);
|
|
464
|
+
// Keep the wrapper identity stable like the backing Edwards API instead of
|
|
465
|
+
// allocating a fresh wrapper around the same cached point.
|
|
466
|
+
return this;
|
|
467
|
+
}
|
|
468
|
+
}
|
|
469
|
+
exports.PrimeEdwardsPoint = PrimeEdwardsPoint;
|
|
470
|
+
/**
|
|
471
|
+
* Initializes EdDSA signatures over given Edwards curve.
|
|
472
|
+
* @param Point - Edwards point constructor.
|
|
473
|
+
* @param cHash - Hash function.
|
|
474
|
+
* @param eddsaOpts - Optional signature helpers. See {@link EdDSAOpts}.
|
|
475
|
+
* @returns EdDSA helper namespace.
|
|
476
|
+
* @throws If the hash function, options, or derived point operations are invalid. {@link Error}
|
|
477
|
+
* @example
|
|
478
|
+
* Initializes EdDSA signatures over given Edwards curve.
|
|
479
|
+
*
|
|
480
|
+
* ```ts
|
|
481
|
+
* import { eddsa } from './edwards';
|
|
482
|
+
* import { jubjub } from '../misc';
|
|
483
|
+
* import { sha512 } from '@decryption/hashes/sha2';
|
|
484
|
+
* const sigs = eddsa(jubjub.Point, sha512);
|
|
485
|
+
* const { secretKey, publicKey } = sigs.keygen();
|
|
486
|
+
* const msg = new TextEncoder().encode('hello noble');
|
|
487
|
+
* const sig = sigs.sign(msg, secretKey);
|
|
488
|
+
* const isValid = sigs.verify(sig, msg, publicKey);
|
|
489
|
+
* ```
|
|
490
|
+
*/
|
|
491
|
+
function eddsa(Point, cHash, eddsaOpts = {}) {
|
|
492
|
+
if (typeof cHash !== 'function')
|
|
493
|
+
throw new Error('"hash" function param is required');
|
|
494
|
+
const hash = cHash;
|
|
495
|
+
const opts = eddsaOpts;
|
|
496
|
+
(0, utils_1.validateObject)(opts, {}, {
|
|
497
|
+
adjustScalarBytes: 'function',
|
|
498
|
+
randomBytes: 'function',
|
|
499
|
+
domain: 'function',
|
|
500
|
+
prehash: 'function',
|
|
501
|
+
zip215: 'boolean',
|
|
502
|
+
mapToCurve: 'function',
|
|
503
|
+
});
|
|
504
|
+
const { prehash } = opts;
|
|
505
|
+
const { BASE, Fp, Fn } = Point;
|
|
506
|
+
const outputLen = hash.outputLen;
|
|
507
|
+
const expectedLen = 2 * Fp.BYTES;
|
|
508
|
+
// When hash metadata is available, reject incompatible EdDSA wrappers at construction time
|
|
509
|
+
// instead of deferring the mismatch until the first keygen/sign call.
|
|
510
|
+
if (outputLen !== undefined) {
|
|
511
|
+
(0, utils_1.asafenumber)(outputLen, 'hash.outputLen');
|
|
512
|
+
if (outputLen !== expectedLen)
|
|
513
|
+
throw new Error(`hash.outputLen must be ${expectedLen}, got ${outputLen}`);
|
|
514
|
+
}
|
|
515
|
+
const randomBytes = opts.randomBytes === undefined ? utils_1.randomBytes : opts.randomBytes;
|
|
516
|
+
const adjustScalarBytes = opts.adjustScalarBytes === undefined
|
|
517
|
+
? (bytes) => bytes
|
|
518
|
+
: opts.adjustScalarBytes;
|
|
519
|
+
const domain = opts.domain === undefined
|
|
520
|
+
? (data, ctx, phflag) => {
|
|
521
|
+
(0, utils_1.abool)(phflag, 'phflag');
|
|
522
|
+
if (ctx.length || phflag)
|
|
523
|
+
throw new Error('Contexts/pre-hash are not supported');
|
|
524
|
+
return data;
|
|
525
|
+
}
|
|
526
|
+
: opts.domain; // NOOP
|
|
527
|
+
// Parse an EdDSA digest as a little-endian integer and reduce it modulo the scalar field order.
|
|
528
|
+
function modN_LE(hash) {
|
|
529
|
+
return Fn.create((0, utils_1.bytesToNumberLE)(hash)); // Not Fn.fromBytes: it has length limit
|
|
530
|
+
}
|
|
531
|
+
// Get the hashed private scalar per RFC8032 5.1.5
|
|
532
|
+
function getPrivateScalar(key) {
|
|
533
|
+
const len = lengths.secretKey;
|
|
534
|
+
(0, utils_1.abytes)(key, lengths.secretKey, 'secretKey');
|
|
535
|
+
// Hash private key with curve's hash function to produce uniformingly random input
|
|
536
|
+
// Check byte lengths: ensure(64, h(ensure(32, key)))
|
|
537
|
+
const hashed = (0, utils_1.abytes)(hash(key), 2 * len, 'hashedSecretKey');
|
|
538
|
+
// Slice before clamping so in-place adjustors don't corrupt the prefix half.
|
|
539
|
+
const head = adjustScalarBytes(hashed.slice(0, len)); // clear first half bits, produce FE
|
|
540
|
+
const prefix = hashed.slice(len, 2 * len); // second half is called key prefix (5.1.6)
|
|
541
|
+
const scalar = modN_LE(head); // The actual private scalar
|
|
542
|
+
return { head, prefix, scalar };
|
|
543
|
+
}
|
|
544
|
+
/** Convenience method that creates public key from scalar. RFC8032 5.1.5
|
|
545
|
+
* Also exposes the derived scalar/prefix tuple and point form reused by sign().
|
|
546
|
+
*/
|
|
547
|
+
function getExtendedPublicKey(secretKey) {
|
|
548
|
+
const { head, prefix, scalar } = getPrivateScalar(secretKey);
|
|
549
|
+
const point = BASE.multiply(scalar); // Point on Edwards curve aka public key
|
|
550
|
+
const pointBytes = point.toBytes();
|
|
551
|
+
return { head, prefix, scalar, point, pointBytes };
|
|
552
|
+
}
|
|
553
|
+
/** Calculates EdDSA pub key. RFC8032 5.1.5. */
|
|
554
|
+
function getPublicKey(secretKey) {
|
|
555
|
+
return getExtendedPublicKey(secretKey).pointBytes;
|
|
556
|
+
}
|
|
557
|
+
// Hash domain-separated chunks into a little-endian scalar modulo the group order.
|
|
558
|
+
function hashDomainToScalar(context = Uint8Array.of(), ...msgs) {
|
|
559
|
+
const msg = (0, utils_1.concatBytes)(...msgs);
|
|
560
|
+
return modN_LE(hash(domain(msg, (0, utils_1.abytes)(context, undefined, 'context'), !!prehash)));
|
|
561
|
+
}
|
|
562
|
+
/** Signs message with secret key. RFC8032 5.1.6 */
|
|
563
|
+
function sign(msg, secretKey, options = {}) {
|
|
564
|
+
msg = (0, utils_1.abytes)(msg, undefined, 'message');
|
|
565
|
+
if (prehash)
|
|
566
|
+
msg = prehash(msg); // for ed25519ph etc.
|
|
567
|
+
const { prefix, scalar, pointBytes } = getExtendedPublicKey(secretKey);
|
|
568
|
+
const r = hashDomainToScalar(options.context, prefix, msg); // r = dom2(F, C) || prefix || PH(M)
|
|
569
|
+
// RFC 8032 5.1.6 allows r mod L = 0, and SUPERCOP ref10 accepts the resulting identity-point
|
|
570
|
+
// signature.
|
|
571
|
+
// We intentionally keep the safe multiply() rejection here so a miswired all-zero hash provider
|
|
572
|
+
// fails loudly instead of silently producing a degenerate signature.
|
|
573
|
+
const R = BASE.multiply(r).toBytes(); // R = rG
|
|
574
|
+
const k = hashDomainToScalar(options.context, R, pointBytes, msg); // R || A || PH(M)
|
|
575
|
+
const s = Fn.create(r + k * scalar); // S = (r + k * s) mod L
|
|
576
|
+
if (!Fn.isValid(s))
|
|
577
|
+
throw new Error('sign failed: invalid s'); // 0 <= s < L
|
|
578
|
+
const rs = (0, utils_1.concatBytes)(R, Fn.toBytes(s));
|
|
579
|
+
return (0, utils_1.abytes)(rs, lengths.signature, 'result');
|
|
580
|
+
}
|
|
581
|
+
// Keep the shared helper strict by default: RFC 8032 / NIST-style wrappers should reject
|
|
582
|
+
// non-canonical encodings unless they explicitly opt into ZIP-215's more permissive decode rules.
|
|
583
|
+
const verifyOpts = {
|
|
584
|
+
zip215: opts.zip215,
|
|
585
|
+
};
|
|
586
|
+
/**
|
|
587
|
+
* Verifies EdDSA signature against message and public key. RFC 8032 §§5.1.7 and 5.2.7.
|
|
588
|
+
* A cofactored verification equation is checked.
|
|
589
|
+
*/
|
|
590
|
+
function verify(sig, msg, publicKey, options = verifyOpts) {
|
|
591
|
+
// Preserve the wrapper-selected default for `{}` / `{ zip215: undefined }`, not just omitted opts.
|
|
592
|
+
const { context } = options;
|
|
593
|
+
const zip215 = options.zip215 === undefined ? !!verifyOpts.zip215 : options.zip215;
|
|
594
|
+
const len = lengths.signature;
|
|
595
|
+
sig = (0, utils_1.abytes)(sig, len, 'signature');
|
|
596
|
+
msg = (0, utils_1.abytes)(msg, undefined, 'message');
|
|
597
|
+
publicKey = (0, utils_1.abytes)(publicKey, lengths.publicKey, 'publicKey');
|
|
598
|
+
if (zip215 !== undefined)
|
|
599
|
+
(0, utils_1.abool)(zip215, 'zip215');
|
|
600
|
+
if (prehash)
|
|
601
|
+
msg = prehash(msg); // for ed25519ph, etc
|
|
602
|
+
const mid = len / 2;
|
|
603
|
+
const r = sig.subarray(0, mid);
|
|
604
|
+
const s = (0, utils_1.bytesToNumberLE)(sig.subarray(mid, len));
|
|
605
|
+
let A, R, SB;
|
|
606
|
+
try {
|
|
607
|
+
// ZIP-215 is more permissive than RFC 8032 / NIST186-5. Use it only for wrappers that
|
|
608
|
+
// explicitly want consensus-style unreduced encoding acceptance.
|
|
609
|
+
// zip215=true: 0 <= y < MASK (2^256 for ed25519)
|
|
610
|
+
// zip215=false: 0 <= y < P (2^255-19 for ed25519)
|
|
611
|
+
A = Point.fromBytes(publicKey, zip215);
|
|
612
|
+
R = Point.fromBytes(r, zip215);
|
|
613
|
+
SB = BASE.multiplyUnsafe(s); // 0 <= s < l is done inside
|
|
614
|
+
}
|
|
615
|
+
catch (error) {
|
|
616
|
+
return false;
|
|
617
|
+
}
|
|
618
|
+
// RFC 8032 §§5.1.7/5.2.7 and FIPS 186-5 §§7.7.2/7.8.2 only decode A' and check the cofactored
|
|
619
|
+
// verification equation; they do not add a separate low-order-public-key rejection here.
|
|
620
|
+
// Strict mode still rejects small-order A' intentionally for SBS-style non-repudiation and to
|
|
621
|
+
// avoid ambiguous verification outcomes where unusual low-order keys can make distinct
|
|
622
|
+
// key/signature/message combinations verify.
|
|
623
|
+
if (!zip215 && A.isSmallOrder())
|
|
624
|
+
return false;
|
|
625
|
+
// ZIP-215 accepts noncanonical / unreduced point encodings, so the challenge hash must use the
|
|
626
|
+
// exact signature/public-key bytes rather than canonicalized re-encodings of the decoded points.
|
|
627
|
+
const k = hashDomainToScalar(context, r, publicKey, msg);
|
|
628
|
+
const RkA = R.add(A.multiplyUnsafe(k));
|
|
629
|
+
// Check the cofactored verification equation via the curve cofactor h.
|
|
630
|
+
// [h][S]B = [h]R + [h][k]A'
|
|
631
|
+
return RkA.subtract(SB).clearCofactor().is0();
|
|
632
|
+
}
|
|
633
|
+
const _size = Fp.BYTES; // 32 for ed25519, 57 for ed448
|
|
634
|
+
const lengths = {
|
|
635
|
+
secretKey: _size,
|
|
636
|
+
publicKey: _size,
|
|
637
|
+
signature: 2 * _size,
|
|
638
|
+
seed: _size,
|
|
639
|
+
};
|
|
640
|
+
function randomSecretKey(seed) {
|
|
641
|
+
seed = seed === undefined ? randomBytes(lengths.seed) : seed;
|
|
642
|
+
return (0, utils_1.abytes)(seed, lengths.seed, 'seed');
|
|
643
|
+
}
|
|
644
|
+
function isValidSecretKey(key) {
|
|
645
|
+
return (0, utils_1.isBytes)(key) && key.length === lengths.secretKey;
|
|
646
|
+
}
|
|
647
|
+
function isValidPublicKey(key, zip215) {
|
|
648
|
+
try {
|
|
649
|
+
// Preserve the wrapper-selected default for omitted / `undefined` ZIP-215 flags here too.
|
|
650
|
+
return !!Point.fromBytes(key, zip215 === undefined ? verifyOpts.zip215 : zip215);
|
|
651
|
+
}
|
|
652
|
+
catch (error) {
|
|
653
|
+
return false;
|
|
654
|
+
}
|
|
655
|
+
}
|
|
656
|
+
const utils = {
|
|
657
|
+
getExtendedPublicKey,
|
|
658
|
+
randomSecretKey,
|
|
659
|
+
isValidSecretKey,
|
|
660
|
+
isValidPublicKey,
|
|
661
|
+
/**
|
|
662
|
+
* Converts ed public key to x public key. Uses formula:
|
|
663
|
+
* - ed25519:
|
|
664
|
+
* - `(u, v) = ((1+y)/(1-y), sqrt(-486664)*u/x)`
|
|
665
|
+
* - `(x, y) = (sqrt(-486664)*u/v, (u-1)/(u+1))`
|
|
666
|
+
* - ed448:
|
|
667
|
+
* - `(u, v) = ((y-1)/(y+1), sqrt(156324)*u/x)`
|
|
668
|
+
* - `(x, y) = (sqrt(156324)*u/v, (1+u)/(1-u))`
|
|
669
|
+
*/
|
|
670
|
+
toMontgomery(publicKey) {
|
|
671
|
+
const { y } = Point.fromBytes(publicKey);
|
|
672
|
+
const size = lengths.publicKey;
|
|
673
|
+
const is25519 = size === 32;
|
|
674
|
+
if (!is25519 && size !== 57)
|
|
675
|
+
throw new Error('only defined for 25519 and 448');
|
|
676
|
+
const u = is25519 ? Fp.div(_1n + y, _1n - y) : Fp.div(y - _1n, y + _1n);
|
|
677
|
+
return Fp.toBytes(u);
|
|
678
|
+
},
|
|
679
|
+
toMontgomerySecret(secretKey) {
|
|
680
|
+
const size = lengths.secretKey;
|
|
681
|
+
(0, utils_1.abytes)(secretKey, size);
|
|
682
|
+
const hashed = hash(secretKey.subarray(0, size));
|
|
683
|
+
return adjustScalarBytes(hashed).subarray(0, size);
|
|
684
|
+
},
|
|
685
|
+
};
|
|
686
|
+
Object.freeze(lengths);
|
|
687
|
+
Object.freeze(utils);
|
|
688
|
+
return Object.freeze({
|
|
689
|
+
keygen: (0, curve_1.createKeygen)(randomSecretKey, getPublicKey),
|
|
690
|
+
getPublicKey,
|
|
691
|
+
sign,
|
|
692
|
+
verify,
|
|
693
|
+
utils,
|
|
694
|
+
Point,
|
|
695
|
+
lengths,
|
|
696
|
+
});
|
|
697
|
+
}
|