@decryption/curves 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (69) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +75 -0
  3. package/abstract/bls.d.ts +410 -0
  4. package/abstract/bls.js +433 -0
  5. package/abstract/curve.d.ts +441 -0
  6. package/abstract/curve.js +622 -0
  7. package/abstract/edwards.d.ts +319 -0
  8. package/abstract/edwards.js +697 -0
  9. package/abstract/fft.d.ts +438 -0
  10. package/abstract/fft.js +580 -0
  11. package/abstract/frost.d.ts +292 -0
  12. package/abstract/frost.js +705 -0
  13. package/abstract/hash-to-curve.d.ts +238 -0
  14. package/abstract/hash-to-curve.js +353 -0
  15. package/abstract/modular.d.ts +550 -0
  16. package/abstract/modular.js +872 -0
  17. package/abstract/montgomery.d.ts +95 -0
  18. package/abstract/montgomery.js +180 -0
  19. package/abstract/oprf.d.ts +354 -0
  20. package/abstract/oprf.js +358 -0
  21. package/abstract/poseidon.d.ts +198 -0
  22. package/abstract/poseidon.js +471 -0
  23. package/abstract/tower.d.ts +213 -0
  24. package/abstract/tower.js +963 -0
  25. package/abstract/weierstrass.d.ts +587 -0
  26. package/abstract/weierstrass.js +1421 -0
  27. package/bls12-381.d.ts +23 -0
  28. package/bls12-381.js +680 -0
  29. package/bn254.d.ts +74 -0
  30. package/bn254.js +248 -0
  31. package/ed25519.d.ts +211 -0
  32. package/ed25519.js +626 -0
  33. package/ed448.d.ts +184 -0
  34. package/ed448.js +596 -0
  35. package/esm/abstract/bls.js +429 -0
  36. package/esm/abstract/curve.js +610 -0
  37. package/esm/abstract/edwards.js +691 -0
  38. package/esm/abstract/fft.js +567 -0
  39. package/esm/abstract/frost.js +702 -0
  40. package/esm/abstract/hash-to-curve.js +345 -0
  41. package/esm/abstract/modular.js +849 -0
  42. package/esm/abstract/montgomery.js +177 -0
  43. package/esm/abstract/oprf.js +355 -0
  44. package/esm/abstract/poseidon.js +462 -0
  45. package/esm/abstract/tower.js +925 -0
  46. package/esm/abstract/weierstrass.js +1411 -0
  47. package/esm/bls12-381.js +677 -0
  48. package/esm/bn254.js +244 -0
  49. package/esm/ed25519.js +622 -0
  50. package/esm/ed448.js +593 -0
  51. package/esm/index.js +38 -0
  52. package/esm/misc.js +211 -0
  53. package/esm/nist.js +266 -0
  54. package/esm/secp256k1.js +465 -0
  55. package/esm/utils.js +597 -0
  56. package/esm/webcrypto.js +362 -0
  57. package/index.d.ts +0 -0
  58. package/index.js +38 -0
  59. package/misc.d.ts +113 -0
  60. package/misc.js +216 -0
  61. package/nist.d.ts +136 -0
  62. package/nist.js +269 -0
  63. package/package.json +46 -0
  64. package/secp256k1.d.ts +152 -0
  65. package/secp256k1.js +468 -0
  66. package/utils.d.ts +535 -0
  67. package/utils.js +626 -0
  68. package/webcrypto.d.ts +240 -0
  69. package/webcrypto.js +365 -0
@@ -0,0 +1,345 @@
1
+ import { abytes, asafenumber, asciiToBytes, bytesToNumberBE, copyBytes, concatBytes, isBytes, validateObject, } from '../utils';
2
+ import { FpInvertBatch, mod } from './modular';
3
+ // Octet Stream to Integer. "spec" implementation of os2ip is 2.5x slower vs bytesToNumberBE.
4
+ const os2ip = bytesToNumberBE;
5
+ // Integer to Octet Stream (numberToBytesBE).
6
+ function i2osp(value, length) {
7
+ asafenumber(value);
8
+ asafenumber(length);
9
+ // This helper stays on the JS bitwise/u32 fast-path. Callers that need wider encodings should
10
+ // use bigint + numberToBytesBE instead of routing large widths through this small helper.
11
+ if (length < 0 || length > 4)
12
+ throw new Error('invalid I2OSP length: ' + length);
13
+ if (value < 0 || value > 2 ** (8 * length) - 1)
14
+ throw new Error('invalid I2OSP input: ' + value);
15
+ const res = Array.from({ length }).fill(0);
16
+ for (let i = length - 1; i >= 0; i--) {
17
+ res[i] = value & 0xff;
18
+ value >>>= 8;
19
+ }
20
+ return new Uint8Array(res);
21
+ }
22
+ // RFC 9380 only applies strxor() to equal-length strings; callers must preserve that invariant.
23
+ function strxor(a, b) {
24
+ const arr = new Uint8Array(a.length);
25
+ for (let i = 0; i < a.length; i++) {
26
+ arr[i] = a[i] ^ b[i];
27
+ }
28
+ return arr;
29
+ }
30
+ // User can always use utf8 if they want, by passing Uint8Array.
31
+ // If string is passed, we treat it as ASCII: other formats are likely a mistake.
32
+ function normDST(DST) {
33
+ if (!isBytes(DST) && typeof DST !== 'string')
34
+ throw new Error('DST must be Uint8Array or ascii string');
35
+ const dst = typeof DST === 'string' ? asciiToBytes(DST) : DST;
36
+ // RFC 9380 §3.1 requirement 2: tags "MUST have nonzero length".
37
+ if (dst.length === 0)
38
+ throw new Error('DST must be non-empty');
39
+ return dst;
40
+ }
41
+ /**
42
+ * Produces a uniformly random byte string using a cryptographic hash
43
+ * function H that outputs b bits.
44
+ * See {@link https://www.rfc-editor.org/rfc/rfc9380#section-5.3.1 | RFC 9380 section 5.3.1}.
45
+ * @param msg - Input message.
46
+ * @param DST - Domain separation tag. This helper normalizes DST, rejects empty DSTs, and
47
+ * oversize-hashes DST when needed.
48
+ * @param lenInBytes - Output length.
49
+ * @param H - Hash function.
50
+ * @returns Uniform byte string.
51
+ * @throws If the message, DST, hash, or output length is invalid. {@link Error}
52
+ * @example
53
+ * Expand one message into uniform bytes with the XMD construction.
54
+ *
55
+ * ```ts
56
+ * import { expand_message_xmd } from './hash-to-curve';
57
+ * import { sha256 } from '@decryption/hashes/sha2';
58
+ * const uniform = expand_message_xmd(new TextEncoder().encode('hello noble'), 'DST', 32, sha256);
59
+ * ```
60
+ */
61
+ export function expand_message_xmd(msg, DST, lenInBytes, H) {
62
+ abytes(msg);
63
+ asafenumber(lenInBytes);
64
+ DST = normDST(DST);
65
+ // https://www.rfc-editor.org/rfc/rfc9380#section-5.3.3
66
+ if (DST.length > 255)
67
+ DST = H(concatBytes(asciiToBytes('H2C-OVERSIZE-DST-'), DST));
68
+ const { outputLen: b_in_bytes, blockLen: r_in_bytes } = H;
69
+ const ell = Math.ceil(lenInBytes / b_in_bytes);
70
+ if (lenInBytes > 65535 || ell > 255)
71
+ throw new Error('expand_message_xmd: invalid lenInBytes');
72
+ const DST_prime = concatBytes(DST, i2osp(DST.length, 1));
73
+ const Z_pad = new Uint8Array(r_in_bytes); // RFC 9380: Z_pad = I2OSP(0, s_in_bytes)
74
+ const l_i_b_str = i2osp(lenInBytes, 2); // len_in_bytes_str
75
+ const b = new Array(ell);
76
+ const b_0 = H(concatBytes(Z_pad, msg, l_i_b_str, i2osp(0, 1), DST_prime));
77
+ b[0] = H(concatBytes(b_0, i2osp(1, 1), DST_prime));
78
+ // `b[0]` already stores RFC `b_1`, so only derive `b_2..b_ell` here. The old `<= ell`
79
+ // loop computed one extra tail block, which was usually sliced away but broke at max `ell=255`
80
+ // by reaching `I2OSP(256, 1)`.
81
+ for (let i = 1; i < ell; i++) {
82
+ const args = [strxor(b_0, b[i - 1]), i2osp(i + 1, 1), DST_prime];
83
+ b[i] = H(concatBytes(...args));
84
+ }
85
+ const pseudo_random_bytes = concatBytes(...b);
86
+ return pseudo_random_bytes.slice(0, lenInBytes);
87
+ }
88
+ /**
89
+ * Produces a uniformly random byte string using an extendable-output function (XOF) H.
90
+ * 1. The collision resistance of H MUST be at least k bits.
91
+ * 2. H MUST be an XOF that has been proved indifferentiable from
92
+ * a random oracle under a reasonable cryptographic assumption.
93
+ * See {@link https://www.rfc-editor.org/rfc/rfc9380#section-5.3.2 | RFC 9380 section 5.3.2}.
94
+ * @param msg - Input message.
95
+ * @param DST - Domain separation tag. This helper normalizes DST, rejects empty DSTs, and
96
+ * oversize-hashes DST when needed.
97
+ * @param lenInBytes - Output length.
98
+ * @param k - Target security level.
99
+ * @param H - XOF hash function.
100
+ * @returns Uniform byte string.
101
+ * @throws If the message, DST, XOF, or output length is invalid. {@link Error}
102
+ * @example
103
+ * Expand one message into uniform bytes with the XOF construction.
104
+ *
105
+ * ```ts
106
+ * import { expand_message_xof } from './hash-to-curve';
107
+ * import { shake256 } from '@decryption/hashes/sha3';
108
+ * const uniform = expand_message_xof(
109
+ * new TextEncoder().encode('hello noble'),
110
+ * 'DST',
111
+ * 32,
112
+ * 128,
113
+ * shake256
114
+ * );
115
+ * ```
116
+ */
117
+ export function expand_message_xof(msg, DST, lenInBytes, k, H) {
118
+ abytes(msg);
119
+ asafenumber(lenInBytes);
120
+ DST = normDST(DST);
121
+ // https://www.rfc-editor.org/rfc/rfc9380#section-5.3.3
122
+ // RFC 9380 §5.3.3: DST = H("H2C-OVERSIZE-DST-" || a_very_long_DST, ceil(2 * k / 8)).
123
+ if (DST.length > 255) {
124
+ const dkLen = Math.ceil((2 * k) / 8);
125
+ DST = H.create({ dkLen }).update(asciiToBytes('H2C-OVERSIZE-DST-')).update(DST).digest();
126
+ }
127
+ if (lenInBytes > 65535 || DST.length > 255)
128
+ throw new Error('expand_message_xof: invalid lenInBytes');
129
+ return (H.create({ dkLen: lenInBytes })
130
+ .update(msg)
131
+ .update(i2osp(lenInBytes, 2))
132
+ // 2. DST_prime = DST || I2OSP(len(DST), 1)
133
+ .update(DST)
134
+ .update(i2osp(DST.length, 1))
135
+ .digest());
136
+ }
137
+ /**
138
+ * Hashes arbitrary-length byte strings to a list of one or more elements of a finite field F.
139
+ * See {@link https://www.rfc-editor.org/rfc/rfc9380#section-5.2 | RFC 9380 section 5.2}.
140
+ * @param msg - Input message bytes.
141
+ * @param count - Number of field elements to derive. Must be `>= 1`.
142
+ * @param options - RFC 9380 options. See {@link H2COpts}. `m` must be `>= 1`.
143
+ * @returns `[u_0, ..., u_(count - 1)]`, a list of field elements.
144
+ * @throws If the expander choice or RFC 9380 options are invalid. {@link Error}
145
+ * @example
146
+ * Hash one message into field elements before mapping it onto a curve.
147
+ *
148
+ * ```ts
149
+ * import { hash_to_field } from './hash-to-curve';
150
+ * import { sha256 } from '@decryption/hashes/sha2';
151
+ * const scalars = hash_to_field(new TextEncoder().encode('hello noble'), 2, {
152
+ * DST: 'DST',
153
+ * p: 17n,
154
+ * m: 1,
155
+ * k: 128,
156
+ * expand: 'xmd',
157
+ * hash: sha256,
158
+ * });
159
+ * ```
160
+ */
161
+ export function hash_to_field(msg, count, options) {
162
+ validateObject(options, {
163
+ p: 'bigint',
164
+ m: 'number',
165
+ k: 'number',
166
+ hash: 'function',
167
+ });
168
+ const { p, k, m, hash, expand, DST } = options;
169
+ asafenumber(hash.outputLen, 'valid hash');
170
+ abytes(msg);
171
+ asafenumber(count);
172
+ // RFC 9380 §5.2 defines hash_to_field over a list of one or more field elements and requires
173
+ // extension degree `m >= 1`; rejecting here avoids degenerate `[]` / `[[]]` helper outputs.
174
+ if (count < 1)
175
+ throw new Error('hash_to_field: expected count >= 1');
176
+ if (m < 1)
177
+ throw new Error('hash_to_field: expected m >= 1');
178
+ const log2p = p.toString(2).length;
179
+ const L = Math.ceil((log2p + k) / 8); // section 5.1 of ietf draft link above
180
+ const len_in_bytes = count * m * L;
181
+ let prb; // pseudo_random_bytes
182
+ if (expand === 'xmd') {
183
+ prb = expand_message_xmd(msg, DST, len_in_bytes, hash);
184
+ }
185
+ else if (expand === 'xof') {
186
+ prb = expand_message_xof(msg, DST, len_in_bytes, k, hash);
187
+ }
188
+ else if (expand === '_internal_pass') {
189
+ // for internal tests only
190
+ prb = msg;
191
+ }
192
+ else {
193
+ throw new Error('expand must be "xmd" or "xof"');
194
+ }
195
+ const u = new Array(count);
196
+ for (let i = 0; i < count; i++) {
197
+ const e = new Array(m);
198
+ for (let j = 0; j < m; j++) {
199
+ const elm_offset = L * (j + i * m);
200
+ const tv = prb.subarray(elm_offset, elm_offset + L);
201
+ e[j] = mod(os2ip(tv), p);
202
+ }
203
+ u[i] = e;
204
+ }
205
+ return u;
206
+ }
207
+ /**
208
+ * @param field - Field implementation.
209
+ * @param map - Isogeny coefficients.
210
+ * @returns Isogeny mapping helper.
211
+ * @example
212
+ * Build one rational isogeny map, then apply it to affine x/y coordinates.
213
+ *
214
+ * ```ts
215
+ * import { isogenyMap } from './hash-to-curve';
216
+ * import { Field } from './modular';
217
+ * const Fp = Field(17n);
218
+ * const iso = isogenyMap(Fp, [[0n, 1n], [1n], [1n], [1n]]);
219
+ * const point = iso(3n, 5n);
220
+ * ```
221
+ */
222
+ export function isogenyMap(field, map) {
223
+ // Make same order as in spec
224
+ const coeff = map.map((i) => Array.from(i).reverse());
225
+ return (x, y) => {
226
+ const [xn, xd, yn, yd] = coeff.map((val) => val.reduce((acc, i) => field.add(field.mul(acc, x), i)));
227
+ // RFC 9380 §6.6.3 / Appendix E: denominator-zero exceptional cases must
228
+ // return the identity on E.
229
+ // Shipped Weierstrass consumers encode that affine identity as all-zero
230
+ // coordinates, so `passZero=true` intentionally collapses zero
231
+ // denominators to `{ x: 0, y: 0 }`.
232
+ const [xd_inv, yd_inv] = FpInvertBatch(field, [xd, yd], true);
233
+ x = field.mul(xn, xd_inv); // xNum / xDen
234
+ y = field.mul(y, field.mul(yn, yd_inv)); // y * (yNum / yDev)
235
+ return { x, y };
236
+ };
237
+ }
238
+ // Keep the shared DST removable when the selected bundle never hashes to scalar.
239
+ // Callers that need protocol-specific scalar domain separation must override this generic default.
240
+ // RFC 9497 §§4.1-4.5 use this ASCII prefix before appending the ciphersuite context string.
241
+ // Export a string instead of mutable bytes so callers cannot poison default hash-to-scalar behavior
242
+ // by mutating a shared Uint8Array in place.
243
+ export const _DST_scalar = 'HashToScalar-';
244
+ /**
245
+ * Creates hash-to-curve methods from EC Point and mapToCurve function. See {@link H2CHasher}.
246
+ * @param Point - Point constructor.
247
+ * @param mapToCurve - Map-to-curve function.
248
+ * @param defaults - Default hash-to-curve options. This object is frozen in place and reused as
249
+ * the shared defaults bundle for the returned helpers.
250
+ * @returns Hash-to-curve helper namespace.
251
+ * @throws If the map-to-curve callback or default hash-to-curve options are invalid. {@link Error}
252
+ * @example
253
+ * Bundle hash-to-curve, hash-to-scalar, and encode-to-curve helpers for one curve.
254
+ *
255
+ * ```ts
256
+ * import { createHasher } from './hash-to-curve';
257
+ * import { p256 } from '../nist';
258
+ * import { sha256 } from '@decryption/hashes/sha2';
259
+ * const hasher = createHasher(p256.Point, () => p256.Point.BASE.toAffine(), {
260
+ * DST: 'P256_XMD:SHA-256_SSWU_RO_',
261
+ * encodeDST: 'P256_XMD:SHA-256_SSWU_NU_',
262
+ * p: p256.Point.Fp.ORDER,
263
+ * m: 1,
264
+ * k: 128,
265
+ * expand: 'xmd',
266
+ * hash: sha256,
267
+ * });
268
+ * const point = hasher.encodeToCurve(new TextEncoder().encode('hello noble'));
269
+ * ```
270
+ */
271
+ export function createHasher(Point, mapToCurve, defaults) {
272
+ if (typeof mapToCurve !== 'function')
273
+ throw new Error('mapToCurve() must be defined');
274
+ // `Point` is intentionally not shape-validated eagerly here: point constructors vary across
275
+ // curve families, so this helper only checks the hooks it can validate cheaply. Misconfigured
276
+ // suites fail later when hashing first touches Point.fromAffine / Point.ZERO / clearCofactor().
277
+ const snapshot = (src) => Object.freeze({
278
+ ...src,
279
+ DST: isBytes(src.DST) ? copyBytes(src.DST) : src.DST,
280
+ ...(src.encodeDST === undefined
281
+ ? {}
282
+ : { encodeDST: isBytes(src.encodeDST) ? copyBytes(src.encodeDST) : src.encodeDST }),
283
+ });
284
+ // Keep one private defaults snapshot for actual hashing and expose fresh
285
+ // detached snapshots via the public getter.
286
+ // Otherwise a caller could mutate `hasher.defaults.DST` in place and poison
287
+ // the singleton hasher for every other consumer in the same process.
288
+ const safeDefaults = snapshot(defaults);
289
+ function map(num) {
290
+ return Point.fromAffine(mapToCurve(num));
291
+ }
292
+ function clear(initial) {
293
+ const P = initial.clearCofactor();
294
+ // Keep ZERO as the algebraic cofactor-clearing result here; strict public point-validity
295
+ // surfaces may still reject it later, but createHasher.clear() itself is not that boundary.
296
+ if (P.equals(Point.ZERO))
297
+ return Point.ZERO;
298
+ P.assertValidity();
299
+ return P;
300
+ }
301
+ return Object.freeze({
302
+ get defaults() {
303
+ return snapshot(safeDefaults);
304
+ },
305
+ Point,
306
+ hashToCurve(msg, options) {
307
+ const opts = Object.assign({}, safeDefaults, options);
308
+ const u = hash_to_field(msg, 2, opts);
309
+ const u0 = map(u[0]);
310
+ const u1 = map(u[1]);
311
+ return clear(u0.add(u1));
312
+ },
313
+ encodeToCurve(msg, options) {
314
+ const optsDst = safeDefaults.encodeDST ? { DST: safeDefaults.encodeDST } : {};
315
+ const opts = Object.assign({}, safeDefaults, optsDst, options);
316
+ const u = hash_to_field(msg, 1, opts);
317
+ const u0 = map(u[0]);
318
+ return clear(u0);
319
+ },
320
+ /** See {@link H2CHasher} */
321
+ mapToCurve(scalars) {
322
+ // Curves with m=1 accept only single scalar
323
+ if (safeDefaults.m === 1) {
324
+ if (typeof scalars !== 'bigint')
325
+ throw new Error('expected bigint (m=1)');
326
+ return clear(map([scalars]));
327
+ }
328
+ if (!Array.isArray(scalars))
329
+ throw new Error('expected array of bigints');
330
+ for (const i of scalars)
331
+ if (typeof i !== 'bigint')
332
+ throw new Error('expected array of bigints');
333
+ return clear(map(scalars));
334
+ },
335
+ // hash_to_scalar can produce 0: https://www.rfc-editor.org/errata/eid8393
336
+ // RFC 9380, draft-irtf-cfrg-bbs-signatures-08. Default scalar DST is the shared generic
337
+ // `HashToScalar-` prefix above unless the caller overrides it per invocation.
338
+ hashToScalar(msg, options) {
339
+ // @ts-ignore
340
+ const N = Point.Fn.ORDER;
341
+ const opts = Object.assign({}, safeDefaults, { p: N, m: 1, DST: _DST_scalar }, options);
342
+ return hash_to_field(msg, 1, opts)[0][0];
343
+ },
344
+ });
345
+ }