@ohos-ports/crypto 0.0.0-stage → 0.3.1-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (121) hide show
  1. package/LICENSE +7 -0
  2. package/README.md +60 -2
  3. package/dist/bech32.d.ts +53 -0
  4. package/dist/bech32.js +187 -0
  5. package/dist/blake2b.d.ts +7 -0
  6. package/dist/blake2b.js +213 -0
  7. package/dist/bls12_318.d.ts +48 -0
  8. package/dist/bls12_318.js +268 -0
  9. package/dist/ed25519.d.ts +55 -0
  10. package/dist/ed25519.js +721 -0
  11. package/dist/hasGlobalWebCrypto.d.ts +1 -0
  12. package/dist/hasGlobalWebCrypto.js +21 -0
  13. package/dist/hmacSHA512.d.ts +6 -0
  14. package/dist/hmacSHA512.js +14 -0
  15. package/dist/index.d.ts +14 -0
  16. package/dist/index.js +30 -0
  17. package/dist/keccak.d.ts +4 -0
  18. package/dist/keccak.js +43 -0
  19. package/dist/kes/constants.d.ts +2 -0
  20. package/dist/kes/constants.js +5 -0
  21. package/dist/kes/index.d.ts +0 -0
  22. package/dist/kes/index.js +0 -0
  23. package/dist/kes/macro/sum_kes.d.ts +15 -0
  24. package/dist/kes/macro/sum_kes.js +9 -0
  25. package/dist/kes/singleKes.d.ts +0 -0
  26. package/dist/kes/singleKes.js +0 -0
  27. package/dist/noble/_assert.d.ts +23 -0
  28. package/dist/noble/_assert.js +55 -0
  29. package/dist/noble/_md.d.ts +29 -0
  30. package/dist/noble/_md.js +170 -0
  31. package/dist/noble/_shortw_utils.d.ts +61 -0
  32. package/dist/noble/_shortw_utils.js +63 -0
  33. package/dist/noble/_u64.d.ts +28 -0
  34. package/dist/noble/_u64.js +116 -0
  35. package/dist/noble/abstract/bls.d.ts +119 -0
  36. package/dist/noble/abstract/bls.js +334 -0
  37. package/dist/noble/abstract/curve.d.ts +83 -0
  38. package/dist/noble/abstract/curve.js +319 -0
  39. package/dist/noble/abstract/edwards.d.ts +85 -0
  40. package/dist/noble/abstract/edwards.js +508 -0
  41. package/dist/noble/abstract/hash-to-curve.d.ts +57 -0
  42. package/dist/noble/abstract/hash-to-curve.js +220 -0
  43. package/dist/noble/abstract/modular.d.ts +122 -0
  44. package/dist/noble/abstract/modular.js +455 -0
  45. package/dist/noble/abstract/montgomery.d.ts +28 -0
  46. package/dist/noble/abstract/montgomery.js +172 -0
  47. package/dist/noble/abstract/utils.d.ts +106 -0
  48. package/dist/noble/abstract/utils.js +442 -0
  49. package/dist/noble/bls12_381.d.ts +95 -0
  50. package/dist/noble/bls12_381.js +1434 -0
  51. package/dist/noble/crypto.d.ts +1 -0
  52. package/dist/noble/crypto.js +4 -0
  53. package/dist/noble/curves/curve.d.ts +69 -0
  54. package/dist/noble/curves/curve.js +167 -0
  55. package/dist/noble/curves/modular.d.ts +122 -0
  56. package/dist/noble/curves/modular.js +442 -0
  57. package/dist/noble/curves/utils.d.ts +93 -0
  58. package/dist/noble/curves/utils.js +385 -0
  59. package/dist/noble/curves/weierstrass.d.ts +240 -0
  60. package/dist/noble/curves/weierstrass.js +1178 -0
  61. package/dist/noble/ed25519.d.ts +100 -0
  62. package/dist/noble/ed25519.js +494 -0
  63. package/dist/noble/hmac.d.ts +25 -0
  64. package/dist/noble/hmac.js +101 -0
  65. package/dist/noble/index.d.ts +2 -0
  66. package/dist/noble/index.js +20 -0
  67. package/dist/noble/keccak.d.ts +58 -0
  68. package/dist/noble/keccak.js +289 -0
  69. package/dist/noble/ripemd_160.d.ts +20 -0
  70. package/dist/noble/ripemd_160.js +147 -0
  71. package/dist/noble/secp256k1.d.ts +98 -0
  72. package/dist/noble/secp256k1.js +309 -0
  73. package/dist/noble/sha256.d.ts +34 -0
  74. package/dist/noble/sha256.js +146 -0
  75. package/dist/noble/sha512.d.ts +66 -0
  76. package/dist/noble/sha512.js +301 -0
  77. package/dist/noble/utils.d.ts +90 -0
  78. package/dist/noble/utils.js +278 -0
  79. package/dist/ripemd_160.d.ts +1 -0
  80. package/dist/ripemd_160.js +23 -0
  81. package/dist/rust_vrf_reimpl/curves.d.ts +162 -0
  82. package/dist/rust_vrf_reimpl/curves.js +4225 -0
  83. package/dist/rust_vrf_reimpl/vrf03.d.ts +60 -0
  84. package/dist/rust_vrf_reimpl/vrf03.js +373 -0
  85. package/dist/rust_vrf_reimpl/vrf10.d.ts +73 -0
  86. package/dist/rust_vrf_reimpl/vrf10.js +468 -0
  87. package/dist/rust_vrf_reimpl/vrf10_batch.d.ts +53 -0
  88. package/dist/rust_vrf_reimpl/vrf10_batch.js +245 -0
  89. package/dist/secp256k1.d.ts +4 -0
  90. package/dist/secp256k1.js +33 -0
  91. package/dist/sha2_256.d.ts +16 -0
  92. package/dist/sha2_256.js +403 -0
  93. package/dist/sha2_512.d.ts +16 -0
  94. package/dist/sha2_512.js +256 -0
  95. package/dist/sha3.d.ts +17 -0
  96. package/dist/sha3.js +181 -0
  97. package/dist/types.d.ts +26 -0
  98. package/dist/types.js +120 -0
  99. package/dist/utils/assert.d.ts +3 -0
  100. package/dist/utils/assert.js +55 -0
  101. package/dist/utils/base32.d.ts +5 -0
  102. package/dist/utils/base32.js +52 -0
  103. package/dist/utils/bigintToBuffer.d.ts +1 -0
  104. package/dist/utils/bigintToBuffer.js +27 -0
  105. package/dist/utils/bytesToHex.d.ts +2 -0
  106. package/dist/utils/bytesToHex.js +15 -0
  107. package/dist/utils/getRandomValues.d.ts +4 -0
  108. package/dist/utils/getRandomValues.js +12 -0
  109. package/dist/utils/hexToBytes.d.ts +2 -0
  110. package/dist/utils/hexToBytes.js +14 -0
  111. package/dist/utils/index.d.ts +3 -0
  112. package/dist/utils/index.js +19 -0
  113. package/dist/utils/positiveMod.d.ts +1 -0
  114. package/dist/utils/positiveMod.js +11 -0
  115. package/dist/utils/promisifySync.d.ts +0 -0
  116. package/dist/utils/promisifySync.js +0 -0
  117. package/dist/utils/rotr32.d.ts +2 -0
  118. package/dist/utils/rotr32.js +7 -0
  119. package/dist/vrf.d.ts +74 -0
  120. package/dist/vrf.js +286 -0
  121. package/package.json +49 -4
@@ -0,0 +1,508 @@
1
+ "use strict";
2
+ var __assign = (this && this.__assign) || function () {
3
+ __assign = Object.assign || function(t) {
4
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
5
+ s = arguments[i];
6
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
7
+ t[p] = s[p];
8
+ }
9
+ return t;
10
+ };
11
+ return __assign.apply(this, arguments);
12
+ };
13
+ var __read = (this && this.__read) || function (o, n) {
14
+ var m = typeof Symbol === "function" && o[Symbol.iterator];
15
+ if (!m) return o;
16
+ var i = m.call(o), r, ar = [], e;
17
+ try {
18
+ while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
19
+ }
20
+ catch (error) { e = { error: error }; }
21
+ finally {
22
+ try {
23
+ if (r && !r.done && (m = i["return"])) m.call(i);
24
+ }
25
+ finally { if (e) throw e.error; }
26
+ }
27
+ return ar;
28
+ };
29
+ var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
30
+ if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
31
+ if (ar || !(i in from)) {
32
+ if (!ar) ar = Array.prototype.slice.call(from, 0, i);
33
+ ar[i] = from[i];
34
+ }
35
+ }
36
+ return to.concat(ar || Array.prototype.slice.call(from));
37
+ };
38
+ Object.defineProperty(exports, "__esModule", { value: true });
39
+ exports.twistedEdwards = void 0;
40
+ /**
41
+ * Twisted Edwards curve. The formula is: ax² + y² = 1 + dx²y².
42
+ * For design rationale of types / exports, see weierstrass module documentation.
43
+ * @module
44
+ */
45
+ /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
46
+ var uint8array_utils_1 = require("@harmoniclabs/uint8array-utils");
47
+ var curve_1 = require("./curve.js");
48
+ var modular_js_1 = require("./modular.js");
49
+ var utils_js_1 = require("./utils.js");
50
+ // Be friendly to bad ECMAScript parsers by not using bigint literals
51
+ // prettier-ignore
52
+ var _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _8n = BigInt(8);
53
+ // verification rule is either zip215 or rfc8032 / nist186-5. Consult fromHex:
54
+ var VERIFY_DEFAULT = { zip215: true };
55
+ function validateOpts(curve) {
56
+ var opts = (0, curve_1.validateBasic)(curve);
57
+ (0, utils_js_1.validateObject)(curve, {
58
+ hash: 'function',
59
+ a: 'bigint',
60
+ d: 'bigint',
61
+ randomBytes: 'function',
62
+ }, {
63
+ adjustScalarBytes: 'function',
64
+ domain: 'function',
65
+ uvRatio: 'function',
66
+ mapToCurve: 'function',
67
+ });
68
+ // Set defaults
69
+ return Object.freeze(__assign({}, opts));
70
+ }
71
+ /**
72
+ * Creates Twisted Edwards curve with EdDSA signatures.
73
+ * @example
74
+ * import { Field } from '@noble/curves/abstract/modular';
75
+ * // Before that, define BigInt-s: a, d, p, n, Gx, Gy, h
76
+ * const curve = twistedEdwards({ a, d, Fp: Field(p), n, Gx, Gy, h })
77
+ */
78
+ function twistedEdwards(curveDef) {
79
+ var CURVE = validateOpts(curveDef);
80
+ var Fp = CURVE.Fp, CURVE_ORDER = CURVE.n, prehash = CURVE.prehash, cHash = CURVE.hash, randomBytes = CURVE.randomBytes, nByteLength = CURVE.nByteLength, cofactor = CURVE.h;
81
+ // Important:
82
+ // There are some places where Fp.BYTES is used instead of nByteLength.
83
+ // So far, everything has been tested with curves of Fp.BYTES == nByteLength.
84
+ // TODO: test and find curves which behave otherwise.
85
+ var MASK = _2n << (BigInt(nByteLength * 8) - _1n);
86
+ var modP = Fp.create; // Function overrides
87
+ var Fn = (0, modular_js_1.Field)(CURVE.n, CURVE.nBitLength);
88
+ // sqrt(u/v)
89
+ var uvRatio = CURVE.uvRatio ||
90
+ (function (u, v) {
91
+ try {
92
+ return { isValid: true, value: Fp.sqrt(u * Fp.inv(v)) };
93
+ }
94
+ catch (e) {
95
+ return { isValid: false, value: _0n };
96
+ }
97
+ });
98
+ var adjustScalarBytes = CURVE.adjustScalarBytes || (function (bytes) { return bytes; }); // NOOP
99
+ var domain = CURVE.domain ||
100
+ (function (data, ctx, phflag) {
101
+ (0, utils_js_1.abool)('phflag', phflag);
102
+ if (ctx.length || phflag)
103
+ throw new Error('Contexts/pre-hash are not supported');
104
+ return data;
105
+ }); // NOOP
106
+ // 0 <= n < MASK
107
+ // Coordinates larger than Fp.ORDER are allowed for zip215
108
+ function aCoordinate(title, n) {
109
+ (0, utils_js_1.aInRange)('coordinate ' + title, n, _0n, MASK);
110
+ }
111
+ function assertPoint(other) {
112
+ if (!(other instanceof Point))
113
+ throw new Error('ExtendedPoint expected');
114
+ }
115
+ // Converts Extended point to default (x, y) coordinates.
116
+ // Can accept precomputed Z^-1 - for example, from invertBatch.
117
+ var toAffineMemo = (0, utils_js_1.memoized)(function (p, iz) {
118
+ var x = p.ex, y = p.ey, z = p.ez;
119
+ var is0 = p.is0();
120
+ if (iz == null)
121
+ iz = is0 ? _8n : Fp.inv(z); // 8 was chosen arbitrarily
122
+ var ax = modP(x * iz);
123
+ var ay = modP(y * iz);
124
+ var zz = modP(z * iz);
125
+ if (is0)
126
+ return { x: _0n, y: _1n };
127
+ if (zz !== _1n)
128
+ throw new Error('invZ was invalid');
129
+ return { x: ax, y: ay };
130
+ });
131
+ var assertValidMemo = (0, utils_js_1.memoized)(function (p) {
132
+ var a = CURVE.a, d = CURVE.d;
133
+ if (p.is0())
134
+ throw new Error('bad point: ZERO'); // TODO: optimize, with vars below?
135
+ // Equation in affine coordinates: ax² + y² = 1 + dx²y²
136
+ // Equation in projective coordinates (X/Z, Y/Z, Z): (aX² + Y²)Z² = Z⁴ + dX²Y²
137
+ var X = p.ex, Y = p.ey, Z = p.ez, T = p.et;
138
+ var X2 = modP(X * X); // X²
139
+ var Y2 = modP(Y * Y); // Y²
140
+ var Z2 = modP(Z * Z); // Z²
141
+ var Z4 = modP(Z2 * Z2); // Z⁴
142
+ var aX2 = modP(X2 * a); // aX²
143
+ var left = modP(Z2 * modP(aX2 + Y2)); // (aX² + Y²)Z²
144
+ var right = modP(Z4 + modP(d * modP(X2 * Y2))); // Z⁴ + dX²Y²
145
+ if (left !== right)
146
+ throw new Error('bad point: equation left != right (1)');
147
+ // In Extended coordinates we also have T, which is x*y=T/Z: check X*Y == Z*T
148
+ var XY = modP(X * Y);
149
+ var ZT = modP(Z * T);
150
+ if (XY !== ZT)
151
+ throw new Error('bad point: equation left != right (2)');
152
+ return true;
153
+ });
154
+ // Extended Point works in extended coordinates: (x, y, z, t) ∋ (x=x/z, y=y/z, t=xy).
155
+ // https://en.wikipedia.org/wiki/Twisted_Edwards_curve#Extended_coordinates
156
+ var Point = /** @class */ (function () {
157
+ function Point(ex, ey, ez, et) {
158
+ aCoordinate('x', ex);
159
+ aCoordinate('y', ey);
160
+ aCoordinate('z', ez);
161
+ aCoordinate('t', et);
162
+ this.ex = ex;
163
+ this.ey = ey;
164
+ this.ez = ez;
165
+ this.et = et;
166
+ Object.freeze(this);
167
+ }
168
+ Object.defineProperty(Point.prototype, "x", {
169
+ get: function () {
170
+ return this.toAffine().x;
171
+ },
172
+ enumerable: false,
173
+ configurable: true
174
+ });
175
+ Object.defineProperty(Point.prototype, "y", {
176
+ get: function () {
177
+ return this.toAffine().y;
178
+ },
179
+ enumerable: false,
180
+ configurable: true
181
+ });
182
+ Point.fromAffine = function (p) {
183
+ if (p instanceof Point)
184
+ throw new Error('extended point not allowed');
185
+ var _a = p || {}, x = _a.x, y = _a.y;
186
+ aCoordinate('x', x);
187
+ aCoordinate('y', y);
188
+ return new Point(x, y, _1n, modP(x * y));
189
+ };
190
+ Point.normalizeZ = function (points) {
191
+ var toInv = Fp.invertBatch(points.map(function (p) { return p.ez; }));
192
+ return points.map(function (p, i) { return p.toAffine(toInv[i]); }).map(Point.fromAffine);
193
+ };
194
+ // Multiscalar Multiplication
195
+ Point.msm = function (points, scalars) {
196
+ return (0, curve_1.pippenger)(Point, Fn, points, scalars);
197
+ };
198
+ // "Private method", don't use it directly
199
+ Point.prototype._setWindowSize = function (windowSize) {
200
+ wnaf.setWindowSize(this, windowSize);
201
+ };
202
+ // Not required for fromHex(), which always creates valid points.
203
+ // Could be useful for fromAffine().
204
+ Point.prototype.assertValidity = function () {
205
+ assertValidMemo(this);
206
+ };
207
+ // Compare one point to another.
208
+ Point.prototype.equals = function (other) {
209
+ assertPoint(other);
210
+ var _a = this, X1 = _a.ex, Y1 = _a.ey, Z1 = _a.ez;
211
+ var X2 = other.ex, Y2 = other.ey, Z2 = other.ez;
212
+ var X1Z2 = modP(X1 * Z2);
213
+ var X2Z1 = modP(X2 * Z1);
214
+ var Y1Z2 = modP(Y1 * Z2);
215
+ var Y2Z1 = modP(Y2 * Z1);
216
+ return X1Z2 === X2Z1 && Y1Z2 === Y2Z1;
217
+ };
218
+ Point.prototype.is0 = function () {
219
+ return this.equals(Point.ZERO);
220
+ };
221
+ Point.prototype.negate = function () {
222
+ // Flips point sign to a negative one (-x, y in affine coords)
223
+ return new Point(modP(-this.ex), this.ey, this.ez, modP(-this.et));
224
+ };
225
+ // Fast algo for doubling Extended Point.
226
+ // https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#doubling-dbl-2008-hwcd
227
+ // Cost: 4M + 4S + 1*a + 6add + 1*2.
228
+ Point.prototype.double = function () {
229
+ var a = CURVE.a;
230
+ var _a = this, X1 = _a.ex, Y1 = _a.ey, Z1 = _a.ez;
231
+ var A = modP(X1 * X1); // A = X12
232
+ var B = modP(Y1 * Y1); // B = Y12
233
+ var C = modP(_2n * modP(Z1 * Z1)); // C = 2*Z12
234
+ var D = modP(a * A); // D = a*A
235
+ var x1y1 = X1 + Y1;
236
+ var E = modP(modP(x1y1 * x1y1) - A - B); // E = (X1+Y1)2-A-B
237
+ var G = D + B; // G = D+B
238
+ var F = G - C; // F = G-C
239
+ var H = D - B; // H = D-B
240
+ var X3 = modP(E * F); // X3 = E*F
241
+ var Y3 = modP(G * H); // Y3 = G*H
242
+ var T3 = modP(E * H); // T3 = E*H
243
+ var Z3 = modP(F * G); // Z3 = F*G
244
+ return new Point(X3, Y3, Z3, T3);
245
+ };
246
+ // Fast algo for adding 2 Extended Points.
247
+ // https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#addition-add-2008-hwcd
248
+ // Cost: 9M + 1*a + 1*d + 7add.
249
+ Point.prototype.add = function (other) {
250
+ assertPoint(other);
251
+ var a = CURVE.a, d = CURVE.d;
252
+ var _a = this, X1 = _a.ex, Y1 = _a.ey, Z1 = _a.ez, T1 = _a.et;
253
+ var X2 = other.ex, Y2 = other.ey, Z2 = other.ez, T2 = other.et;
254
+ // Faster algo for adding 2 Extended Points when curve's a=-1.
255
+ // http://hyperelliptic.org/EFD/g1p/auto-twisted-extended-1.html#addition-add-2008-hwcd-4
256
+ // Cost: 8M + 8add + 2*2.
257
+ // Note: It does not check whether the `other` point is valid.
258
+ if (a === BigInt(-1)) {
259
+ var A_1 = modP((Y1 - X1) * (Y2 + X2));
260
+ var B_1 = modP((Y1 + X1) * (Y2 - X2));
261
+ var F_1 = modP(B_1 - A_1);
262
+ if (F_1 === _0n)
263
+ return this.double(); // Same point. Tests say it doesn't affect timing
264
+ var C_1 = modP(Z1 * _2n * T2);
265
+ var D_1 = modP(T1 * _2n * Z2);
266
+ var E_1 = D_1 + C_1;
267
+ var G_1 = B_1 + A_1;
268
+ var H_1 = D_1 - C_1;
269
+ var X3_1 = modP(E_1 * F_1);
270
+ var Y3_1 = modP(G_1 * H_1);
271
+ var T3_1 = modP(E_1 * H_1);
272
+ var Z3_1 = modP(F_1 * G_1);
273
+ return new Point(X3_1, Y3_1, Z3_1, T3_1);
274
+ }
275
+ var A = modP(X1 * X2); // A = X1*X2
276
+ var B = modP(Y1 * Y2); // B = Y1*Y2
277
+ var C = modP(T1 * d * T2); // C = T1*d*T2
278
+ var D = modP(Z1 * Z2); // D = Z1*Z2
279
+ var E = modP((X1 + Y1) * (X2 + Y2) - A - B); // E = (X1+Y1)*(X2+Y2)-A-B
280
+ var F = D - C; // F = D-C
281
+ var G = D + C; // G = D+C
282
+ var H = modP(B - a * A); // H = B-a*A
283
+ var X3 = modP(E * F); // X3 = E*F
284
+ var Y3 = modP(G * H); // Y3 = G*H
285
+ var T3 = modP(E * H); // T3 = E*H
286
+ var Z3 = modP(F * G); // Z3 = F*G
287
+ return new Point(X3, Y3, Z3, T3);
288
+ };
289
+ Point.prototype.subtract = function (other) {
290
+ return this.add(other.negate());
291
+ };
292
+ Point.prototype.wNAF = function (n) {
293
+ return wnaf.wNAFCached(this, n, Point.normalizeZ);
294
+ };
295
+ // Constant-time multiplication.
296
+ Point.prototype.multiply = function (scalar) {
297
+ var n = scalar;
298
+ (0, utils_js_1.aInRange)('scalar', n, _1n, CURVE_ORDER); // 1 <= scalar < L
299
+ var _a = this.wNAF(n), p = _a.p, f = _a.f;
300
+ return Point.normalizeZ([p, f])[0];
301
+ };
302
+ // Non-constant-time multiplication. Uses double-and-add algorithm.
303
+ // It's faster, but should only be used when you don't care about
304
+ // an exposed private key e.g. sig verification.
305
+ // Does NOT allow scalars higher than CURVE.n.
306
+ // Accepts optional accumulator to merge with multiply (important for sparse scalars)
307
+ Point.prototype.multiplyUnsafe = function (scalar, acc) {
308
+ if (acc === void 0) { acc = Point.ZERO; }
309
+ var n = scalar;
310
+ (0, utils_js_1.aInRange)('scalar', n, _0n, CURVE_ORDER); // 0 <= scalar < L
311
+ if (n === _0n)
312
+ return I;
313
+ if (this.is0() || n === _1n)
314
+ return this;
315
+ return wnaf.wNAFCachedUnsafe(this, n, Point.normalizeZ, acc);
316
+ };
317
+ // Checks if point is of small order.
318
+ // If you add something to small order point, you will have "dirty"
319
+ // point with torsion component.
320
+ // Multiplies point by cofactor and checks if the result is 0.
321
+ Point.prototype.isSmallOrder = function () {
322
+ return this.multiplyUnsafe(cofactor).is0();
323
+ };
324
+ // Multiplies point by curve order and checks if the result is 0.
325
+ // Returns `false` is the point is dirty.
326
+ Point.prototype.isTorsionFree = function () {
327
+ return wnaf.unsafeLadder(this, CURVE_ORDER).is0();
328
+ };
329
+ // Converts Extended point to default (x, y) coordinates.
330
+ // Can accept precomputed Z^-1 - for example, from invertBatch.
331
+ Point.prototype.toAffine = function (iz) {
332
+ return toAffineMemo(this, iz);
333
+ };
334
+ Point.prototype.clearCofactor = function () {
335
+ var cofactor = CURVE.h;
336
+ if (cofactor === _1n)
337
+ return this;
338
+ return this.multiplyUnsafe(cofactor);
339
+ };
340
+ // Converts hash string or Uint8Array to Point.
341
+ // Uses algo from RFC8032 5.1.3.
342
+ Point.fromHex = function (hex, zip215) {
343
+ if (zip215 === void 0) { zip215 = false; }
344
+ var d = CURVE.d, a = CURVE.a;
345
+ var len = Fp.BYTES;
346
+ hex = (0, utils_js_1.ensureBytes)('pointHex', hex, len); // copy hex to a new array
347
+ (0, utils_js_1.abool)('zip215', zip215);
348
+ var normed = hex.slice(); // copy again, we'll manipulate it
349
+ var lastByte = hex[len - 1]; // select last byte
350
+ normed[len - 1] = lastByte & ~0x80; // clear last bit
351
+ var y = (0, utils_js_1.bytesToNumberLE)(normed);
352
+ // zip215=true is good for consensus-critical apps. =false follows RFC8032 / NIST186-5.
353
+ // RFC8032 prohibits >= p, but ZIP215 doesn't
354
+ // zip215=true: 0 <= y < MASK (2^256 for ed25519)
355
+ // zip215=false: 0 <= y < P (2^255-19 for ed25519)
356
+ var max = zip215 ? MASK : Fp.ORDER;
357
+ (0, utils_js_1.aInRange)('pointHex.y', y, _0n, max);
358
+ // Ed25519: x² = (y²-1)/(dy²+1) mod p. Ed448: x² = (y²-1)/(dy²-1) mod p. Generic case:
359
+ // ax²+y²=1+dx²y² => y²-1=dx²y²-ax² => y²-1=x²(dy²-a) => x²=(y²-1)/(dy²-a)
360
+ var y2 = modP(y * y); // denominator is always non-0 mod p.
361
+ var u = modP(y2 - _1n); // u = y² - 1
362
+ var v = modP(d * y2 - a); // v = d y² + 1.
363
+ var _a = uvRatio(u, v), isValid = _a.isValid, x = _a.value; // √(u/v)
364
+ if (!isValid)
365
+ throw new Error('Point.fromHex: invalid y coordinate');
366
+ var isXOdd = (x & _1n) === _1n; // There are 2 square roots. Use x_0 bit to select proper
367
+ var isLastByteOdd = (lastByte & 0x80) !== 0; // x_0, last bit
368
+ if (!zip215 && x === _0n && isLastByteOdd)
369
+ // if x=0 and x_0 = 1, fail
370
+ throw new Error('Point.fromHex: x=0 and x_0=1');
371
+ if (isLastByteOdd !== isXOdd)
372
+ x = modP(-x); // if x_0 != x mod 2, set x = p-x
373
+ return Point.fromAffine({ x: x, y: y });
374
+ };
375
+ Point.fromPrivateKey = function (privKey) {
376
+ return getExtendedPublicKey(privKey).point;
377
+ };
378
+ Point.prototype.toRawBytes = function () {
379
+ var _a = this.toAffine(), x = _a.x, y = _a.y;
380
+ var bytes = (0, utils_js_1.numberToBytesLE)(y, Fp.BYTES); // each y has 2 x values (x, -y)
381
+ bytes[bytes.length - 1] |= x & _1n ? 0x80 : 0; // when compressing, it's enough to store y
382
+ return bytes; // and use the last byte to encode sign of x
383
+ };
384
+ Point.prototype.toHex = function () {
385
+ return (0, uint8array_utils_1.toHex)(this.toRawBytes()); // Same as toRawBytes, but returns string.
386
+ };
387
+ Point.BASE = new Point(CURVE.Gx, CURVE.Gy, _1n, modP(CURVE.Gx * CURVE.Gy));
388
+ Point.ZERO = new Point(_0n, _1n, _1n, _0n); // 0, 1, 1, 0
389
+ return Point;
390
+ }());
391
+ var G = Point.BASE, I = Point.ZERO;
392
+ var wnaf = (0, curve_1.wNAF)(Point, nByteLength * 8);
393
+ function modN(a) {
394
+ return (0, modular_js_1.mod)(a, CURVE_ORDER);
395
+ }
396
+ // Little-endian SHA512 with modulo n
397
+ function modN_LE(hash) {
398
+ return modN((0, utils_js_1.bytesToNumberLE)(hash));
399
+ }
400
+ /** Convenience method that creates public key and other stuff. RFC8032 5.1.5 */
401
+ function getExtendedPublicKey(key) {
402
+ var len = Fp.BYTES;
403
+ key = (0, utils_js_1.ensureBytes)('private key', key, len);
404
+ // Hash private key with curve's hash function to produce uniformingly random input
405
+ // Check byte lengths: ensure(64, h(ensure(32, key)))
406
+ var hashed = (0, utils_js_1.ensureBytes)('hashed private key', cHash(key), 2 * len);
407
+ var head = adjustScalarBytes(hashed.slice(0, len)); // clear first half bits, produce FE
408
+ var prefix = hashed.slice(len, 2 * len); // second half is called key prefix (5.1.6)
409
+ var scalar = modN_LE(head); // The actual private scalar
410
+ var point = G.multiply(scalar); // Point on Edwards curve aka public key
411
+ var pointBytes = point.toRawBytes(); // Uint8Array representation
412
+ return { head: head, prefix: prefix, scalar: scalar, point: point, pointBytes: pointBytes };
413
+ }
414
+ // Calculates EdDSA pub key. RFC8032 5.1.5. Privkey is hashed. Use first half with 3 bits cleared
415
+ function getPublicKey(privKey) {
416
+ return getExtendedPublicKey(privKey).pointBytes;
417
+ }
418
+ // int('LE', SHA512(dom2(F, C) || msgs)) mod N
419
+ function hashDomainToScalar(context) {
420
+ if (context === void 0) { context = new Uint8Array(); }
421
+ var msgs = [];
422
+ for (var _i = 1; _i < arguments.length; _i++) {
423
+ msgs[_i - 1] = arguments[_i];
424
+ }
425
+ var msg = uint8array_utils_1.concatUint8Array.apply(void 0, __spreadArray([], __read(msgs), false));
426
+ return modN_LE(cHash(domain(msg, (0, utils_js_1.ensureBytes)('context', context), !!prehash)));
427
+ }
428
+ /** Signs message with privateKey. RFC8032 5.1.6 */
429
+ function sign(msg, privKey, options) {
430
+ if (options === void 0) { options = {}; }
431
+ msg = (0, utils_js_1.ensureBytes)('message', msg);
432
+ if (prehash)
433
+ msg = prehash(msg); // for ed25519ph etc.
434
+ var _a = getExtendedPublicKey(privKey), prefix = _a.prefix, scalar = _a.scalar, pointBytes = _a.pointBytes;
435
+ var r = hashDomainToScalar(options.context, prefix, msg); // r = dom2(F, C) || prefix || PH(M)
436
+ var R = G.multiply(r).toRawBytes(); // R = rG
437
+ var k = hashDomainToScalar(options.context, R, pointBytes, msg); // R || A || PH(M)
438
+ var s = modN(r + k * scalar); // S = (r + k * s) mod L
439
+ (0, utils_js_1.aInRange)('signature.s', s, _0n, CURVE_ORDER); // 0 <= s < l
440
+ var res = (0, uint8array_utils_1.concatUint8Array)(R, (0, utils_js_1.numberToBytesLE)(s, Fp.BYTES));
441
+ return (0, utils_js_1.ensureBytes)('result', res, Fp.BYTES * 2); // 64-byte signature
442
+ }
443
+ var verifyOpts = VERIFY_DEFAULT;
444
+ /**
445
+ * Verifies EdDSA signature against message and public key. RFC8032 5.1.7.
446
+ * An extended group equation is checked.
447
+ */
448
+ function verify(sig, msg, publicKey, options) {
449
+ if (options === void 0) { options = verifyOpts; }
450
+ var context = options.context, zip215 = options.zip215;
451
+ var len = Fp.BYTES; // Verifies EdDSA signature against message and public key. RFC8032 5.1.7.
452
+ sig = (0, utils_js_1.ensureBytes)('signature', sig, 2 * len); // An extended group equation is checked.
453
+ msg = (0, utils_js_1.ensureBytes)('message', msg);
454
+ publicKey = (0, utils_js_1.ensureBytes)('publicKey', publicKey, len);
455
+ if (zip215 !== undefined)
456
+ (0, utils_js_1.abool)('zip215', zip215);
457
+ if (prehash)
458
+ msg = prehash(msg); // for ed25519ph, etc
459
+ var s = (0, utils_js_1.bytesToNumberLE)(sig.slice(len, 2 * len));
460
+ var A, R, SB;
461
+ try {
462
+ // zip215=true is good for consensus-critical apps. =false follows RFC8032 / NIST186-5.
463
+ // zip215=true: 0 <= y < MASK (2^256 for ed25519)
464
+ // zip215=false: 0 <= y < P (2^255-19 for ed25519)
465
+ A = Point.fromHex(publicKey, zip215);
466
+ R = Point.fromHex(sig.slice(0, len), zip215);
467
+ SB = G.multiplyUnsafe(s); // 0 <= s < l is done inside
468
+ }
469
+ catch (error) {
470
+ return false;
471
+ }
472
+ if (!zip215 && A.isSmallOrder())
473
+ return false;
474
+ var k = hashDomainToScalar(context, R.toRawBytes(), A.toRawBytes(), msg);
475
+ var RkA = R.add(A.multiplyUnsafe(k));
476
+ // Extended group equation
477
+ // [8][S]B = [8]R + [8][k]A'
478
+ return RkA.subtract(SB).clearCofactor().equals(Point.ZERO);
479
+ }
480
+ G._setWindowSize(8); // Enable precomputes. Slows down first publicKey computation by 20ms.
481
+ var utils = {
482
+ getExtendedPublicKey: getExtendedPublicKey,
483
+ // ed25519 private keys are uniform 32b. No need to check for modulo bias, like in secp256k1.
484
+ randomPrivateKey: function () { return randomBytes(Fp.BYTES); },
485
+ /**
486
+ * We're doing scalar multiplication (used in getPublicKey etc) with precomputed BASE_POINT
487
+ * values. This slows down first getPublicKey() by milliseconds (see Speed section),
488
+ * but allows to speed-up subsequent getPublicKey() calls up to 20x.
489
+ * @param windowSize 2, 4, 8, 16
490
+ */
491
+ precompute: function (windowSize, point) {
492
+ if (windowSize === void 0) { windowSize = 8; }
493
+ if (point === void 0) { point = Point.BASE; }
494
+ point._setWindowSize(windowSize);
495
+ point.multiply(BigInt(3));
496
+ return point;
497
+ },
498
+ };
499
+ return {
500
+ CURVE: CURVE,
501
+ getPublicKey: getPublicKey,
502
+ sign: sign,
503
+ verify: verify,
504
+ ExtendedPoint: Point,
505
+ utils: utils,
506
+ };
507
+ }
508
+ exports.twistedEdwards = twistedEdwards;
@@ -0,0 +1,57 @@
1
+ /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
2
+ import type { Group, GroupConstructor, AffinePoint } from './curve.js';
3
+ import { IField } from './modular.js';
4
+ import type { CHash } from './utils.js';
5
+ /**
6
+ * * `DST` is a domain separation tag, defined in section 2.2.5
7
+ * * `p` characteristic of F, where F is a finite field of characteristic p and order q = p^m
8
+ * * `m` is extension degree (1 for prime fields)
9
+ * * `k` is the target security target in bits (e.g. 128), from section 5.1
10
+ * * `expand` is `xmd` (SHA2, SHA3, BLAKE) or `xof` (SHAKE, BLAKE-XOF)
11
+ * * `hash` conforming to `utils.CHash` interface, with `outputLen` / `blockLen` props
12
+ */
13
+ type UnicodeOrBytes = string | Uint8Array;
14
+ export type Opts = {
15
+ DST: UnicodeOrBytes;
16
+ p: bigint;
17
+ m: number;
18
+ k: number;
19
+ expand: 'xmd' | 'xof';
20
+ hash: CHash;
21
+ };
22
+ export declare function expand_message_xmd(msg: Uint8Array, DST: Uint8Array, lenInBytes: number, H: CHash): Uint8Array;
23
+ export declare function expand_message_xof(msg: Uint8Array, DST: Uint8Array, lenInBytes: number, k: number, H: CHash): Uint8Array;
24
+ /**
25
+ * Hashes arbitrary-length byte strings to a list of one or more elements of a finite field F
26
+ * https://www.rfc-editor.org/rfc/rfc9380#section-5.2
27
+ * @param msg a byte string containing the message to hash
28
+ * @param count the number of elements of F to output
29
+ * @param options `{DST: string, p: bigint, m: number, k: number, expand: 'xmd' | 'xof', hash: H}`, see above
30
+ * @returns [u_0, ..., u_(count - 1)], a list of field elements.
31
+ */
32
+ export declare function hash_to_field(msg: Uint8Array, count: number, options: Opts): bigint[][];
33
+ export declare function isogenyMap<T, F extends IField<T>>(field: F, map: [T[], T[], T[], T[]]): (x: T, y: T) => {
34
+ x: T;
35
+ y: T;
36
+ };
37
+ export interface H2CPoint<T> extends Group<H2CPoint<T>> {
38
+ add(rhs: H2CPoint<T>): H2CPoint<T>;
39
+ toAffine(iz?: bigint): AffinePoint<T>;
40
+ clearCofactor(): H2CPoint<T>;
41
+ assertValidity(): void;
42
+ }
43
+ export interface H2CPointConstructor<T> extends GroupConstructor<H2CPoint<T>> {
44
+ fromAffine(ap: AffinePoint<T>): H2CPoint<T>;
45
+ }
46
+ export type MapToCurve<T> = (scalar: bigint[]) => AffinePoint<T>;
47
+ export type htfBasicOpts = {
48
+ DST: UnicodeOrBytes;
49
+ };
50
+ export type HTFMethod<ReturnT> = (msg: Uint8Array, options?: htfBasicOpts) => H2CPoint<ReturnT>;
51
+ export declare function createHasher<T>(Point: H2CPointConstructor<T>, mapToCurve: MapToCurve<T>, def: Opts & {
52
+ encodeDST?: UnicodeOrBytes;
53
+ }): {
54
+ hashToCurve(msg: Uint8Array, options?: htfBasicOpts): H2CPoint<T>;
55
+ encodeToCurve(msg: Uint8Array, options?: htfBasicOpts): H2CPoint<T>;
56
+ };
57
+ export {};