@ocap/mcrypto 1.30.24 → 1.30.25

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.
Files changed (51) hide show
  1. package/esm/crypter/aes-legacy.d.mts +11 -0
  2. package/esm/crypter/aes-legacy.mjs +67 -15
  3. package/esm/crypter/aes.d.mts +14 -2
  4. package/esm/crypter/aes.mjs +69 -3
  5. package/esm/encode.mjs +1 -1
  6. package/esm/hasher/keccak.mjs +7 -2
  7. package/esm/hasher/sha2.d.mts +1 -1
  8. package/esm/hasher/sha2.mjs +26 -11
  9. package/esm/hasher/sha3.d.mts +1 -1
  10. package/esm/hasher/sha3.mjs +21 -6
  11. package/esm/index.d.mts +1 -1
  12. package/esm/signer/ed25519.d.mts +1 -1
  13. package/esm/signer/ed25519.mjs +143 -16
  14. package/esm/signer/ethereum.mjs +7 -3
  15. package/esm/signer/secp256k1.mjs +3 -2
  16. package/esm/webauthn.d.mts +68 -2
  17. package/esm/webauthn.mjs +64 -16
  18. package/lib/_vendor/@noble/curves/LICENSE +21 -0
  19. package/lib/_vendor/@noble/curves/abstract/curve.cjs +373 -0
  20. package/lib/_vendor/@noble/curves/abstract/modular.cjs +616 -0
  21. package/lib/_vendor/@noble/curves/abstract/weierstrass.cjs +1020 -0
  22. package/lib/_vendor/@noble/curves/nist.cjs +91 -0
  23. package/lib/_vendor/@noble/curves/secp256k1.cjs +73 -0
  24. package/lib/_vendor/@noble/curves/utils.cjs +463 -0
  25. package/lib/_vendor/@noble/ed25519/LICENSE +21 -0
  26. package/lib/_vendor/@noble/ed25519/index.cjs +512 -0
  27. package/lib/_vendor/@noble/hashes/LICENSE +21 -0
  28. package/lib/_vendor/@noble/hashes/_md.cjs +230 -0
  29. package/lib/_vendor/@noble/hashes/_u64.cjs +67 -0
  30. package/lib/_vendor/@noble/hashes/hmac.cjs +86 -0
  31. package/lib/_vendor/@noble/hashes/sha2.cjs +477 -0
  32. package/lib/_vendor/@noble/hashes/sha3.cjs +329 -0
  33. package/lib/_vendor/@noble/hashes/utils.cjs +410 -0
  34. package/lib/crypter/aes-legacy.cjs +68 -21
  35. package/lib/crypter/aes-legacy.d.cts +11 -0
  36. package/lib/crypter/aes.cjs +69 -2
  37. package/lib/crypter/aes.d.cts +14 -2
  38. package/lib/encode.cjs +1 -1
  39. package/lib/hasher/keccak.cjs +13 -8
  40. package/lib/hasher/sha2.cjs +32 -17
  41. package/lib/hasher/sha2.d.cts +1 -1
  42. package/lib/hasher/sha3.cjs +27 -12
  43. package/lib/hasher/sha3.d.cts +1 -1
  44. package/lib/index.d.cts +1 -1
  45. package/lib/signer/ed25519.cjs +146 -20
  46. package/lib/signer/ed25519.d.cts +1 -1
  47. package/lib/signer/ethereum.cjs +16 -12
  48. package/lib/signer/secp256k1.cjs +11 -10
  49. package/lib/webauthn.cjs +80 -31
  50. package/lib/webauthn.d.cts +68 -2
  51. package/package.json +6 -7
@@ -0,0 +1,1020 @@
1
+ const require_utils = require('../../hashes/utils.cjs');
2
+ const require_utils$1 = require('../utils.cjs');
3
+ const require_modular = require('./modular.cjs');
4
+ const require_curve = require('./curve.cjs');
5
+ const require_hmac = require('../../hashes/hmac.cjs');
6
+
7
+ //#region ../../node_modules/@noble/curves/abstract/weierstrass.js
8
+ /**
9
+ * Short Weierstrass curve methods. The formula is: y² = x³ + ax + b.
10
+ *
11
+ * ### Design rationale for types
12
+ *
13
+ * * Interaction between classes from different curves should fail:
14
+ * `k256.Point.BASE.add(p256.Point.BASE)`
15
+ * * For this purpose we want to use `instanceof` operator, which is fast and works during runtime
16
+ * * Different calls of `curve()` would return different classes -
17
+ * `curve(params) !== curve(params)`: if somebody decided to monkey-patch their curve,
18
+ * it won't affect others
19
+ *
20
+ * TypeScript can't infer types for classes created inside a function. Classes is one instance
21
+ * of nominative types in TypeScript and interfaces only check for shape, so it's hard to create
22
+ * unique type for every function call.
23
+ *
24
+ * We can use generic types via some param, like curve opts, but that would:
25
+ * 1. Enable interaction between `curve(params)` and `curve(params)` (curves of same params)
26
+ * which is hard to debug.
27
+ * 2. Params can be generic and we can't enforce them to be constant value:
28
+ * if somebody creates curve from non-constant params,
29
+ * it would be allowed to interact with other curves with non-constant params
30
+ *
31
+ * @todo https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-7.html#unique-symbol
32
+ * @module
33
+ */
34
+ /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
35
+ const divNearest = (num, den) => (num + (num >= 0 ? den : -den) / _2n) / den;
36
+ /** Splits scalar for GLV endomorphism. */
37
+ function _splitEndoScalar(k, basis, n) {
38
+ require_utils$1.aInRange("scalar", k, _0n, n);
39
+ const [[a1, b1], [a2, b2]] = basis;
40
+ const c1 = divNearest(b2 * k, n);
41
+ const c2 = divNearest(-b1 * k, n);
42
+ let k1 = k - c1 * a1 - c2 * a2;
43
+ let k2 = -c1 * b1 - c2 * b2;
44
+ const k1neg = k1 < _0n;
45
+ const k2neg = k2 < _0n;
46
+ if (k1neg) k1 = -k1;
47
+ if (k2neg) k2 = -k2;
48
+ const MAX_NUM = require_utils$1.bitMask(Math.ceil(require_utils$1.bitLen(n) / 2)) + _1n;
49
+ if (k1 < _0n || k1 >= MAX_NUM || k2 < _0n || k2 >= MAX_NUM) throw new Error("splitScalar (endomorphism): failed for k");
50
+ return {
51
+ k1neg,
52
+ k1,
53
+ k2neg,
54
+ k2
55
+ };
56
+ }
57
+ function validateSigFormat(format) {
58
+ if (![
59
+ "compact",
60
+ "recovered",
61
+ "der"
62
+ ].includes(format)) throw new Error("Signature format must be \"compact\", \"recovered\", or \"der\"");
63
+ return format;
64
+ }
65
+ function validateSigOpts(opts, def) {
66
+ require_utils$1.validateObject(opts);
67
+ const optsn = {};
68
+ for (let optName of Object.keys(def)) optsn[optName] = opts[optName] === void 0 ? def[optName] : opts[optName];
69
+ require_utils$1.abool(optsn.lowS, "lowS");
70
+ require_utils$1.abool(optsn.prehash, "prehash");
71
+ if (optsn.format !== void 0) validateSigFormat(optsn.format);
72
+ return optsn;
73
+ }
74
+ /**
75
+ * @param m - Error message.
76
+ * @example
77
+ * Throw a DER-specific error when signature parsing encounters invalid bytes.
78
+ *
79
+ * ```ts
80
+ * new DERErr('bad der');
81
+ * ```
82
+ */
83
+ var DERErr = class extends Error {
84
+ constructor(m = "") {
85
+ super(m);
86
+ }
87
+ };
88
+ /**
89
+ * ASN.1 DER encoding utilities. ASN is very complex & fragile. Format:
90
+ *
91
+ * [0x30 (SEQUENCE), bytelength, 0x02 (INTEGER), intLength, R, 0x02 (INTEGER), intLength, S]
92
+ *
93
+ * Docs: {@link https://letsencrypt.org/docs/a-warm-welcome-to-asn1-and-der/ | Let's Encrypt ASN.1 guide} and
94
+ * {@link https://luca.ntop.org/Teaching/Appunti/asn1.html | Luca Deri's ASN.1 notes}.
95
+ * @example
96
+ * ASN.1 DER encoding utilities.
97
+ *
98
+ * ```ts
99
+ * const der = DER.hexFromSig({ r: 1n, s: 2n });
100
+ * ```
101
+ */
102
+ const DER = {
103
+ Err: DERErr,
104
+ _tlv: {
105
+ encode: (tag, data) => {
106
+ const { Err: E } = DER;
107
+ require_utils$1.asafenumber(tag, "tag");
108
+ if (tag < 0 || tag > 255) throw new E("tlv.encode: wrong tag");
109
+ if (typeof data !== "string") throw new TypeError("\"data\" expected string, got type=" + typeof data);
110
+ if (data.length & 1) throw new E("tlv.encode: unpadded data");
111
+ const dataLen = data.length / 2;
112
+ const len = require_utils$1.numberToHexUnpadded(dataLen);
113
+ if (len.length / 2 & 128) throw new E("tlv.encode: long form length too big");
114
+ const lenLen = dataLen > 127 ? require_utils$1.numberToHexUnpadded(len.length / 2 | 128) : "";
115
+ return require_utils$1.numberToHexUnpadded(tag) + lenLen + len + data;
116
+ },
117
+ decode(tag, data) {
118
+ const { Err: E } = DER;
119
+ data = require_utils$1.abytes(data, void 0, "DER data");
120
+ let pos = 0;
121
+ if (tag < 0 || tag > 255) throw new E("tlv.encode: wrong tag");
122
+ if (data.length < 2 || data[pos++] !== tag) throw new E("tlv.decode: wrong tlv");
123
+ const first = data[pos++];
124
+ const isLong = !!(first & 128);
125
+ let length = 0;
126
+ if (!isLong) length = first;
127
+ else {
128
+ const lenLen = first & 127;
129
+ if (!lenLen) throw new E("tlv.decode(long): indefinite length not supported");
130
+ if (lenLen > 4) throw new E("tlv.decode(long): byte length is too big");
131
+ const lengthBytes = data.subarray(pos, pos + lenLen);
132
+ if (lengthBytes.length !== lenLen) throw new E("tlv.decode: length bytes not complete");
133
+ if (lengthBytes[0] === 0) throw new E("tlv.decode(long): zero leftmost byte");
134
+ for (const b of lengthBytes) length = length << 8 | b;
135
+ pos += lenLen;
136
+ if (length < 128) throw new E("tlv.decode(long): not minimal encoding");
137
+ }
138
+ const v = data.subarray(pos, pos + length);
139
+ if (v.length !== length) throw new E("tlv.decode: wrong value length");
140
+ return {
141
+ v,
142
+ l: data.subarray(pos + length)
143
+ };
144
+ }
145
+ },
146
+ _int: {
147
+ encode(num) {
148
+ const { Err: E } = DER;
149
+ require_utils$1.abignumber(num);
150
+ if (num < _0n) throw new E("integer: negative integers are not allowed");
151
+ let hex = require_utils$1.numberToHexUnpadded(num);
152
+ if (Number.parseInt(hex[0], 16) & 8) hex = "00" + hex;
153
+ if (hex.length & 1) throw new E("unexpected DER parsing assertion: unpadded hex");
154
+ return hex;
155
+ },
156
+ decode(data) {
157
+ const { Err: E } = DER;
158
+ if (data.length < 1) throw new E("invalid signature integer: empty");
159
+ if (data[0] & 128) throw new E("invalid signature integer: negative");
160
+ if (data.length > 1 && data[0] === 0 && !(data[1] & 128)) throw new E("invalid signature integer: unnecessary leading zero");
161
+ return require_utils$1.bytesToNumberBE(data);
162
+ }
163
+ },
164
+ toSig(bytes) {
165
+ const { Err: E, _int: int, _tlv: tlv } = DER;
166
+ const data = require_utils$1.abytes(bytes, void 0, "signature");
167
+ const { v: seqBytes, l: seqLeftBytes } = tlv.decode(48, data);
168
+ if (seqLeftBytes.length) throw new E("invalid signature: left bytes after parsing");
169
+ const { v: rBytes, l: rLeftBytes } = tlv.decode(2, seqBytes);
170
+ const { v: sBytes, l: sLeftBytes } = tlv.decode(2, rLeftBytes);
171
+ if (sLeftBytes.length) throw new E("invalid signature: left bytes after parsing");
172
+ return {
173
+ r: int.decode(rBytes),
174
+ s: int.decode(sBytes)
175
+ };
176
+ },
177
+ hexFromSig(sig) {
178
+ const { _tlv: tlv, _int: int } = DER;
179
+ const seq = tlv.encode(2, int.encode(sig.r)) + tlv.encode(2, int.encode(sig.s));
180
+ return tlv.encode(48, seq);
181
+ }
182
+ };
183
+ Object.freeze(DER._tlv);
184
+ Object.freeze(DER._int);
185
+ Object.freeze(DER);
186
+ const _0n = /* @__PURE__ */ BigInt(0), _1n = /* @__PURE__ */ BigInt(1), _2n = /* @__PURE__ */ BigInt(2), _3n = /* @__PURE__ */ BigInt(3), _4n = /* @__PURE__ */ BigInt(4);
187
+ /**
188
+ * Creates weierstrass Point constructor, based on specified curve options.
189
+ *
190
+ * See {@link WeierstrassOpts}.
191
+ * @param params - Curve parameters. See {@link WeierstrassOpts}.
192
+ * @param extraOpts - Optional helpers and overrides. See {@link WeierstrassExtraOpts}.
193
+ * @returns Weierstrass point constructor.
194
+ * @throws If the curve parameters, overrides, or point codecs are invalid. {@link Error}
195
+ *
196
+ * @example
197
+ * Construct a point type from explicit Weierstrass curve parameters.
198
+ *
199
+ * ```js
200
+ * const opts = {
201
+ * p: 0xfffffffffffffffffffffffffffffffeffffac73n,
202
+ * n: 0x100000000000000000001b8fa16dfab9aca16b6b3n,
203
+ * h: 1n,
204
+ * a: 0n,
205
+ * b: 7n,
206
+ * Gx: 0x3b4c382ce37aa192a4019e763036f4f5dd4d7ebbn,
207
+ * Gy: 0x938cf935318fdced6bc28286531733c3f03c4feen,
208
+ * };
209
+ * const secp160k1_Point = weierstrass(opts);
210
+ * ```
211
+ */
212
+ function weierstrass(params, extraOpts = {}) {
213
+ const validated = require_curve.createCurveFields("weierstrass", params, extraOpts);
214
+ const Fp = validated.Fp;
215
+ const Fn = validated.Fn;
216
+ let CURVE = validated.CURVE;
217
+ const { h: cofactor, n: CURVE_ORDER } = CURVE;
218
+ require_utils$1.validateObject(extraOpts, {}, {
219
+ allowInfinityPoint: "boolean",
220
+ clearCofactor: "function",
221
+ isTorsionFree: "function",
222
+ fromBytes: "function",
223
+ toBytes: "function",
224
+ endo: "object"
225
+ });
226
+ const { endo, allowInfinityPoint } = extraOpts;
227
+ if (endo) {
228
+ if (!Fp.is0(CURVE.a) || typeof endo.beta !== "bigint" || !Array.isArray(endo.basises)) throw new Error("invalid endo: expected \"beta\": bigint and \"basises\": array");
229
+ }
230
+ const lengths = getWLengths(Fp, Fn);
231
+ function assertCompressionIsSupported() {
232
+ if (!Fp.isOdd) throw new Error("compression is not supported: Field does not have .isOdd()");
233
+ }
234
+ function pointToBytes(_c, point, isCompressed) {
235
+ if (allowInfinityPoint && point.is0()) return Uint8Array.of(0);
236
+ const { x, y } = point.toAffine();
237
+ const bx = Fp.toBytes(x);
238
+ require_utils$1.abool(isCompressed, "isCompressed");
239
+ if (isCompressed) {
240
+ assertCompressionIsSupported();
241
+ return require_utils$1.concatBytes(pprefix(!Fp.isOdd(y)), bx);
242
+ } else return require_utils$1.concatBytes(Uint8Array.of(4), bx, Fp.toBytes(y));
243
+ }
244
+ function pointFromBytes(bytes) {
245
+ require_utils$1.abytes(bytes, void 0, "Point");
246
+ const { publicKey: comp, publicKeyUncompressed: uncomp } = lengths;
247
+ const length = bytes.length;
248
+ const head = bytes[0];
249
+ const tail = bytes.subarray(1);
250
+ if (allowInfinityPoint && length === 1 && head === 0) return {
251
+ x: Fp.ZERO,
252
+ y: Fp.ZERO
253
+ };
254
+ if (length === comp && (head === 2 || head === 3)) {
255
+ const x = Fp.fromBytes(tail);
256
+ if (!Fp.isValid(x)) throw new Error("bad point: is not on curve, wrong x");
257
+ const y2 = weierstrassEquation(x);
258
+ let y;
259
+ try {
260
+ y = Fp.sqrt(y2);
261
+ } catch (sqrtError) {
262
+ const err = sqrtError instanceof Error ? ": " + sqrtError.message : "";
263
+ throw new Error("bad point: is not on curve, sqrt error" + err);
264
+ }
265
+ assertCompressionIsSupported();
266
+ const evenY = Fp.isOdd(y);
267
+ if ((head & 1) === 1 !== evenY) y = Fp.neg(y);
268
+ return {
269
+ x,
270
+ y
271
+ };
272
+ } else if (length === uncomp && head === 4) {
273
+ const L = Fp.BYTES;
274
+ const x = Fp.fromBytes(tail.subarray(0, L));
275
+ const y = Fp.fromBytes(tail.subarray(L, L * 2));
276
+ if (!isValidXY(x, y)) throw new Error("bad point: is not on curve");
277
+ return {
278
+ x,
279
+ y
280
+ };
281
+ } else throw new Error(`bad point: got length ${length}, expected compressed=${comp} or uncompressed=${uncomp}`);
282
+ }
283
+ const encodePoint = extraOpts.toBytes === void 0 ? pointToBytes : extraOpts.toBytes;
284
+ const decodePoint = extraOpts.fromBytes === void 0 ? pointFromBytes : extraOpts.fromBytes;
285
+ function weierstrassEquation(x) {
286
+ const x2 = Fp.sqr(x);
287
+ const x3 = Fp.mul(x2, x);
288
+ return Fp.add(Fp.add(x3, Fp.mul(x, CURVE.a)), CURVE.b);
289
+ }
290
+ /** Checks whether equation holds for given x, y: y² == x³ + ax + b */
291
+ function isValidXY(x, y) {
292
+ const left = Fp.sqr(y);
293
+ const right = weierstrassEquation(x);
294
+ return Fp.eql(left, right);
295
+ }
296
+ if (!isValidXY(CURVE.Gx, CURVE.Gy)) throw new Error("bad curve params: generator point");
297
+ const _4a3 = Fp.mul(Fp.pow(CURVE.a, _3n), _4n);
298
+ const _27b2 = Fp.mul(Fp.sqr(CURVE.b), BigInt(27));
299
+ if (Fp.is0(Fp.add(_4a3, _27b2))) throw new Error("bad curve params: a or b");
300
+ /** Asserts coordinate is valid: 0 <= n < Fp.ORDER. */
301
+ function acoord(title, n, banZero = false) {
302
+ if (!Fp.isValid(n) || banZero && Fp.is0(n)) throw new Error(`bad point coordinate ${title}`);
303
+ return n;
304
+ }
305
+ function aprjpoint(other) {
306
+ if (!(other instanceof Point)) throw new Error("Weierstrass Point expected");
307
+ }
308
+ function splitEndoScalarN(k) {
309
+ if (!endo || !endo.basises) throw new Error("no endo");
310
+ return _splitEndoScalar(k, endo.basises, Fn.ORDER);
311
+ }
312
+ function finishEndo(endoBeta, k1p, k2p, k1neg, k2neg) {
313
+ k2p = new Point(Fp.mul(k2p.X, endoBeta), k2p.Y, k2p.Z);
314
+ k1p = require_curve.negateCt(k1neg, k1p);
315
+ k2p = require_curve.negateCt(k2neg, k2p);
316
+ return k1p.add(k2p);
317
+ }
318
+ /**
319
+ * Projective Point works in 3d / projective (homogeneous) coordinates:(X, Y, Z) ∋ (x=X/Z, y=Y/Z).
320
+ * Default Point works in 2d / affine coordinates: (x, y).
321
+ * We're doing calculations in projective, because its operations don't require costly inversion.
322
+ */
323
+ class Point {
324
+ static BASE = new Point(CURVE.Gx, CURVE.Gy, Fp.ONE);
325
+ static ZERO = new Point(Fp.ZERO, Fp.ONE, Fp.ZERO);
326
+ static Fp = Fp;
327
+ static Fn = Fn;
328
+ X;
329
+ Y;
330
+ Z;
331
+ /** Does NOT validate if the point is valid. Use `.assertValidity()`. */
332
+ constructor(X, Y, Z) {
333
+ this.X = acoord("x", X);
334
+ this.Y = acoord("y", Y, true);
335
+ this.Z = acoord("z", Z);
336
+ Object.freeze(this);
337
+ }
338
+ static CURVE() {
339
+ return CURVE;
340
+ }
341
+ /** Does NOT validate if the point is valid. Use `.assertValidity()`. */
342
+ static fromAffine(p) {
343
+ const { x, y } = p || {};
344
+ if (!p || !Fp.isValid(x) || !Fp.isValid(y)) throw new Error("invalid affine point");
345
+ if (p instanceof Point) throw new Error("projective point not allowed");
346
+ if (Fp.is0(x) && Fp.is0(y)) return Point.ZERO;
347
+ return new Point(x, y, Fp.ONE);
348
+ }
349
+ static fromBytes(bytes) {
350
+ const P = Point.fromAffine(decodePoint(require_utils$1.abytes(bytes, void 0, "point")));
351
+ P.assertValidity();
352
+ return P;
353
+ }
354
+ static fromHex(hex) {
355
+ return Point.fromBytes(require_utils$1.hexToBytes(hex));
356
+ }
357
+ get x() {
358
+ return this.toAffine().x;
359
+ }
360
+ get y() {
361
+ return this.toAffine().y;
362
+ }
363
+ /**
364
+ *
365
+ * @param windowSize
366
+ * @param isLazy - true will defer table computation until the first multiplication
367
+ * @returns
368
+ */
369
+ precompute(windowSize = 8, isLazy = true) {
370
+ wnaf.createCache(this, windowSize);
371
+ if (!isLazy) this.multiply(_3n);
372
+ return this;
373
+ }
374
+ /** A point on curve is valid if it conforms to equation. */
375
+ assertValidity() {
376
+ const p = this;
377
+ if (p.is0()) {
378
+ if (extraOpts.allowInfinityPoint && Fp.is0(p.X) && Fp.eql(p.Y, Fp.ONE) && Fp.is0(p.Z)) return;
379
+ throw new Error("bad point: ZERO");
380
+ }
381
+ const { x, y } = p.toAffine();
382
+ if (!Fp.isValid(x) || !Fp.isValid(y)) throw new Error("bad point: x or y not field elements");
383
+ if (!isValidXY(x, y)) throw new Error("bad point: equation left != right");
384
+ if (!p.isTorsionFree()) throw new Error("bad point: not in prime-order subgroup");
385
+ }
386
+ hasEvenY() {
387
+ const { y } = this.toAffine();
388
+ if (!Fp.isOdd) throw new Error("Field doesn't support isOdd");
389
+ return !Fp.isOdd(y);
390
+ }
391
+ /** Compare one point to another. */
392
+ equals(other) {
393
+ aprjpoint(other);
394
+ const { X: X1, Y: Y1, Z: Z1 } = this;
395
+ const { X: X2, Y: Y2, Z: Z2 } = other;
396
+ const U1 = Fp.eql(Fp.mul(X1, Z2), Fp.mul(X2, Z1));
397
+ const U2 = Fp.eql(Fp.mul(Y1, Z2), Fp.mul(Y2, Z1));
398
+ return U1 && U2;
399
+ }
400
+ /** Flips point to one corresponding to (x, -y) in Affine coordinates. */
401
+ negate() {
402
+ return new Point(this.X, Fp.neg(this.Y), this.Z);
403
+ }
404
+ double() {
405
+ const { a, b } = CURVE;
406
+ const b3 = Fp.mul(b, _3n);
407
+ const { X: X1, Y: Y1, Z: Z1 } = this;
408
+ let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO;
409
+ let t0 = Fp.mul(X1, X1);
410
+ let t1 = Fp.mul(Y1, Y1);
411
+ let t2 = Fp.mul(Z1, Z1);
412
+ let t3 = Fp.mul(X1, Y1);
413
+ t3 = Fp.add(t3, t3);
414
+ Z3 = Fp.mul(X1, Z1);
415
+ Z3 = Fp.add(Z3, Z3);
416
+ X3 = Fp.mul(a, Z3);
417
+ Y3 = Fp.mul(b3, t2);
418
+ Y3 = Fp.add(X3, Y3);
419
+ X3 = Fp.sub(t1, Y3);
420
+ Y3 = Fp.add(t1, Y3);
421
+ Y3 = Fp.mul(X3, Y3);
422
+ X3 = Fp.mul(t3, X3);
423
+ Z3 = Fp.mul(b3, Z3);
424
+ t2 = Fp.mul(a, t2);
425
+ t3 = Fp.sub(t0, t2);
426
+ t3 = Fp.mul(a, t3);
427
+ t3 = Fp.add(t3, Z3);
428
+ Z3 = Fp.add(t0, t0);
429
+ t0 = Fp.add(Z3, t0);
430
+ t0 = Fp.add(t0, t2);
431
+ t0 = Fp.mul(t0, t3);
432
+ Y3 = Fp.add(Y3, t0);
433
+ t2 = Fp.mul(Y1, Z1);
434
+ t2 = Fp.add(t2, t2);
435
+ t0 = Fp.mul(t2, t3);
436
+ X3 = Fp.sub(X3, t0);
437
+ Z3 = Fp.mul(t2, t1);
438
+ Z3 = Fp.add(Z3, Z3);
439
+ Z3 = Fp.add(Z3, Z3);
440
+ return new Point(X3, Y3, Z3);
441
+ }
442
+ add(other) {
443
+ aprjpoint(other);
444
+ const { X: X1, Y: Y1, Z: Z1 } = this;
445
+ const { X: X2, Y: Y2, Z: Z2 } = other;
446
+ let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO;
447
+ const a = CURVE.a;
448
+ const b3 = Fp.mul(CURVE.b, _3n);
449
+ let t0 = Fp.mul(X1, X2);
450
+ let t1 = Fp.mul(Y1, Y2);
451
+ let t2 = Fp.mul(Z1, Z2);
452
+ let t3 = Fp.add(X1, Y1);
453
+ let t4 = Fp.add(X2, Y2);
454
+ t3 = Fp.mul(t3, t4);
455
+ t4 = Fp.add(t0, t1);
456
+ t3 = Fp.sub(t3, t4);
457
+ t4 = Fp.add(X1, Z1);
458
+ let t5 = Fp.add(X2, Z2);
459
+ t4 = Fp.mul(t4, t5);
460
+ t5 = Fp.add(t0, t2);
461
+ t4 = Fp.sub(t4, t5);
462
+ t5 = Fp.add(Y1, Z1);
463
+ X3 = Fp.add(Y2, Z2);
464
+ t5 = Fp.mul(t5, X3);
465
+ X3 = Fp.add(t1, t2);
466
+ t5 = Fp.sub(t5, X3);
467
+ Z3 = Fp.mul(a, t4);
468
+ X3 = Fp.mul(b3, t2);
469
+ Z3 = Fp.add(X3, Z3);
470
+ X3 = Fp.sub(t1, Z3);
471
+ Z3 = Fp.add(t1, Z3);
472
+ Y3 = Fp.mul(X3, Z3);
473
+ t1 = Fp.add(t0, t0);
474
+ t1 = Fp.add(t1, t0);
475
+ t2 = Fp.mul(a, t2);
476
+ t4 = Fp.mul(b3, t4);
477
+ t1 = Fp.add(t1, t2);
478
+ t2 = Fp.sub(t0, t2);
479
+ t2 = Fp.mul(a, t2);
480
+ t4 = Fp.add(t4, t2);
481
+ t0 = Fp.mul(t1, t4);
482
+ Y3 = Fp.add(Y3, t0);
483
+ t0 = Fp.mul(t5, t4);
484
+ X3 = Fp.mul(t3, X3);
485
+ X3 = Fp.sub(X3, t0);
486
+ t0 = Fp.mul(t3, t1);
487
+ Z3 = Fp.mul(t5, Z3);
488
+ Z3 = Fp.add(Z3, t0);
489
+ return new Point(X3, Y3, Z3);
490
+ }
491
+ subtract(other) {
492
+ aprjpoint(other);
493
+ return this.add(other.negate());
494
+ }
495
+ is0() {
496
+ return this.equals(Point.ZERO);
497
+ }
498
+ /**
499
+ * Constant time multiplication.
500
+ * Uses wNAF method. Windowed method may be 10% faster,
501
+ * but takes 2x longer to generate and consumes 2x memory.
502
+ * Uses precomputes when available.
503
+ * Uses endomorphism for Koblitz curves.
504
+ * @param scalar - by which the point would be multiplied
505
+ * @returns New point
506
+ */
507
+ multiply(scalar) {
508
+ const { endo: endo$1 } = extraOpts;
509
+ if (!Fn.isValidNot0(scalar)) throw new RangeError("invalid scalar: out of range");
510
+ let point, fake;
511
+ const mul = (n) => wnaf.cached(this, n, (p) => require_curve.normalizeZ(Point, p));
512
+ /** See docs for {@link EndomorphismOpts} */
513
+ if (endo$1) {
514
+ const { k1neg, k1, k2neg, k2 } = splitEndoScalarN(scalar);
515
+ const { p: k1p, f: k1f } = mul(k1);
516
+ const { p: k2p, f: k2f } = mul(k2);
517
+ fake = k1f.add(k2f);
518
+ point = finishEndo(endo$1.beta, k1p, k2p, k1neg, k2neg);
519
+ } else {
520
+ const { p, f } = mul(scalar);
521
+ point = p;
522
+ fake = f;
523
+ }
524
+ return require_curve.normalizeZ(Point, [point, fake])[0];
525
+ }
526
+ /**
527
+ * Non-constant-time multiplication. Uses double-and-add algorithm.
528
+ * It's faster, but should only be used when you don't care about
529
+ * an exposed secret key e.g. sig verification, which works over *public* keys.
530
+ */
531
+ multiplyUnsafe(scalar) {
532
+ const { endo: endo$1 } = extraOpts;
533
+ const p = this;
534
+ const sc = scalar;
535
+ if (!Fn.isValid(sc)) throw new RangeError("invalid scalar: out of range");
536
+ if (sc === _0n || p.is0()) return Point.ZERO;
537
+ if (sc === _1n) return p;
538
+ if (wnaf.hasCache(this)) return this.multiply(sc);
539
+ if (endo$1) {
540
+ const { k1neg, k1, k2neg, k2 } = splitEndoScalarN(sc);
541
+ const { p1, p2 } = require_curve.mulEndoUnsafe(Point, p, k1, k2);
542
+ return finishEndo(endo$1.beta, p1, p2, k1neg, k2neg);
543
+ } else return wnaf.unsafe(p, sc);
544
+ }
545
+ /**
546
+ * Converts Projective point to affine (x, y) coordinates.
547
+ * (X, Y, Z) ∋ (x=X/Z, y=Y/Z).
548
+ * @param invertedZ - Z^-1 (inverted zero) - optional, precomputation is useful for invertBatch
549
+ */
550
+ toAffine(invertedZ) {
551
+ const p = this;
552
+ let iz = invertedZ;
553
+ const { X, Y, Z } = p;
554
+ if (Fp.eql(Z, Fp.ONE)) return {
555
+ x: X,
556
+ y: Y
557
+ };
558
+ const is0 = p.is0();
559
+ if (iz == null) iz = is0 ? Fp.ONE : Fp.inv(Z);
560
+ const x = Fp.mul(X, iz);
561
+ const y = Fp.mul(Y, iz);
562
+ const zz = Fp.mul(Z, iz);
563
+ if (is0) return {
564
+ x: Fp.ZERO,
565
+ y: Fp.ZERO
566
+ };
567
+ if (!Fp.eql(zz, Fp.ONE)) throw new Error("invZ was invalid");
568
+ return {
569
+ x,
570
+ y
571
+ };
572
+ }
573
+ /**
574
+ * Checks whether Point is free of torsion elements (is in prime subgroup).
575
+ * Always torsion-free for cofactor=1 curves.
576
+ */
577
+ isTorsionFree() {
578
+ const { isTorsionFree } = extraOpts;
579
+ if (cofactor === _1n) return true;
580
+ if (isTorsionFree) return isTorsionFree(Point, this);
581
+ return wnaf.unsafe(this, CURVE_ORDER).is0();
582
+ }
583
+ clearCofactor() {
584
+ const { clearCofactor } = extraOpts;
585
+ if (cofactor === _1n) return this;
586
+ if (clearCofactor) return clearCofactor(Point, this);
587
+ return this.multiplyUnsafe(cofactor);
588
+ }
589
+ isSmallOrder() {
590
+ if (cofactor === _1n) return this.is0();
591
+ return this.clearCofactor().is0();
592
+ }
593
+ toBytes(isCompressed = true) {
594
+ require_utils$1.abool(isCompressed, "isCompressed");
595
+ this.assertValidity();
596
+ return encodePoint(Point, this, isCompressed);
597
+ }
598
+ toHex(isCompressed = true) {
599
+ return require_utils$1.bytesToHex(this.toBytes(isCompressed));
600
+ }
601
+ toString() {
602
+ return `<Point ${this.is0() ? "ZERO" : this.toHex()}>`;
603
+ }
604
+ }
605
+ const bits = Fn.BITS;
606
+ const wnaf = new require_curve.wNAF(Point, extraOpts.endo ? Math.ceil(bits / 2) : bits);
607
+ if (bits >= 8) Point.BASE.precompute(8);
608
+ Object.freeze(Point.prototype);
609
+ Object.freeze(Point);
610
+ return Point;
611
+ }
612
+ function pprefix(hasEvenY) {
613
+ return Uint8Array.of(hasEvenY ? 2 : 3);
614
+ }
615
+ function getWLengths(Fp, Fn) {
616
+ return {
617
+ secretKey: Fn.BYTES,
618
+ publicKey: 1 + Fp.BYTES,
619
+ publicKeyUncompressed: 1 + 2 * Fp.BYTES,
620
+ publicKeyHasPrefix: true,
621
+ signature: 2 * Fn.BYTES
622
+ };
623
+ }
624
+ /**
625
+ * Sometimes users only need getPublicKey, getSharedSecret, and secret key handling.
626
+ * This helper ensures no signature functionality is present. Less code, smaller bundle size.
627
+ * @param Point - Weierstrass point constructor.
628
+ * @param ecdhOpts - Optional randomness helpers:
629
+ * - `randomBytes` (optional): Optional RNG override.
630
+ * @returns ECDH helper namespace.
631
+ * @example
632
+ * Sometimes users only need getPublicKey, getSharedSecret, and secret key handling.
633
+ *
634
+ * ```ts
635
+ * import { ecdh } from '@noble/curves/abstract/weierstrass.js';
636
+ * import { p256 } from '@noble/curves/nist.js';
637
+ * const dh = ecdh(p256.Point);
638
+ * const alice = dh.keygen();
639
+ * const shared = dh.getSharedSecret(alice.secretKey, alice.publicKey);
640
+ * ```
641
+ */
642
+ function ecdh(Point, ecdhOpts = {}) {
643
+ const { Fn } = Point;
644
+ const randomBytes_ = ecdhOpts.randomBytes === void 0 ? require_utils$1.randomBytes : ecdhOpts.randomBytes;
645
+ const lengths = Object.assign(getWLengths(Point.Fp, Fn), { seed: Math.max(require_modular.getMinHashLength(Fn.ORDER), 16) });
646
+ function isValidSecretKey(secretKey) {
647
+ try {
648
+ const num = Fn.fromBytes(secretKey);
649
+ return Fn.isValidNot0(num);
650
+ } catch (error) {
651
+ return false;
652
+ }
653
+ }
654
+ function isValidPublicKey(publicKey, isCompressed) {
655
+ const { publicKey: comp, publicKeyUncompressed } = lengths;
656
+ try {
657
+ const l = publicKey.length;
658
+ if (isCompressed === true && l !== comp) return false;
659
+ if (isCompressed === false && l !== publicKeyUncompressed) return false;
660
+ return !!Point.fromBytes(publicKey);
661
+ } catch (error) {
662
+ return false;
663
+ }
664
+ }
665
+ /**
666
+ * Produces cryptographically secure secret key from random of size
667
+ * (groupLen + ceil(groupLen / 2)) with modulo bias being negligible.
668
+ */
669
+ function randomSecretKey(seed) {
670
+ seed = seed === void 0 ? randomBytes_(lengths.seed) : seed;
671
+ return require_modular.mapHashToField(require_utils$1.abytes(seed, lengths.seed, "seed"), Fn.ORDER);
672
+ }
673
+ /**
674
+ * Computes public key for a secret key. Checks for validity of the secret key.
675
+ * @param isCompressed - whether to return compact (default), or full key
676
+ * @returns Public key, full when isCompressed=false; short when isCompressed=true
677
+ */
678
+ function getPublicKey(secretKey, isCompressed = true) {
679
+ return Point.BASE.multiply(Fn.fromBytes(secretKey)).toBytes(isCompressed);
680
+ }
681
+ /**
682
+ * Quick and dirty check for item being public key. Does not validate hex, or being on-curve.
683
+ */
684
+ function isProbPub(item) {
685
+ const { secretKey, publicKey, publicKeyUncompressed } = lengths;
686
+ const allowedLengths = Fn._lengths;
687
+ if (!require_utils$1.isBytes(item)) return void 0;
688
+ const l = require_utils$1.abytes(item, void 0, "key").length;
689
+ const isPub = l === publicKey || l === publicKeyUncompressed;
690
+ const isSec = l === secretKey || !!allowedLengths?.includes(l);
691
+ if (isPub && isSec) return void 0;
692
+ return isPub;
693
+ }
694
+ /**
695
+ * ECDH (Elliptic Curve Diffie Hellman).
696
+ * Computes encoded shared point from secret key A and public key B.
697
+ * Checks: 1) secret key validity 2) shared key is on-curve.
698
+ * Does NOT hash the result or expose the SEC 1 x-coordinate-only `z`.
699
+ * Returns the encoded shared point on purpose: callers that need `x_P`
700
+ * can derive it from the encoded point, but `x_P` alone cannot recover the
701
+ * point/parity back.
702
+ * This helper only exposes the fully validated public-key path, not cofactor DH.
703
+ * @param isCompressed - whether to return compact (default), or full key
704
+ * @returns shared point encoding
705
+ */
706
+ function getSharedSecret(secretKeyA, publicKeyB, isCompressed = true) {
707
+ if (isProbPub(secretKeyA) === true) throw new Error("first arg must be private key");
708
+ if (isProbPub(publicKeyB) === false) throw new Error("second arg must be public key");
709
+ const s = Fn.fromBytes(secretKeyA);
710
+ return Point.fromBytes(publicKeyB).multiply(s).toBytes(isCompressed);
711
+ }
712
+ const utils = {
713
+ isValidSecretKey,
714
+ isValidPublicKey,
715
+ randomSecretKey
716
+ };
717
+ const keygen = require_curve.createKeygen(randomSecretKey, getPublicKey);
718
+ Object.freeze(utils);
719
+ Object.freeze(lengths);
720
+ return Object.freeze({
721
+ getPublicKey,
722
+ getSharedSecret,
723
+ keygen,
724
+ Point,
725
+ utils,
726
+ lengths
727
+ });
728
+ }
729
+ /**
730
+ * Creates ECDSA signing interface for given elliptic curve `Point` and `hash` function.
731
+ *
732
+ * @param Point - created using {@link weierstrass} function
733
+ * @param hash - used for 1) message prehash-ing 2) k generation in `sign`, using hmac_drbg(hash)
734
+ * @param ecdsaOpts - rarely needed, see {@link ECDSAOpts}:
735
+ * - `lowS`: Default low-S policy.
736
+ * - `hmac`: HMAC implementation used by RFC6979 DRBG.
737
+ * - `randomBytes`: Optional RNG override.
738
+ * - `bits2int`: Optional hash-to-int conversion override.
739
+ * - `bits2int_modN`: Optional hash-to-int-mod-n conversion override.
740
+ *
741
+ * @returns ECDSA helper namespace.
742
+ * @example
743
+ * Create an ECDSA signer/verifier bundle for one curve implementation.
744
+ *
745
+ * ```ts
746
+ * import { ecdsa } from '@noble/curves/abstract/weierstrass.js';
747
+ * import { p256 } from '@noble/curves/nist.js';
748
+ * import { sha256 } from '@noble/hashes/sha2.js';
749
+ * const p256ecdsa = ecdsa(p256.Point, sha256);
750
+ * const { secretKey, publicKey } = p256ecdsa.keygen();
751
+ * const msg = new TextEncoder().encode('hello noble');
752
+ * const sig = p256ecdsa.sign(msg, secretKey);
753
+ * const isValid = p256ecdsa.verify(sig, msg, publicKey);
754
+ * ```
755
+ */
756
+ function ecdsa(Point, hash, ecdsaOpts = {}) {
757
+ const hash_ = hash;
758
+ require_utils.ahash(hash_);
759
+ require_utils$1.validateObject(ecdsaOpts, {}, {
760
+ hmac: "function",
761
+ lowS: "boolean",
762
+ randomBytes: "function",
763
+ bits2int: "function",
764
+ bits2int_modN: "function"
765
+ });
766
+ ecdsaOpts = Object.assign({}, ecdsaOpts);
767
+ const randomBytes$1 = ecdsaOpts.randomBytes === void 0 ? require_utils$1.randomBytes : ecdsaOpts.randomBytes;
768
+ const hmac$1 = ecdsaOpts.hmac === void 0 ? (key, msg) => require_hmac.hmac(hash_, key, msg) : ecdsaOpts.hmac;
769
+ const { Fp, Fn } = Point;
770
+ const { ORDER: CURVE_ORDER, BITS: fnBits } = Fn;
771
+ const { keygen, getPublicKey, getSharedSecret, utils, lengths } = ecdh(Point, ecdsaOpts);
772
+ const defaultSigOpts = {
773
+ prehash: true,
774
+ lowS: typeof ecdsaOpts.lowS === "boolean" ? ecdsaOpts.lowS : true,
775
+ format: "compact",
776
+ extraEntropy: false
777
+ };
778
+ const hasLargeRecoveryLifts = CURVE_ORDER * _2n + _1n < Fp.ORDER;
779
+ function isBiggerThanHalfOrder(number) {
780
+ return number > CURVE_ORDER >> _1n;
781
+ }
782
+ function validateRS(title, num) {
783
+ if (!Fn.isValidNot0(num)) throw new Error(`invalid signature ${title}: out of range 1..Point.Fn.ORDER`);
784
+ return num;
785
+ }
786
+ function assertRecoverableCurve() {
787
+ if (hasLargeRecoveryLifts) throw new Error("\"recovered\" sig type is not supported for cofactor >2 curves");
788
+ }
789
+ function validateSigLength(bytes, format) {
790
+ validateSigFormat(format);
791
+ const size = lengths.signature;
792
+ return require_utils$1.abytes(bytes, format === "compact" ? size : format === "recovered" ? size + 1 : void 0);
793
+ }
794
+ /**
795
+ * ECDSA signature with its (r, s) properties. Supports compact, recovered & DER representations.
796
+ */
797
+ class Signature {
798
+ r;
799
+ s;
800
+ recovery;
801
+ constructor(r, s, recovery) {
802
+ this.r = validateRS("r", r);
803
+ this.s = validateRS("s", s);
804
+ if (recovery != null) {
805
+ assertRecoverableCurve();
806
+ if (![
807
+ 0,
808
+ 1,
809
+ 2,
810
+ 3
811
+ ].includes(recovery)) throw new Error("invalid recovery id");
812
+ this.recovery = recovery;
813
+ }
814
+ Object.freeze(this);
815
+ }
816
+ static fromBytes(bytes, format = defaultSigOpts.format) {
817
+ validateSigLength(bytes, format);
818
+ let recid;
819
+ if (format === "der") {
820
+ const { r: r$1, s: s$1 } = DER.toSig(require_utils$1.abytes(bytes));
821
+ return new Signature(r$1, s$1);
822
+ }
823
+ if (format === "recovered") {
824
+ recid = bytes[0];
825
+ format = "compact";
826
+ bytes = bytes.subarray(1);
827
+ }
828
+ const L = lengths.signature / 2;
829
+ const r = bytes.subarray(0, L);
830
+ const s = bytes.subarray(L, L * 2);
831
+ return new Signature(Fn.fromBytes(r), Fn.fromBytes(s), recid);
832
+ }
833
+ static fromHex(hex, format) {
834
+ return this.fromBytes(require_utils$1.hexToBytes(hex), format);
835
+ }
836
+ assertRecovery() {
837
+ const { recovery } = this;
838
+ if (recovery == null) throw new Error("invalid recovery id: must be present");
839
+ return recovery;
840
+ }
841
+ addRecoveryBit(recovery) {
842
+ return new Signature(this.r, this.s, recovery);
843
+ }
844
+ recoverPublicKey(messageHash) {
845
+ const { r, s } = this;
846
+ const recovery = this.assertRecovery();
847
+ const radj = recovery === 2 || recovery === 3 ? r + CURVE_ORDER : r;
848
+ if (!Fp.isValid(radj)) throw new Error("invalid recovery id: sig.r+curve.n != R.x");
849
+ const x = Fp.toBytes(radj);
850
+ const R = Point.fromBytes(require_utils$1.concatBytes(pprefix((recovery & 1) === 0), x));
851
+ const ir = Fn.inv(radj);
852
+ const h = bits2int_modN(require_utils$1.abytes(messageHash, void 0, "msgHash"));
853
+ const u1 = Fn.create(-h * ir);
854
+ const u2 = Fn.create(s * ir);
855
+ const Q = Point.BASE.multiplyUnsafe(u1).add(R.multiplyUnsafe(u2));
856
+ if (Q.is0()) throw new Error("invalid recovery: point at infinify");
857
+ Q.assertValidity();
858
+ return Q;
859
+ }
860
+ hasHighS() {
861
+ return isBiggerThanHalfOrder(this.s);
862
+ }
863
+ toBytes(format = defaultSigOpts.format) {
864
+ validateSigFormat(format);
865
+ if (format === "der") return require_utils$1.hexToBytes(DER.hexFromSig(this));
866
+ const { r, s } = this;
867
+ const rb = Fn.toBytes(r);
868
+ const sb = Fn.toBytes(s);
869
+ if (format === "recovered") {
870
+ assertRecoverableCurve();
871
+ return require_utils$1.concatBytes(Uint8Array.of(this.assertRecovery()), rb, sb);
872
+ }
873
+ return require_utils$1.concatBytes(rb, sb);
874
+ }
875
+ toHex(format) {
876
+ return require_utils$1.bytesToHex(this.toBytes(format));
877
+ }
878
+ }
879
+ Object.freeze(Signature.prototype);
880
+ Object.freeze(Signature);
881
+ const bits2int = ecdsaOpts.bits2int === void 0 ? function bits2int_def(bytes) {
882
+ if (bytes.length > 8192) throw new Error("input is too large");
883
+ const num = require_utils$1.bytesToNumberBE(bytes);
884
+ const delta = bytes.length * 8 - fnBits;
885
+ return delta > 0 ? num >> BigInt(delta) : num;
886
+ } : ecdsaOpts.bits2int;
887
+ const bits2int_modN = ecdsaOpts.bits2int_modN === void 0 ? function bits2int_modN_def(bytes) {
888
+ return Fn.create(bits2int(bytes));
889
+ } : ecdsaOpts.bits2int_modN;
890
+ const ORDER_MASK = require_utils$1.bitMask(fnBits);
891
+ /** Converts to bytes. Checks if num in `[0..ORDER_MASK-1]` e.g.: `[0..2^256-1]`. */
892
+ function int2octets(num) {
893
+ require_utils$1.aInRange("num < 2^" + fnBits, num, _0n, ORDER_MASK);
894
+ return Fn.toBytes(num);
895
+ }
896
+ function validateMsgAndHash(message, prehash) {
897
+ require_utils$1.abytes(message, void 0, "message");
898
+ return prehash ? require_utils$1.abytes(hash_(message), void 0, "prehashed message") : message;
899
+ }
900
+ /**
901
+ * Steps A, D of RFC6979 3.2.
902
+ * Creates RFC6979 seed; converts msg/privKey to numbers.
903
+ * Used only in sign, not in verify.
904
+ *
905
+ * Warning: we cannot assume here that message has same amount of bytes as curve order,
906
+ * this will be invalid at least for P521. Also it can be bigger for P224 + SHA256.
907
+ */
908
+ function prepSig(message, secretKey, opts) {
909
+ const { lowS, prehash, extraEntropy } = validateSigOpts(opts, defaultSigOpts);
910
+ message = validateMsgAndHash(message, prehash);
911
+ const h1int = bits2int_modN(message);
912
+ const d = Fn.fromBytes(secretKey);
913
+ if (!Fn.isValidNot0(d)) throw new Error("invalid private key");
914
+ const seedArgs = [int2octets(d), int2octets(h1int)];
915
+ if (extraEntropy != null && extraEntropy !== false) {
916
+ const e = extraEntropy === true ? randomBytes$1(lengths.secretKey) : extraEntropy;
917
+ seedArgs.push(require_utils$1.abytes(e, void 0, "extraEntropy"));
918
+ }
919
+ const seed = require_utils$1.concatBytes(...seedArgs);
920
+ const m = h1int;
921
+ function k2sig(kBytes) {
922
+ const k = bits2int(kBytes);
923
+ if (!Fn.isValidNot0(k)) return;
924
+ const ik = Fn.inv(k);
925
+ const q = Point.BASE.multiply(k).toAffine();
926
+ const r = Fn.create(q.x);
927
+ if (r === _0n) return;
928
+ const s = Fn.create(ik * Fn.create(m + r * d));
929
+ if (s === _0n) return;
930
+ let recovery = (q.x === r ? 0 : 2) | Number(q.y & _1n);
931
+ let normS = s;
932
+ if (lowS && isBiggerThanHalfOrder(s)) {
933
+ normS = Fn.neg(s);
934
+ recovery ^= 1;
935
+ }
936
+ return new Signature(r, normS, hasLargeRecoveryLifts ? void 0 : recovery);
937
+ }
938
+ return {
939
+ seed,
940
+ k2sig
941
+ };
942
+ }
943
+ /**
944
+ * Signs a message or message hash with a secret key.
945
+ * With the default `prehash: true`, raw message bytes are hashed internally;
946
+ * only `{ prehash: false }` expects a caller-supplied digest.
947
+ *
948
+ * ```
949
+ * sign(m, d) where
950
+ * k = rfc6979_hmac_drbg(m, d)
951
+ * (x, y) = G × k
952
+ * r = x mod n
953
+ * s = (m + dr) / k mod n
954
+ * ```
955
+ */
956
+ function sign(message, secretKey, opts = {}) {
957
+ const { seed, k2sig } = prepSig(message, secretKey, opts);
958
+ return require_utils$1.createHmacDrbg(hash_.outputLen, Fn.BYTES, hmac$1)(seed, k2sig).toBytes(opts.format);
959
+ }
960
+ /**
961
+ * Verifies a signature against message and public key.
962
+ * Rejects lowS signatures by default: see {@link ECDSAVerifyOpts}.
963
+ * Implements section 4.1.4 from https://www.secg.org/sec1-v2.pdf:
964
+ *
965
+ * ```
966
+ * verify(r, s, h, P) where
967
+ * u1 = hs^-1 mod n
968
+ * u2 = rs^-1 mod n
969
+ * R = u1⋅G + u2⋅P
970
+ * mod(R.x, n) == r
971
+ * ```
972
+ */
973
+ function verify(signature, message, publicKey, opts = {}) {
974
+ const { lowS, prehash, format } = validateSigOpts(opts, defaultSigOpts);
975
+ publicKey = require_utils$1.abytes(publicKey, void 0, "publicKey");
976
+ message = validateMsgAndHash(message, prehash);
977
+ if (!require_utils$1.isBytes(signature)) {
978
+ const end = signature instanceof Signature ? ", use sig.toBytes()" : "";
979
+ throw new Error("verify expects Uint8Array signature" + end);
980
+ }
981
+ validateSigLength(signature, format);
982
+ try {
983
+ const sig = Signature.fromBytes(signature, format);
984
+ const P = Point.fromBytes(publicKey);
985
+ if (lowS && sig.hasHighS()) return false;
986
+ const { r, s } = sig;
987
+ const h = bits2int_modN(message);
988
+ const is = Fn.inv(s);
989
+ const u1 = Fn.create(h * is);
990
+ const u2 = Fn.create(r * is);
991
+ const R = Point.BASE.multiplyUnsafe(u1).add(P.multiplyUnsafe(u2));
992
+ if (R.is0()) return false;
993
+ return Fn.create(R.x) === r;
994
+ } catch (e) {
995
+ return false;
996
+ }
997
+ }
998
+ function recoverPublicKey(signature, message, opts = {}) {
999
+ const { prehash } = validateSigOpts(opts, defaultSigOpts);
1000
+ message = validateMsgAndHash(message, prehash);
1001
+ return Signature.fromBytes(signature, "recovered").recoverPublicKey(message).toBytes();
1002
+ }
1003
+ return Object.freeze({
1004
+ keygen,
1005
+ getPublicKey,
1006
+ getSharedSecret,
1007
+ utils,
1008
+ lengths,
1009
+ Point,
1010
+ sign,
1011
+ verify,
1012
+ recoverPublicKey,
1013
+ Signature,
1014
+ hash: hash_
1015
+ });
1016
+ }
1017
+
1018
+ //#endregion
1019
+ exports.ecdsa = ecdsa;
1020
+ exports.weierstrass = weierstrass;