@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,442 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.mapHashToField = exports.getMinHashLength = exports.getFieldBytesLength = exports.hashToPrivateScalar = exports.FpSqrtEven = exports.FpSqrtOdd = exports.Field = exports.nLength = exports.FpIsSquare = exports.FpDiv = exports.FpInvertBatch = exports.FpPow = exports.validateField = exports.isNegativeLE = exports.FpSqrt = exports.tonelliShanks = exports.invert = exports.pow2 = exports.pow = exports.mod = void 0;
4
+ /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
5
+ // Utilities for modular arithmetics and finite fields
6
+ var utils_1 = require("./utils.js");
7
+ // prettier-ignore
8
+ var _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _3n = BigInt(3);
9
+ // prettier-ignore
10
+ var _4n = BigInt(4), _5n = BigInt(5), _8n = BigInt(8);
11
+ // prettier-ignore
12
+ var _9n = BigInt(9), _16n = BigInt(16);
13
+ // Calculates a modulo b
14
+ function mod(a, b) {
15
+ var result = a % b;
16
+ return result >= _0n ? result : b + result;
17
+ }
18
+ exports.mod = mod;
19
+ /**
20
+ * Efficiently raise num to power and do modular division.
21
+ * Unsafe in some contexts: uses ladder, so can expose bigint bits.
22
+ * @example
23
+ * pow(2n, 6n, 11n) // 64n % 11n == 9n
24
+ */
25
+ // TODO: use field version && remove
26
+ function pow(num, power, modulo) {
27
+ if (modulo <= _0n || power < _0n)
28
+ throw new Error('Expected power/modulo > 0');
29
+ if (modulo === _1n)
30
+ return _0n;
31
+ var res = _1n;
32
+ while (power > _0n) {
33
+ if (power & _1n)
34
+ res = (res * num) % modulo;
35
+ num = (num * num) % modulo;
36
+ power >>= _1n;
37
+ }
38
+ return res;
39
+ }
40
+ exports.pow = pow;
41
+ // Does x ^ (2 ^ power) mod p. pow2(30, 4) == 30 ^ (2 ^ 4)
42
+ function pow2(x, power, modulo) {
43
+ var res = x;
44
+ while (power-- > _0n) {
45
+ res *= res;
46
+ res %= modulo;
47
+ }
48
+ return res;
49
+ }
50
+ exports.pow2 = pow2;
51
+ // Inverses number over modulo
52
+ function invert(number, modulo) {
53
+ if (number === _0n || modulo <= _0n) {
54
+ throw new Error("invert: expected positive integers, got n=".concat(number, " mod=").concat(modulo));
55
+ }
56
+ // Euclidean GCD https://brilliant.org/wiki/extended-euclidean-algorithm/
57
+ // Fermat's little theorem "CT-like" version inv(n) = n^(m-2) mod m is 30x slower.
58
+ var a = mod(number, modulo);
59
+ var b = modulo;
60
+ // prettier-ignore
61
+ var x = _0n, y = _1n, u = _1n, v = _0n;
62
+ while (a !== _0n) {
63
+ // JIT applies optimization if those two lines follow each other
64
+ var q = b / a;
65
+ var r = b % a;
66
+ var m = x - u * q;
67
+ var n = y - v * q;
68
+ // prettier-ignore
69
+ b = a, a = r, x = u, y = v, u = m, v = n;
70
+ }
71
+ var gcd = b;
72
+ if (gcd !== _1n)
73
+ throw new Error('invert: does not exist');
74
+ return mod(x, modulo);
75
+ }
76
+ exports.invert = invert;
77
+ /**
78
+ * Tonelli-Shanks square root search algorithm.
79
+ * 1. https://eprint.iacr.org/2012/685.pdf (page 12)
80
+ * 2. Square Roots from 1; 24, 51, 10 to Dan Shanks
81
+ * Will start an infinite loop if field order P is not prime.
82
+ * @param P field order
83
+ * @returns function that takes field Fp (created from P) and number n
84
+ */
85
+ function tonelliShanks(P) {
86
+ // Legendre constant: used to calculate Legendre symbol (a | p),
87
+ // which denotes the value of a^((p-1)/2) (mod p).
88
+ // (a | p) ≡ 1 if a is a square (mod p)
89
+ // (a | p) ≡ -1 if a is not a square (mod p)
90
+ // (a | p) ≡ 0 if a ≡ 0 (mod p)
91
+ var legendreC = (P - _1n) / _2n;
92
+ var Q, S, Z;
93
+ // Step 1: By factoring out powers of 2 from p - 1,
94
+ // find q and s such that p - 1 = q*(2^s) with q odd
95
+ for (Q = P - _1n, S = 0; Q % _2n === _0n; Q /= _2n, S++)
96
+ ;
97
+ // Step 2: Select a non-square z such that (z | p) ≡ -1 and set c ≡ zq
98
+ for (Z = _2n; Z < P && pow(Z, legendreC, P) !== P - _1n; Z++)
99
+ ;
100
+ // Fast-path
101
+ if (S === 1) {
102
+ var p1div4_1 = (P + _1n) / _4n;
103
+ return function tonelliFast(Fp, n) {
104
+ var root = Fp.pow(n, p1div4_1);
105
+ if (!Fp.eql(Fp.sqr(root), n))
106
+ throw new Error('Cannot find square root');
107
+ return root;
108
+ };
109
+ }
110
+ // Slow-path
111
+ var Q1div2 = (Q + _1n) / _2n;
112
+ return function tonelliSlow(Fp, n) {
113
+ // Step 0: Check that n is indeed a square: (n | p) should not be ≡ -1
114
+ if (Fp.pow(n, legendreC) === Fp.neg(Fp.ONE))
115
+ throw new Error('Cannot find square root');
116
+ var r = S;
117
+ // TODO: will fail at Fp2/etc
118
+ var g = Fp.pow(Fp.mul(Fp.ONE, Z), Q); // will update both x and b
119
+ var x = Fp.pow(n, Q1div2); // first guess at the square root
120
+ var b = Fp.pow(n, Q); // first guess at the fudge factor
121
+ while (!Fp.eql(b, Fp.ONE)) {
122
+ if (Fp.eql(b, Fp.ZERO))
123
+ return Fp.ZERO; // https://en.wikipedia.org/wiki/Tonelli%E2%80%93Shanks_algorithm (4. If t = 0, return r = 0)
124
+ // Find m such b^(2^m)==1
125
+ var m = 1;
126
+ for (var t2 = Fp.sqr(b); m < r; m++) {
127
+ if (Fp.eql(t2, Fp.ONE))
128
+ break;
129
+ t2 = Fp.sqr(t2); // t2 *= t2
130
+ }
131
+ // NOTE: r-m-1 can be bigger than 32, need to convert to bigint before shift, otherwise there will be overflow
132
+ var ge = Fp.pow(g, _1n << BigInt(r - m - 1)); // ge = 2^(r-m-1)
133
+ g = Fp.sqr(ge); // g = ge * ge
134
+ x = Fp.mul(x, ge); // x *= ge
135
+ b = Fp.mul(b, g); // b *= g
136
+ r = m;
137
+ }
138
+ return x;
139
+ };
140
+ }
141
+ exports.tonelliShanks = tonelliShanks;
142
+ function FpSqrt(P) {
143
+ // NOTE: different algorithms can give different roots, it is up to user to decide which one they want.
144
+ // For example there is FpSqrtOdd/FpSqrtEven to choice root based on oddness (used for hash-to-curve).
145
+ // P ≡ 3 (mod 4)
146
+ // √n = n^((P+1)/4)
147
+ if (P % _4n === _3n) {
148
+ // Not all roots possible!
149
+ // const ORDER =
150
+ // 0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaabn;
151
+ // const NUM = 72057594037927816n;
152
+ var p1div4_2 = (P + _1n) / _4n;
153
+ return function sqrt3mod4(Fp, n) {
154
+ var root = Fp.pow(n, p1div4_2);
155
+ // Throw if root**2 != n
156
+ if (!Fp.eql(Fp.sqr(root), n))
157
+ throw new Error('Cannot find square root');
158
+ return root;
159
+ };
160
+ }
161
+ // Atkin algorithm for q ≡ 5 (mod 8), https://eprint.iacr.org/2012/685.pdf (page 10)
162
+ if (P % _8n === _5n) {
163
+ var c1_1 = (P - _5n) / _8n;
164
+ return function sqrt5mod8(Fp, n) {
165
+ var n2 = Fp.mul(n, _2n);
166
+ var v = Fp.pow(n2, c1_1);
167
+ var nv = Fp.mul(n, v);
168
+ var i = Fp.mul(Fp.mul(nv, _2n), v);
169
+ var root = Fp.mul(nv, Fp.sub(i, Fp.ONE));
170
+ if (!Fp.eql(Fp.sqr(root), n))
171
+ throw new Error('Cannot find square root');
172
+ return root;
173
+ };
174
+ }
175
+ // P ≡ 9 (mod 16)
176
+ if (P % _16n === _9n) {
177
+ // NOTE: tonelli is too slow for bls-Fp2 calculations even on start
178
+ // Means we cannot use sqrt for constants at all!
179
+ //
180
+ // const c1 = Fp.sqrt(Fp.negate(Fp.ONE)); // 1. c1 = sqrt(-1) in F, i.e., (c1^2) == -1 in F
181
+ // const c2 = Fp.sqrt(c1); // 2. c2 = sqrt(c1) in F, i.e., (c2^2) == c1 in F
182
+ // const c3 = Fp.sqrt(Fp.negate(c1)); // 3. c3 = sqrt(-c1) in F, i.e., (c3^2) == -c1 in F
183
+ // const c4 = (P + _7n) / _16n; // 4. c4 = (q + 7) / 16 # Integer arithmetic
184
+ // sqrt = (x) => {
185
+ // let tv1 = Fp.pow(x, c4); // 1. tv1 = x^c4
186
+ // let tv2 = Fp.mul(c1, tv1); // 2. tv2 = c1 * tv1
187
+ // const tv3 = Fp.mul(c2, tv1); // 3. tv3 = c2 * tv1
188
+ // let tv4 = Fp.mul(c3, tv1); // 4. tv4 = c3 * tv1
189
+ // const e1 = Fp.equals(Fp.square(tv2), x); // 5. e1 = (tv2^2) == x
190
+ // const e2 = Fp.equals(Fp.square(tv3), x); // 6. e2 = (tv3^2) == x
191
+ // tv1 = Fp.cmov(tv1, tv2, e1); // 7. tv1 = CMOV(tv1, tv2, e1) # Select tv2 if (tv2^2) == x
192
+ // tv2 = Fp.cmov(tv4, tv3, e2); // 8. tv2 = CMOV(tv4, tv3, e2) # Select tv3 if (tv3^2) == x
193
+ // const e3 = Fp.equals(Fp.square(tv2), x); // 9. e3 = (tv2^2) == x
194
+ // return Fp.cmov(tv1, tv2, e3); // 10. z = CMOV(tv1, tv2, e3) # Select the sqrt from tv1 and tv2
195
+ // }
196
+ }
197
+ // Other cases: Tonelli-Shanks algorithm
198
+ return tonelliShanks(P);
199
+ }
200
+ exports.FpSqrt = FpSqrt;
201
+ // Little-endian check for first LE bit (last BE bit);
202
+ var isNegativeLE = function (num, modulo) { return (mod(num, modulo) & _1n) === _1n; };
203
+ exports.isNegativeLE = isNegativeLE;
204
+ // prettier-ignore
205
+ var FIELD_FIELDS = [
206
+ 'create', 'isValid', 'is0', 'neg', 'inv', 'sqrt', 'sqr',
207
+ 'eql', 'add', 'sub', 'mul', 'pow', 'div',
208
+ 'addN', 'subN', 'mulN', 'sqrN'
209
+ ];
210
+ function validateField(field) {
211
+ var initial = {
212
+ ORDER: 'bigint',
213
+ MASK: 'bigint',
214
+ BYTES: 'isSafeInteger',
215
+ BITS: 'isSafeInteger',
216
+ };
217
+ var opts = FIELD_FIELDS.reduce(function (map, val) {
218
+ map[val] = 'function';
219
+ return map;
220
+ }, initial);
221
+ return (0, utils_1.validateObject)(field, opts);
222
+ }
223
+ exports.validateField = validateField;
224
+ // Generic field functions
225
+ /**
226
+ * Same as `pow` but for Fp: non-constant-time.
227
+ * Unsafe in some contexts: uses ladder, so can expose bigint bits.
228
+ */
229
+ function FpPow(f, num, power) {
230
+ // Should have same speed as pow for bigints
231
+ // TODO: benchmark!
232
+ if (power < _0n)
233
+ throw new Error('Expected power > 0');
234
+ if (power === _0n)
235
+ return f.ONE;
236
+ if (power === _1n)
237
+ return num;
238
+ var p = f.ONE;
239
+ var d = num;
240
+ while (power > _0n) {
241
+ if (power & _1n)
242
+ p = f.mul(p, d);
243
+ d = f.sqr(d);
244
+ power >>= _1n;
245
+ }
246
+ return p;
247
+ }
248
+ exports.FpPow = FpPow;
249
+ /**
250
+ * Efficiently invert an array of Field elements.
251
+ * `inv(0)` will return `undefined` here: make sure to throw an error.
252
+ */
253
+ function FpInvertBatch(f, nums) {
254
+ var tmp = new Array(nums.length);
255
+ // Walk from first to last, multiply them by each other MOD p
256
+ var lastMultiplied = nums.reduce(function (acc, num, i) {
257
+ if (f.is0(num))
258
+ return acc;
259
+ tmp[i] = acc;
260
+ return f.mul(acc, num);
261
+ }, f.ONE);
262
+ // Invert last element
263
+ var inverted = f.inv(lastMultiplied);
264
+ // Walk from last to first, multiply them by inverted each other MOD p
265
+ nums.reduceRight(function (acc, num, i) {
266
+ if (f.is0(num))
267
+ return acc;
268
+ tmp[i] = f.mul(acc, tmp[i]);
269
+ return f.mul(acc, num);
270
+ }, inverted);
271
+ return tmp;
272
+ }
273
+ exports.FpInvertBatch = FpInvertBatch;
274
+ function FpDiv(f, lhs, rhs) {
275
+ return f.mul(lhs, typeof rhs === 'bigint' ? invert(rhs, f.ORDER) : f.inv(rhs));
276
+ }
277
+ exports.FpDiv = FpDiv;
278
+ // This function returns True whenever the value x is a square in the field F.
279
+ function FpIsSquare(f) {
280
+ var legendreConst = (f.ORDER - _1n) / _2n; // Integer arithmetic
281
+ return function (x) {
282
+ var p = f.pow(x, legendreConst);
283
+ return f.eql(p, f.ZERO) || f.eql(p, f.ONE);
284
+ };
285
+ }
286
+ exports.FpIsSquare = FpIsSquare;
287
+ // CURVE.n lengths
288
+ function nLength(n, nBitLength) {
289
+ // Bit size, byte size of CURVE.n
290
+ var _nBitLength = nBitLength !== undefined ? nBitLength : n.toString(2).length;
291
+ var nByteLength = Math.ceil(_nBitLength / 8);
292
+ return { nBitLength: _nBitLength, nByteLength: nByteLength };
293
+ }
294
+ exports.nLength = nLength;
295
+ /**
296
+ * Initializes a finite field over prime. **Non-primes are not supported.**
297
+ * Do not init in loop: slow. Very fragile: always run a benchmark on a change.
298
+ * Major performance optimizations:
299
+ * * a) denormalized operations like mulN instead of mul
300
+ * * b) same object shape: never add or remove keys
301
+ * * c) Object.freeze
302
+ * @param ORDER prime positive bigint
303
+ * @param bitLen how many bits the field consumes
304
+ * @param isLE (def: false) if encoding / decoding should be in little-endian
305
+ * @param redef optional faster redefinitions of sqrt and other methods
306
+ */
307
+ function Field(ORDER, bitLen, isLE, redef) {
308
+ if (isLE === void 0) { isLE = false; }
309
+ if (redef === void 0) { redef = {}; }
310
+ if (ORDER <= _0n)
311
+ throw new Error("Expected Field ORDER > 0, got ".concat(ORDER));
312
+ var _a = nLength(ORDER, bitLen), BITS = _a.nBitLength, BYTES = _a.nByteLength;
313
+ if (BYTES > 2048)
314
+ throw new Error('Field lengths over 2048 bytes are not supported');
315
+ var sqrtP = FpSqrt(ORDER);
316
+ var f = Object.freeze({
317
+ ORDER: ORDER,
318
+ BITS: BITS,
319
+ BYTES: BYTES,
320
+ MASK: (0, utils_1.bitMask)(BITS),
321
+ ZERO: _0n,
322
+ ONE: _1n,
323
+ create: function (num) { return mod(num, ORDER); },
324
+ isValid: function (num) {
325
+ if (typeof num !== 'bigint')
326
+ throw new Error("Invalid field element: expected bigint, got ".concat(typeof num));
327
+ return _0n <= num && num < ORDER; // 0 is valid element, but it's not invertible
328
+ },
329
+ is0: function (num) { return num === _0n; },
330
+ isOdd: function (num) { return (num & _1n) === _1n; },
331
+ neg: function (num) { return mod(-num, ORDER); },
332
+ eql: function (lhs, rhs) { return lhs === rhs; },
333
+ sqr: function (num) { return mod(num * num, ORDER); },
334
+ add: function (lhs, rhs) { return mod(lhs + rhs, ORDER); },
335
+ sub: function (lhs, rhs) { return mod(lhs - rhs, ORDER); },
336
+ mul: function (lhs, rhs) { return mod(lhs * rhs, ORDER); },
337
+ pow: function (num, power) { return FpPow(f, num, power); },
338
+ div: function (lhs, rhs) { return mod(lhs * invert(rhs, ORDER), ORDER); },
339
+ // Same as above, but doesn't normalize
340
+ sqrN: function (num) { return num * num; },
341
+ addN: function (lhs, rhs) { return lhs + rhs; },
342
+ subN: function (lhs, rhs) { return lhs - rhs; },
343
+ mulN: function (lhs, rhs) { return lhs * rhs; },
344
+ inv: function (num) { return invert(num, ORDER); },
345
+ sqrt: redef.sqrt || (function (n) { return sqrtP(f, n); }),
346
+ invertBatch: function (lst) { return FpInvertBatch(f, lst); },
347
+ // TODO: do we really need constant cmov?
348
+ // We don't have const-time bigints anyway, so probably will be not very useful
349
+ cmov: function (a, b, c) { return (c ? b : a); },
350
+ toBytes: function (num) { return (isLE ? (0, utils_1.numberToBytesLE)(num, BYTES) : (0, utils_1.numberToBytesBE)(num, BYTES)); },
351
+ fromBytes: function (bytes) {
352
+ if (bytes.length !== BYTES)
353
+ throw new Error("Fp.fromBytes: expected ".concat(BYTES, ", got ").concat(bytes.length));
354
+ return isLE ? (0, utils_1.bytesToNumberLE)(bytes) : (0, utils_1.bytesToNumberBE)(bytes);
355
+ },
356
+ });
357
+ return Object.freeze(f);
358
+ }
359
+ exports.Field = Field;
360
+ function FpSqrtOdd(Fp, elm) {
361
+ if (!Fp.isOdd)
362
+ throw new Error("Field doesn't have isOdd");
363
+ var root = Fp.sqrt(elm);
364
+ return Fp.isOdd(root) ? root : Fp.neg(root);
365
+ }
366
+ exports.FpSqrtOdd = FpSqrtOdd;
367
+ function FpSqrtEven(Fp, elm) {
368
+ if (!Fp.isOdd)
369
+ throw new Error("Field doesn't have isOdd");
370
+ var root = Fp.sqrt(elm);
371
+ return Fp.isOdd(root) ? Fp.neg(root) : root;
372
+ }
373
+ exports.FpSqrtEven = FpSqrtEven;
374
+ /**
375
+ * "Constant-time" private key generation utility.
376
+ * Same as mapKeyToField, but accepts less bytes (40 instead of 48 for 32-byte field).
377
+ * Which makes it slightly more biased, less secure.
378
+ * @deprecated use mapKeyToField instead
379
+ */
380
+ function hashToPrivateScalar(hash, groupOrder, isLE) {
381
+ if (isLE === void 0) { isLE = false; }
382
+ hash = (0, utils_1.ensureBytes)('privateHash', hash);
383
+ var hashLen = hash.length;
384
+ var minLen = nLength(groupOrder).nByteLength + 8;
385
+ if (minLen < 24 || hashLen < minLen || hashLen > 1024)
386
+ throw new Error("hashToPrivateScalar: expected ".concat(minLen, "-1024 bytes of input, got ").concat(hashLen));
387
+ var num = isLE ? (0, utils_1.bytesToNumberLE)(hash) : (0, utils_1.bytesToNumberBE)(hash);
388
+ return mod(num, groupOrder - _1n) + _1n;
389
+ }
390
+ exports.hashToPrivateScalar = hashToPrivateScalar;
391
+ /**
392
+ * Returns total number of bytes consumed by the field element.
393
+ * For example, 32 bytes for usual 256-bit weierstrass curve.
394
+ * @param fieldOrder number of field elements, usually CURVE.n
395
+ * @returns byte length of field
396
+ */
397
+ function getFieldBytesLength(fieldOrder) {
398
+ if (typeof fieldOrder !== 'bigint')
399
+ throw new Error('field order must be bigint');
400
+ var bitLength = fieldOrder.toString(2).length;
401
+ return Math.ceil(bitLength / 8);
402
+ }
403
+ exports.getFieldBytesLength = getFieldBytesLength;
404
+ /**
405
+ * Returns minimal amount of bytes that can be safely reduced
406
+ * by field order.
407
+ * Should be 2^-128 for 128-bit curve such as P256.
408
+ * @param fieldOrder number of field elements, usually CURVE.n
409
+ * @returns byte length of target hash
410
+ */
411
+ function getMinHashLength(fieldOrder) {
412
+ var length = getFieldBytesLength(fieldOrder);
413
+ return length + Math.ceil(length / 2);
414
+ }
415
+ exports.getMinHashLength = getMinHashLength;
416
+ /**
417
+ * "Constant-time" private key generation utility.
418
+ * Can take (n + n/2) or more bytes of uniform input e.g. from CSPRNG or KDF
419
+ * and convert them into private scalar, with the modulo bias being negligible.
420
+ * Needs at least 48 bytes of input for 32-byte private key.
421
+ * https://research.kudelskisecurity.com/2020/07/28/the-definitive-guide-to-modulo-bias-and-how-to-avoid-it/
422
+ * FIPS 186-5, A.2 https://csrc.nist.gov/publications/detail/fips/186/5/final
423
+ * RFC 9380, https://www.rfc-editor.org/rfc/rfc9380#section-5
424
+ * @param hash hash output from SHA3 or a similar function
425
+ * @param groupOrder size of subgroup - (e.g. secp256k1.CURVE.n)
426
+ * @param isLE interpret hash bytes as LE num
427
+ * @returns valid private scalar
428
+ */
429
+ function mapHashToField(key, fieldOrder, isLE) {
430
+ if (isLE === void 0) { isLE = false; }
431
+ var len = key.length;
432
+ var fieldLen = getFieldBytesLength(fieldOrder);
433
+ var minLen = getMinHashLength(fieldOrder);
434
+ // No small numbers: need to understand bias story. No huge numbers: easier to detect JS timings.
435
+ if (len < 16 || len < minLen || len > 1024)
436
+ throw new Error("expected ".concat(minLen, "-1024 bytes of input, got ").concat(len));
437
+ var num = isLE ? (0, utils_1.bytesToNumberBE)(key) : (0, utils_1.bytesToNumberLE)(key);
438
+ // `mod(x, 11)` can sometimes produce 0. `mod(x, 10) + 1` is the same, but no 0
439
+ var reduced = mod(num, fieldOrder - _1n) + _1n;
440
+ return isLE ? (0, utils_1.numberToBytesLE)(reduced, fieldLen) : (0, utils_1.numberToBytesBE)(reduced, fieldLen);
441
+ }
442
+ exports.mapHashToField = mapHashToField;
@@ -0,0 +1,93 @@
1
+ export type Hex = Uint8Array | string;
2
+ export type PrivKey = Hex | bigint;
3
+ export type CHash = {
4
+ (message: Uint8Array | string): Uint8Array;
5
+ blockLen: number;
6
+ outputLen: number;
7
+ create(opts?: {
8
+ dkLen?: number;
9
+ }): any;
10
+ };
11
+ export type FHash = (message: Uint8Array | string) => Uint8Array;
12
+ export declare function isBytes(a: unknown): a is Uint8Array;
13
+ export declare function abytes(item: unknown): void;
14
+ /**
15
+ * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'
16
+ */
17
+ export declare function bytesToHex(bytes: Uint8Array): string;
18
+ export declare function numberToHexUnpadded(num: number | bigint): string;
19
+ export declare function hexToNumber(hex: string): bigint;
20
+ /**
21
+ * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])
22
+ */
23
+ export declare function hexToBytes(hex: string): Uint8Array;
24
+ export declare function bytesToNumberBE(bytes: Uint8Array): bigint;
25
+ export declare function bytesToNumberLE(bytes: Uint8Array): bigint;
26
+ export declare function numberToBytesBE(n: number | bigint, len: number): Uint8Array;
27
+ export declare function numberToBytesLE(n: number | bigint, len: number): Uint8Array;
28
+ export declare function numberToVarBytesBE(n: number | bigint): Uint8Array;
29
+ /**
30
+ * Takes hex string or Uint8Array, converts to Uint8Array.
31
+ * Validates output length.
32
+ * Will throw error for other types.
33
+ * @param title descriptive title for an error e.g. 'private key'
34
+ * @param hex hex string or Uint8Array
35
+ * @param expectedLength optional, will compare to result array's length
36
+ * @returns
37
+ */
38
+ export declare function ensureBytes(title: string, hex: Hex, expectedLength?: number): Uint8Array;
39
+ /**
40
+ * Copies several Uint8Arrays into one.
41
+ */
42
+ export declare function concatBytes(...arrays: Uint8Array[]): Uint8Array;
43
+ export declare function equalBytes(a: Uint8Array, b: Uint8Array): boolean;
44
+ /**
45
+ * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99])
46
+ */
47
+ export declare function utf8ToBytes(str: string): Uint8Array;
48
+ /**
49
+ * Calculates amount of bits in a bigint.
50
+ * Same as `n.toString(2).length`
51
+ */
52
+ export declare function bitLen(n: bigint): number;
53
+ /**
54
+ * Gets single bit at position.
55
+ * NOTE: first bit position is 0 (same as arrays)
56
+ * Same as `!!+Array.from(n.toString(2)).reverse()[pos]`
57
+ */
58
+ export declare function bitGet(n: bigint, pos: number): bigint;
59
+ /**
60
+ * Sets single bit at position.
61
+ */
62
+ export declare function bitSet(n: bigint, pos: number, value: boolean): bigint;
63
+ /**
64
+ * Calculate mask for N bits. Not using ** operator with bigints because of old engines.
65
+ * Same as BigInt(`0b${Array(i).fill('1').join('')}`)
66
+ */
67
+ export declare const bitMask: (n: number) => bigint;
68
+ type Pred<T> = (v: Uint8Array) => T | undefined;
69
+ /**
70
+ * Minimal HMAC-DRBG from NIST 800-90 for RFC6979 sigs.
71
+ * @returns function that will call DRBG until 2nd arg returns something meaningful
72
+ * @example
73
+ * const drbg = createHmacDRBG<Key>(32, 32, hmac);
74
+ * drbg(seed, bytesToKey); // bytesToKey must return Key or undefined
75
+ */
76
+ export declare function createHmacDrbg<T>(hashLen: number, qByteLen: number, hmacFn: (key: Uint8Array, ...messages: Uint8Array[]) => Uint8Array): (seed: Uint8Array, predicate: Pred<T>) => T;
77
+ declare const validatorFns: {
78
+ readonly bigint: (val: any) => boolean;
79
+ readonly function: (val: any) => boolean;
80
+ readonly boolean: (val: any) => boolean;
81
+ readonly string: (val: any) => boolean;
82
+ readonly stringOrUint8Array: (val: any) => boolean;
83
+ readonly isSafeInteger: (val: any) => boolean;
84
+ readonly array: (val: any) => boolean;
85
+ readonly field: (val: any, object: any) => any;
86
+ readonly hash: (val: any) => boolean;
87
+ };
88
+ type Validator = keyof typeof validatorFns;
89
+ type ValMap<T extends Record<string, any>> = {
90
+ [K in keyof T]?: Validator;
91
+ };
92
+ export declare function validateObject<T extends Record<string, any>>(object: T, validators: ValMap<T>, optValidators?: ValMap<T>): T;
93
+ export {};