sm-crypto-v2 1.13.0 → 1.15.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.
@@ -0,0 +1,3139 @@
1
+ // GENERATED FILE. DO NOT EDIT.
2
+ (function (global, factory) {
3
+ function preferDefault(exports) {
4
+ return exports.default || exports;
5
+ }
6
+ if (typeof define === "function" && define.amd) {
7
+ define([], function () {
8
+ var exports = {};
9
+ factory(exports);
10
+ return preferDefault(exports);
11
+ });
12
+ } else if (typeof exports === "object") {
13
+ factory(exports);
14
+ if (typeof module === "object") module.exports = preferDefault(exports);
15
+ } else {
16
+ (function () {
17
+ var exports = {};
18
+ factory(exports);
19
+ global.SmCryptoV2 = preferDefault(exports);
20
+ })();
21
+ }
22
+ })(typeof globalThis !== "undefined" ? globalThis : typeof self !== "undefined" ? self : this, function (_exports) {
23
+ "use strict";
24
+
25
+ Object.defineProperty(_exports, "__esModule", {
26
+ value: true
27
+ });
28
+ _exports.kdf = kdf;
29
+ _exports.sm2 = void 0;
30
+ _exports.sm3 = sm32;
31
+ _exports.sm4 = void 0;
32
+ var __defProp = Object.defineProperty;
33
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, {
34
+ enumerable: true,
35
+ configurable: true,
36
+ writable: true,
37
+ value
38
+ }) : obj[key] = value;
39
+ var __export = (target, all) => {
40
+ for (var name in all) __defProp(target, name, {
41
+ get: all[name],
42
+ enumerable: true
43
+ });
44
+ };
45
+ var __publicField = (obj, key, value) => {
46
+ __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
47
+ return value;
48
+ };
49
+
50
+ // src/sm2/index.ts
51
+ var sm2_exports = _exports.sm2 = {};
52
+ __export(sm2_exports, {
53
+ EmptyArray: () => EmptyArray,
54
+ arrayToHex: () => arrayToHex,
55
+ arrayToUtf8: () => arrayToUtf8,
56
+ calculateSharedKey: () => calculateSharedKey,
57
+ comparePublicKeyHex: () => comparePublicKeyHex,
58
+ compressPublicKeyHex: () => compressPublicKeyHex,
59
+ doDecrypt: () => doDecrypt,
60
+ doEncrypt: () => doEncrypt,
61
+ doSignature: () => doSignature,
62
+ doVerifySignature: () => doVerifySignature,
63
+ ecdh: () => getSharedSecret,
64
+ generateKeyPairHex: () => generateKeyPairHex,
65
+ getHash: () => getHash,
66
+ getPoint: () => getPoint,
67
+ getPublicKeyFromPrivateKey: () => getPublicKeyFromPrivateKey,
68
+ getZ: () => getZ,
69
+ hexToArray: () => hexToArray,
70
+ initRNGPool: () => initRNGPool,
71
+ leftPad: () => leftPad,
72
+ precomputePublicKey: () => precomputePublicKey,
73
+ utf8ToHex: () => utf8ToHex,
74
+ verifyPublicKey: () => verifyPublicKey
75
+ });
76
+
77
+ // node_modules/.pnpm/@noble+curves@1.1.0/node_modules/@noble/curves/esm/abstract/utils.js
78
+ var utils_exports = {};
79
+ __export(utils_exports, {
80
+ bitGet: () => bitGet,
81
+ bitLen: () => bitLen,
82
+ bitMask: () => bitMask,
83
+ bitSet: () => bitSet,
84
+ bytesToHex: () => bytesToHex,
85
+ bytesToNumberBE: () => bytesToNumberBE,
86
+ bytesToNumberLE: () => bytesToNumberLE,
87
+ concatBytes: () => concatBytes,
88
+ createHmacDrbg: () => createHmacDrbg,
89
+ ensureBytes: () => ensureBytes,
90
+ equalBytes: () => equalBytes,
91
+ hexToBytes: () => hexToBytes,
92
+ hexToNumber: () => hexToNumber,
93
+ numberToBytesBE: () => numberToBytesBE,
94
+ numberToBytesLE: () => numberToBytesLE,
95
+ numberToHexUnpadded: () => numberToHexUnpadded,
96
+ numberToVarBytesBE: () => numberToVarBytesBE,
97
+ utf8ToBytes: () => utf8ToBytes,
98
+ validateObject: () => validateObject
99
+ });
100
+ var _0n = BigInt(0);
101
+ var _1n = BigInt(1);
102
+ var _2n = BigInt(2);
103
+ var u8a = a => a instanceof Uint8Array;
104
+ var hexes = Array.from({
105
+ length: 256
106
+ }, (v, i) => i.toString(16).padStart(2, "0"));
107
+ function bytesToHex(bytes) {
108
+ if (!u8a(bytes)) throw new Error("Uint8Array expected");
109
+ let hex = "";
110
+ for (let i = 0; i < bytes.length; i++) {
111
+ hex += hexes[bytes[i]];
112
+ }
113
+ return hex;
114
+ }
115
+ function numberToHexUnpadded(num) {
116
+ const hex = num.toString(16);
117
+ return hex.length & 1 ? `0${hex}` : hex;
118
+ }
119
+ function hexToNumber(hex) {
120
+ if (typeof hex !== "string") throw new Error("hex string expected, got " + typeof hex);
121
+ return BigInt(hex === "" ? "0" : `0x${hex}`);
122
+ }
123
+ function hexToBytes(hex) {
124
+ if (typeof hex !== "string") throw new Error("hex string expected, got " + typeof hex);
125
+ const len = hex.length;
126
+ if (len % 2) throw new Error("padded hex string expected, got unpadded hex of length " + len);
127
+ const array = new Uint8Array(len / 2);
128
+ for (let i = 0; i < array.length; i++) {
129
+ const j = i * 2;
130
+ const hexByte = hex.slice(j, j + 2);
131
+ const byte = Number.parseInt(hexByte, 16);
132
+ if (Number.isNaN(byte) || byte < 0) throw new Error("Invalid byte sequence");
133
+ array[i] = byte;
134
+ }
135
+ return array;
136
+ }
137
+ function bytesToNumberBE(bytes) {
138
+ return hexToNumber(bytesToHex(bytes));
139
+ }
140
+ function bytesToNumberLE(bytes) {
141
+ if (!u8a(bytes)) throw new Error("Uint8Array expected");
142
+ return hexToNumber(bytesToHex(Uint8Array.from(bytes).reverse()));
143
+ }
144
+ function numberToBytesBE(n, len) {
145
+ return hexToBytes(n.toString(16).padStart(len * 2, "0"));
146
+ }
147
+ function numberToBytesLE(n, len) {
148
+ return numberToBytesBE(n, len).reverse();
149
+ }
150
+ function numberToVarBytesBE(n) {
151
+ return hexToBytes(numberToHexUnpadded(n));
152
+ }
153
+ function ensureBytes(title, hex, expectedLength) {
154
+ let res;
155
+ if (typeof hex === "string") {
156
+ try {
157
+ res = hexToBytes(hex);
158
+ } catch (e) {
159
+ throw new Error(`${title} must be valid hex string, got "${hex}". Cause: ${e}`);
160
+ }
161
+ } else if (u8a(hex)) {
162
+ res = Uint8Array.from(hex);
163
+ } else {
164
+ throw new Error(`${title} must be hex string or Uint8Array`);
165
+ }
166
+ const len = res.length;
167
+ if (typeof expectedLength === "number" && len !== expectedLength) throw new Error(`${title} expected ${expectedLength} bytes, got ${len}`);
168
+ return res;
169
+ }
170
+ function concatBytes(...arrays) {
171
+ const r = new Uint8Array(arrays.reduce((sum, a) => sum + a.length, 0));
172
+ let pad = 0;
173
+ arrays.forEach(a => {
174
+ if (!u8a(a)) throw new Error("Uint8Array expected");
175
+ r.set(a, pad);
176
+ pad += a.length;
177
+ });
178
+ return r;
179
+ }
180
+ function equalBytes(b1, b2) {
181
+ if (b1.length !== b2.length) return false;
182
+ for (let i = 0; i < b1.length; i++) if (b1[i] !== b2[i]) return false;
183
+ return true;
184
+ }
185
+ function utf8ToBytes(str) {
186
+ if (typeof str !== "string") throw new Error(`utf8ToBytes expected string, got ${typeof str}`);
187
+ return new Uint8Array(new TextEncoder().encode(str));
188
+ }
189
+ function bitLen(n) {
190
+ let len;
191
+ for (len = 0; n > _0n; n >>= _1n, len += 1);
192
+ return len;
193
+ }
194
+ function bitGet(n, pos) {
195
+ return n >> BigInt(pos) & _1n;
196
+ }
197
+ var bitSet = (n, pos, value) => {
198
+ return n | (value ? _1n : _0n) << BigInt(pos);
199
+ };
200
+ var bitMask = n => (_2n << BigInt(n - 1)) - _1n;
201
+ var u8n = data => new Uint8Array(data);
202
+ var u8fr = arr => Uint8Array.from(arr);
203
+ function createHmacDrbg(hashLen, qByteLen, hmacFn) {
204
+ if (typeof hashLen !== "number" || hashLen < 2) throw new Error("hashLen must be a number");
205
+ if (typeof qByteLen !== "number" || qByteLen < 2) throw new Error("qByteLen must be a number");
206
+ if (typeof hmacFn !== "function") throw new Error("hmacFn must be a function");
207
+ let v = u8n(hashLen);
208
+ let k = u8n(hashLen);
209
+ let i = 0;
210
+ const reset = () => {
211
+ v.fill(1);
212
+ k.fill(0);
213
+ i = 0;
214
+ };
215
+ const h = (...b) => hmacFn(k, v, ...b);
216
+ const reseed = (seed = u8n()) => {
217
+ k = h(u8fr([0]), seed);
218
+ v = h();
219
+ if (seed.length === 0) return;
220
+ k = h(u8fr([1]), seed);
221
+ v = h();
222
+ };
223
+ const gen = () => {
224
+ if (i++ >= 1e3) throw new Error("drbg: tried 1000 values");
225
+ let len = 0;
226
+ const out = [];
227
+ while (len < qByteLen) {
228
+ v = h();
229
+ const sl = v.slice();
230
+ out.push(sl);
231
+ len += v.length;
232
+ }
233
+ return concatBytes(...out);
234
+ };
235
+ const genUntil = (seed, pred) => {
236
+ reset();
237
+ reseed(seed);
238
+ let res = void 0;
239
+ while (!(res = pred(gen()))) reseed();
240
+ reset();
241
+ return res;
242
+ };
243
+ return genUntil;
244
+ }
245
+ var validatorFns = {
246
+ bigint: val => typeof val === "bigint",
247
+ function: val => typeof val === "function",
248
+ boolean: val => typeof val === "boolean",
249
+ string: val => typeof val === "string",
250
+ isSafeInteger: val => Number.isSafeInteger(val),
251
+ array: val => Array.isArray(val),
252
+ field: (val, object) => object.Fp.isValid(val),
253
+ hash: val => typeof val === "function" && Number.isSafeInteger(val.outputLen)
254
+ };
255
+ function validateObject(object, validators, optValidators = {}) {
256
+ const checkField = (fieldName, type, isOptional) => {
257
+ const checkVal = validatorFns[type];
258
+ if (typeof checkVal !== "function") throw new Error(`Invalid validator "${type}", expected function`);
259
+ const val = object[fieldName];
260
+ if (isOptional && val === void 0) return;
261
+ if (!checkVal(val, object)) {
262
+ throw new Error(`Invalid param ${String(fieldName)}=${val} (${typeof val}), expected ${type}`);
263
+ }
264
+ };
265
+ for (const [fieldName, type] of Object.entries(validators)) checkField(fieldName, type, false);
266
+ for (const [fieldName, type] of Object.entries(optValidators)) checkField(fieldName, type, true);
267
+ return object;
268
+ }
269
+
270
+ // src/sm2/bn.ts
271
+ var ZERO = BigInt(0);
272
+ var ONE = BigInt(1);
273
+ var TWO = BigInt(2);
274
+ var THREE = BigInt(3);
275
+
276
+ // src/sm2/asn1.ts
277
+ function bigintToValue(bigint) {
278
+ let h = bigint.toString(16);
279
+ if (h[0] !== "-") {
280
+ if (h.length % 2 === 1) h = "0" + h;else if (!h.match(/^[0-7]/)) h = "00" + h;
281
+ } else {
282
+ h = h.substring(1);
283
+ let len = h.length;
284
+ if (len % 2 === 1) len += 1;else if (!h.match(/^[0-7]/)) len += 2;
285
+ let maskString = "";
286
+ for (let i = 0; i < len; i++) maskString += "f";
287
+ let mask = hexToNumber(maskString);
288
+ let output = (mask ^ bigint) + ONE;
289
+ h = output.toString(16).replace(/^-/, "");
290
+ }
291
+ return h;
292
+ }
293
+ var ASN1Object = class {
294
+ constructor(tlv = null, t = "00", l = "00", v = "") {
295
+ this.tlv = tlv;
296
+ this.t = t;
297
+ this.l = l;
298
+ this.v = v;
299
+ }
300
+ /**
301
+ * 获取 der 编码比特流16进制串
302
+ */
303
+ getEncodedHex() {
304
+ if (!this.tlv) {
305
+ this.v = this.getValue();
306
+ this.l = this.getLength();
307
+ this.tlv = this.t + this.l + this.v;
308
+ }
309
+ return this.tlv;
310
+ }
311
+ getLength() {
312
+ const n = this.v.length / 2;
313
+ let nHex = n.toString(16);
314
+ if (nHex.length % 2 === 1) nHex = "0" + nHex;
315
+ if (n < 128) {
316
+ return nHex;
317
+ } else {
318
+ const head = 128 + nHex.length / 2;
319
+ return head.toString(16) + nHex;
320
+ }
321
+ }
322
+ getValue() {
323
+ return "";
324
+ }
325
+ };
326
+ var DERInteger = class extends ASN1Object {
327
+ constructor(bigint) {
328
+ super();
329
+ this.t = "02";
330
+ if (bigint) this.v = bigintToValue(bigint);
331
+ }
332
+ getValue() {
333
+ return this.v;
334
+ }
335
+ };
336
+ var DEROctetString = class extends ASN1Object {
337
+ constructor(s) {
338
+ super();
339
+ this.s = s;
340
+ __publicField(this, "hV", "");
341
+ this.t = "04";
342
+ if (s) this.v = s.toLowerCase();
343
+ }
344
+ getValue() {
345
+ return this.v;
346
+ }
347
+ };
348
+ var DERSequence = class extends ASN1Object {
349
+ constructor(asn1Array) {
350
+ super();
351
+ this.asn1Array = asn1Array;
352
+ __publicField(this, "t", "30");
353
+ }
354
+ getValue() {
355
+ this.v = this.asn1Array.map(asn1Object => asn1Object.getEncodedHex()).join("");
356
+ return this.v;
357
+ }
358
+ };
359
+ function getLenOfL(str, start) {
360
+ if (+str[start + 2] < 8) return 1;
361
+ const encoded = str.slice(start + 2, start + 6);
362
+ const headHex = encoded.slice(0, 2);
363
+ const head = parseInt(headHex, 16);
364
+ const nHexLength = (head - 128) * 2;
365
+ return nHexLength;
366
+ }
367
+ function getL(str, start) {
368
+ const len = getLenOfL(str, start);
369
+ const l = str.substring(start + 2, start + 2 + len * 2);
370
+ if (!l) return -1;
371
+ const bigint = +l[0] < 8 ? hexToNumber(l) : hexToNumber(l.substring(2));
372
+ return +bigint.toString();
373
+ }
374
+ function getStartOfV(str, start) {
375
+ const len = getLenOfL(str, start);
376
+ return start + (len + 1) * 2;
377
+ }
378
+ function encodeDer(r, s) {
379
+ const derR = new DERInteger(r);
380
+ const derS = new DERInteger(s);
381
+ const derSeq = new DERSequence([derR, derS]);
382
+ return derSeq.getEncodedHex();
383
+ }
384
+ function encodeEnc(x2, y, hash, cipher) {
385
+ const derX = new DERInteger(x2);
386
+ const derY = new DERInteger(y);
387
+ const derHash = new DEROctetString(hash);
388
+ const derCipher = new DEROctetString(cipher);
389
+ const derSeq = new DERSequence([derX, derY, derHash, derCipher]);
390
+ return derSeq.getEncodedHex();
391
+ }
392
+ function decodeDer(input) {
393
+ const start = getStartOfV(input, 0);
394
+ const vIndexR = getStartOfV(input, start);
395
+ const lR = getL(input, start);
396
+ const vR = input.substring(vIndexR, vIndexR + lR * 2);
397
+ const nextStart = vIndexR + vR.length;
398
+ const vIndexS = getStartOfV(input, nextStart);
399
+ const lS = getL(input, nextStart);
400
+ const vS = input.substring(vIndexS, vIndexS + lS * 2);
401
+ const r = hexToNumber(vR);
402
+ const s = hexToNumber(vS);
403
+ return {
404
+ r,
405
+ s
406
+ };
407
+ }
408
+ function decodeEnc(input) {
409
+ function extractSequence(input2, start2) {
410
+ const vIndex = getStartOfV(input2, start2);
411
+ const length = getL(input2, start2);
412
+ const value = input2.substring(vIndex, vIndex + length * 2);
413
+ const nextStart = vIndex + value.length;
414
+ return {
415
+ value,
416
+ nextStart
417
+ };
418
+ }
419
+ const start = getStartOfV(input, 0);
420
+ const {
421
+ value: vR,
422
+ nextStart: startS
423
+ } = extractSequence(input, start);
424
+ const {
425
+ value: vS,
426
+ nextStart: startHash
427
+ } = extractSequence(input, startS);
428
+ const {
429
+ value: hash,
430
+ nextStart: startCipher
431
+ } = extractSequence(input, startHash);
432
+ const {
433
+ value: cipher
434
+ } = extractSequence(input, startCipher);
435
+ const x2 = hexToNumber(vR);
436
+ const y = hexToNumber(vS);
437
+ return {
438
+ x: x2,
439
+ y,
440
+ hash,
441
+ cipher
442
+ };
443
+ }
444
+
445
+ // node_modules/.pnpm/@noble+curves@1.1.0/node_modules/@noble/curves/esm/abstract/modular.js
446
+ var _0n2 = BigInt(0);
447
+ var _1n2 = BigInt(1);
448
+ var _2n2 = BigInt(2);
449
+ var _3n = BigInt(3);
450
+ var _4n = BigInt(4);
451
+ var _5n = BigInt(5);
452
+ var _8n = BigInt(8);
453
+ var _9n = BigInt(9);
454
+ var _16n = BigInt(16);
455
+ function mod(a, b) {
456
+ const result = a % b;
457
+ return result >= _0n2 ? result : b + result;
458
+ }
459
+ function pow(num, power, modulo) {
460
+ if (modulo <= _0n2 || power < _0n2) throw new Error("Expected power/modulo > 0");
461
+ if (modulo === _1n2) return _0n2;
462
+ let res = _1n2;
463
+ while (power > _0n2) {
464
+ if (power & _1n2) res = res * num % modulo;
465
+ num = num * num % modulo;
466
+ power >>= _1n2;
467
+ }
468
+ return res;
469
+ }
470
+ function invert(number, modulo) {
471
+ if (number === _0n2 || modulo <= _0n2) {
472
+ throw new Error(`invert: expected positive integers, got n=${number} mod=${modulo}`);
473
+ }
474
+ let a = mod(number, modulo);
475
+ let b = modulo;
476
+ let x2 = _0n2,
477
+ y = _1n2,
478
+ u = _1n2,
479
+ v = _0n2;
480
+ while (a !== _0n2) {
481
+ const q = b / a;
482
+ const r = b % a;
483
+ const m = x2 - u * q;
484
+ const n = y - v * q;
485
+ b = a, a = r, x2 = u, y = v, u = m, v = n;
486
+ }
487
+ const gcd = b;
488
+ if (gcd !== _1n2) throw new Error("invert: does not exist");
489
+ return mod(x2, modulo);
490
+ }
491
+ function tonelliShanks(P) {
492
+ const legendreC = (P - _1n2) / _2n2;
493
+ let Q, S, Z;
494
+ for (Q = P - _1n2, S = 0; Q % _2n2 === _0n2; Q /= _2n2, S++);
495
+ for (Z = _2n2; Z < P && pow(Z, legendreC, P) !== P - _1n2; Z++);
496
+ if (S === 1) {
497
+ const p1div4 = (P + _1n2) / _4n;
498
+ return function tonelliFast(Fp, n) {
499
+ const root = Fp.pow(n, p1div4);
500
+ if (!Fp.eql(Fp.sqr(root), n)) throw new Error("Cannot find square root");
501
+ return root;
502
+ };
503
+ }
504
+ const Q1div2 = (Q + _1n2) / _2n2;
505
+ return function tonelliSlow(Fp, n) {
506
+ if (Fp.pow(n, legendreC) === Fp.neg(Fp.ONE)) throw new Error("Cannot find square root");
507
+ let r = S;
508
+ let g = Fp.pow(Fp.mul(Fp.ONE, Z), Q);
509
+ let x2 = Fp.pow(n, Q1div2);
510
+ let b = Fp.pow(n, Q);
511
+ while (!Fp.eql(b, Fp.ONE)) {
512
+ if (Fp.eql(b, Fp.ZERO)) return Fp.ZERO;
513
+ let m = 1;
514
+ for (let t2 = Fp.sqr(b); m < r; m++) {
515
+ if (Fp.eql(t2, Fp.ONE)) break;
516
+ t2 = Fp.sqr(t2);
517
+ }
518
+ const ge = Fp.pow(g, _1n2 << BigInt(r - m - 1));
519
+ g = Fp.sqr(ge);
520
+ x2 = Fp.mul(x2, ge);
521
+ b = Fp.mul(b, g);
522
+ r = m;
523
+ }
524
+ return x2;
525
+ };
526
+ }
527
+ function FpSqrt(P) {
528
+ if (P % _4n === _3n) {
529
+ const p1div4 = (P + _1n2) / _4n;
530
+ return function sqrt3mod4(Fp, n) {
531
+ const root = Fp.pow(n, p1div4);
532
+ if (!Fp.eql(Fp.sqr(root), n)) throw new Error("Cannot find square root");
533
+ return root;
534
+ };
535
+ }
536
+ if (P % _8n === _5n) {
537
+ const c1 = (P - _5n) / _8n;
538
+ return function sqrt5mod8(Fp, n) {
539
+ const n2 = Fp.mul(n, _2n2);
540
+ const v = Fp.pow(n2, c1);
541
+ const nv = Fp.mul(n, v);
542
+ const i = Fp.mul(Fp.mul(nv, _2n2), v);
543
+ const root = Fp.mul(nv, Fp.sub(i, Fp.ONE));
544
+ if (!Fp.eql(Fp.sqr(root), n)) throw new Error("Cannot find square root");
545
+ return root;
546
+ };
547
+ }
548
+ if (P % _16n === _9n) {}
549
+ return tonelliShanks(P);
550
+ }
551
+ var FIELD_FIELDS = ["create", "isValid", "is0", "neg", "inv", "sqrt", "sqr", "eql", "add", "sub", "mul", "pow", "div", "addN", "subN", "mulN", "sqrN"];
552
+ function validateField(field2) {
553
+ const initial = {
554
+ ORDER: "bigint",
555
+ MASK: "bigint",
556
+ BYTES: "isSafeInteger",
557
+ BITS: "isSafeInteger"
558
+ };
559
+ const opts = FIELD_FIELDS.reduce((map, val) => {
560
+ map[val] = "function";
561
+ return map;
562
+ }, initial);
563
+ return validateObject(field2, opts);
564
+ }
565
+ function FpPow(f, num, power) {
566
+ if (power < _0n2) throw new Error("Expected power > 0");
567
+ if (power === _0n2) return f.ONE;
568
+ if (power === _1n2) return num;
569
+ let p = f.ONE;
570
+ let d = num;
571
+ while (power > _0n2) {
572
+ if (power & _1n2) p = f.mul(p, d);
573
+ d = f.sqr(d);
574
+ power >>= _1n2;
575
+ }
576
+ return p;
577
+ }
578
+ function FpInvertBatch(f, nums) {
579
+ const tmp2 = new Array(nums.length);
580
+ const lastMultiplied = nums.reduce((acc, num, i) => {
581
+ if (f.is0(num)) return acc;
582
+ tmp2[i] = acc;
583
+ return f.mul(acc, num);
584
+ }, f.ONE);
585
+ const inverted = f.inv(lastMultiplied);
586
+ nums.reduceRight((acc, num, i) => {
587
+ if (f.is0(num)) return acc;
588
+ tmp2[i] = f.mul(acc, tmp2[i]);
589
+ return f.mul(acc, num);
590
+ }, inverted);
591
+ return tmp2;
592
+ }
593
+ function nLength(n, nBitLength) {
594
+ const _nBitLength = nBitLength !== void 0 ? nBitLength : n.toString(2).length;
595
+ const nByteLength = Math.ceil(_nBitLength / 8);
596
+ return {
597
+ nBitLength: _nBitLength,
598
+ nByteLength
599
+ };
600
+ }
601
+ function Field(ORDER, bitLen2, isLE3 = false, redef = {}) {
602
+ if (ORDER <= _0n2) throw new Error(`Expected Fp ORDER > 0, got ${ORDER}`);
603
+ const {
604
+ nBitLength: BITS,
605
+ nByteLength: BYTES
606
+ } = nLength(ORDER, bitLen2);
607
+ if (BYTES > 2048) throw new Error("Field lengths over 2048 bytes are not supported");
608
+ const sqrtP = FpSqrt(ORDER);
609
+ const f = Object.freeze({
610
+ ORDER,
611
+ BITS,
612
+ BYTES,
613
+ MASK: bitMask(BITS),
614
+ ZERO: _0n2,
615
+ ONE: _1n2,
616
+ create: num => mod(num, ORDER),
617
+ isValid: num => {
618
+ if (typeof num !== "bigint") throw new Error(`Invalid field element: expected bigint, got ${typeof num}`);
619
+ return _0n2 <= num && num < ORDER;
620
+ },
621
+ is0: num => num === _0n2,
622
+ isOdd: num => (num & _1n2) === _1n2,
623
+ neg: num => mod(-num, ORDER),
624
+ eql: (lhs, rhs) => lhs === rhs,
625
+ sqr: num => mod(num * num, ORDER),
626
+ add: (lhs, rhs) => mod(lhs + rhs, ORDER),
627
+ sub: (lhs, rhs) => mod(lhs - rhs, ORDER),
628
+ mul: (lhs, rhs) => mod(lhs * rhs, ORDER),
629
+ pow: (num, power) => FpPow(f, num, power),
630
+ div: (lhs, rhs) => mod(lhs * invert(rhs, ORDER), ORDER),
631
+ // Same as above, but doesn't normalize
632
+ sqrN: num => num * num,
633
+ addN: (lhs, rhs) => lhs + rhs,
634
+ subN: (lhs, rhs) => lhs - rhs,
635
+ mulN: (lhs, rhs) => lhs * rhs,
636
+ inv: num => invert(num, ORDER),
637
+ sqrt: redef.sqrt || (n => sqrtP(f, n)),
638
+ invertBatch: lst => FpInvertBatch(f, lst),
639
+ // TODO: do we really need constant cmov?
640
+ // We don't have const-time bigints anyway, so probably will be not very useful
641
+ cmov: (a, b, c) => c ? b : a,
642
+ toBytes: num => isLE3 ? numberToBytesLE(num, BYTES) : numberToBytesBE(num, BYTES),
643
+ fromBytes: bytes => {
644
+ if (bytes.length !== BYTES) throw new Error(`Fp.fromBytes: expected ${BYTES}, got ${bytes.length}`);
645
+ return isLE3 ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);
646
+ }
647
+ });
648
+ return Object.freeze(f);
649
+ }
650
+ function hashToPrivateScalar(hash, groupOrder, isLE3 = false) {
651
+ hash = ensureBytes("privateHash", hash);
652
+ const hashLen = hash.length;
653
+ const minLen = nLength(groupOrder).nByteLength + 8;
654
+ if (minLen < 24 || hashLen < minLen || hashLen > 1024) throw new Error(`hashToPrivateScalar: expected ${minLen}-1024 bytes of input, got ${hashLen}`);
655
+ const num = isLE3 ? bytesToNumberLE(hash) : bytesToNumberBE(hash);
656
+ return mod(num, groupOrder - _1n2) + _1n2;
657
+ }
658
+
659
+ // node_modules/.pnpm/@noble+curves@1.1.0/node_modules/@noble/curves/esm/abstract/curve.js
660
+ var _0n3 = BigInt(0);
661
+ var _1n3 = BigInt(1);
662
+ function wNAF(c, bits) {
663
+ const constTimeNegate = (condition, item) => {
664
+ const neg = item.negate();
665
+ return condition ? neg : item;
666
+ };
667
+ const opts = W => {
668
+ const windows = Math.ceil(bits / W) + 1;
669
+ const windowSize = 2 ** (W - 1);
670
+ return {
671
+ windows,
672
+ windowSize
673
+ };
674
+ };
675
+ return {
676
+ constTimeNegate,
677
+ // non-const time multiplication ladder
678
+ unsafeLadder(elm, n) {
679
+ let p = c.ZERO;
680
+ let d = elm;
681
+ while (n > _0n3) {
682
+ if (n & _1n3) p = p.add(d);
683
+ d = d.double();
684
+ n >>= _1n3;
685
+ }
686
+ return p;
687
+ },
688
+ /**
689
+ * Creates a wNAF precomputation window. Used for caching.
690
+ * Default window size is set by `utils.precompute()` and is equal to 8.
691
+ * Number of precomputed points depends on the curve size:
692
+ * 2^(𝑊−1) * (Math.ceil(𝑛 / 𝑊) + 1), where:
693
+ * - 𝑊 is the window size
694
+ * - 𝑛 is the bitlength of the curve order.
695
+ * For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224.
696
+ * @returns precomputed point tables flattened to a single array
697
+ */
698
+ precomputeWindow(elm, W) {
699
+ const {
700
+ windows,
701
+ windowSize
702
+ } = opts(W);
703
+ const points = [];
704
+ let p = elm;
705
+ let base = p;
706
+ for (let window = 0; window < windows; window++) {
707
+ base = p;
708
+ points.push(base);
709
+ for (let i = 1; i < windowSize; i++) {
710
+ base = base.add(p);
711
+ points.push(base);
712
+ }
713
+ p = base.double();
714
+ }
715
+ return points;
716
+ },
717
+ /**
718
+ * Implements ec multiplication using precomputed tables and w-ary non-adjacent form.
719
+ * @param W window size
720
+ * @param precomputes precomputed tables
721
+ * @param n scalar (we don't check here, but should be less than curve order)
722
+ * @returns real and fake (for const-time) points
723
+ */
724
+ wNAF(W, precomputes, n) {
725
+ const {
726
+ windows,
727
+ windowSize
728
+ } = opts(W);
729
+ let p = c.ZERO;
730
+ let f = c.BASE;
731
+ const mask = BigInt(2 ** W - 1);
732
+ const maxNumber = 2 ** W;
733
+ const shiftBy = BigInt(W);
734
+ for (let window = 0; window < windows; window++) {
735
+ const offset = window * windowSize;
736
+ let wbits = Number(n & mask);
737
+ n >>= shiftBy;
738
+ if (wbits > windowSize) {
739
+ wbits -= maxNumber;
740
+ n += _1n3;
741
+ }
742
+ const offset1 = offset;
743
+ const offset2 = offset + Math.abs(wbits) - 1;
744
+ const cond1 = window % 2 !== 0;
745
+ const cond2 = wbits < 0;
746
+ if (wbits === 0) {
747
+ f = f.add(constTimeNegate(cond1, precomputes[offset1]));
748
+ } else {
749
+ p = p.add(constTimeNegate(cond2, precomputes[offset2]));
750
+ }
751
+ }
752
+ return {
753
+ p,
754
+ f
755
+ };
756
+ },
757
+ wNAFCached(P, precomputesMap, n, transform) {
758
+ const W = P._WINDOW_SIZE || 1;
759
+ let comp = precomputesMap.get(P);
760
+ if (!comp) {
761
+ comp = this.precomputeWindow(P, W);
762
+ if (W !== 1) {
763
+ precomputesMap.set(P, transform(comp));
764
+ }
765
+ }
766
+ return this.wNAF(W, comp, n);
767
+ }
768
+ };
769
+ }
770
+ function validateBasic(curve) {
771
+ validateField(curve.Fp);
772
+ validateObject(curve, {
773
+ n: "bigint",
774
+ h: "bigint",
775
+ Gx: "field",
776
+ Gy: "field"
777
+ }, {
778
+ nBitLength: "isSafeInteger",
779
+ nByteLength: "isSafeInteger"
780
+ });
781
+ return Object.freeze({
782
+ ...nLength(curve.n, curve.nBitLength),
783
+ ...curve,
784
+ ...{
785
+ p: curve.Fp.ORDER
786
+ }
787
+ });
788
+ }
789
+
790
+ // node_modules/.pnpm/@noble+curves@1.1.0/node_modules/@noble/curves/esm/abstract/weierstrass.js
791
+ function validatePointOpts(curve) {
792
+ const opts = validateBasic(curve);
793
+ validateObject(opts, {
794
+ a: "field",
795
+ b: "field"
796
+ }, {
797
+ allowedPrivateKeyLengths: "array",
798
+ wrapPrivateKey: "boolean",
799
+ isTorsionFree: "function",
800
+ clearCofactor: "function",
801
+ allowInfinityPoint: "boolean",
802
+ fromBytes: "function",
803
+ toBytes: "function"
804
+ });
805
+ const {
806
+ endo,
807
+ Fp,
808
+ a
809
+ } = opts;
810
+ if (endo) {
811
+ if (!Fp.eql(a, Fp.ZERO)) {
812
+ throw new Error("Endomorphism can only be defined for Koblitz curves that have a=0");
813
+ }
814
+ if (typeof endo !== "object" || typeof endo.beta !== "bigint" || typeof endo.splitScalar !== "function") {
815
+ throw new Error("Expected endomorphism with beta: bigint and splitScalar: function");
816
+ }
817
+ }
818
+ return Object.freeze({
819
+ ...opts
820
+ });
821
+ }
822
+ var {
823
+ bytesToNumberBE: b2n,
824
+ hexToBytes: h2b
825
+ } = utils_exports;
826
+ var DER = {
827
+ // asn.1 DER encoding utils
828
+ Err: class DERErr extends Error {
829
+ constructor(m = "") {
830
+ super(m);
831
+ }
832
+ },
833
+ _parseInt(data) {
834
+ const {
835
+ Err: E
836
+ } = DER;
837
+ if (data.length < 2 || data[0] !== 2) throw new E("Invalid signature integer tag");
838
+ const len = data[1];
839
+ const res = data.subarray(2, len + 2);
840
+ if (!len || res.length !== len) throw new E("Invalid signature integer: wrong length");
841
+ if (res[0] & 128) throw new E("Invalid signature integer: negative");
842
+ if (res[0] === 0 && !(res[1] & 128)) throw new E("Invalid signature integer: unnecessary leading zero");
843
+ return {
844
+ d: b2n(res),
845
+ l: data.subarray(len + 2)
846
+ };
847
+ },
848
+ toSig(hex) {
849
+ const {
850
+ Err: E
851
+ } = DER;
852
+ const data = typeof hex === "string" ? h2b(hex) : hex;
853
+ if (!(data instanceof Uint8Array)) throw new Error("ui8a expected");
854
+ let l = data.length;
855
+ if (l < 2 || data[0] != 48) throw new E("Invalid signature tag");
856
+ if (data[1] !== l - 2) throw new E("Invalid signature: incorrect length");
857
+ const {
858
+ d: r,
859
+ l: sBytes
860
+ } = DER._parseInt(data.subarray(2));
861
+ const {
862
+ d: s,
863
+ l: rBytesLeft
864
+ } = DER._parseInt(sBytes);
865
+ if (rBytesLeft.length) throw new E("Invalid signature: left bytes after parsing");
866
+ return {
867
+ r,
868
+ s
869
+ };
870
+ },
871
+ hexFromSig(sig) {
872
+ const slice = s2 => Number.parseInt(s2[0], 16) & 8 ? "00" + s2 : s2;
873
+ const h = num => {
874
+ const hex = num.toString(16);
875
+ return hex.length & 1 ? `0${hex}` : hex;
876
+ };
877
+ const s = slice(h(sig.s));
878
+ const r = slice(h(sig.r));
879
+ const shl = s.length / 2;
880
+ const rhl = r.length / 2;
881
+ const sl = h(shl);
882
+ const rl = h(rhl);
883
+ return `30${h(rhl + shl + 4)}02${rl}${r}02${sl}${s}`;
884
+ }
885
+ };
886
+ var _0n4 = BigInt(0);
887
+ var _1n4 = BigInt(1);
888
+ var _2n3 = BigInt(2);
889
+ var _3n2 = BigInt(3);
890
+ var _4n2 = BigInt(4);
891
+ function weierstrassPoints(opts) {
892
+ const CURVE = validatePointOpts(opts);
893
+ const {
894
+ Fp
895
+ } = CURVE;
896
+ const toBytes3 = CURVE.toBytes || ((c, point, isCompressed) => {
897
+ const a = point.toAffine();
898
+ return concatBytes(Uint8Array.from([4]), Fp.toBytes(a.x), Fp.toBytes(a.y));
899
+ });
900
+ const fromBytes = CURVE.fromBytes || (bytes => {
901
+ const tail = bytes.subarray(1);
902
+ const x2 = Fp.fromBytes(tail.subarray(0, Fp.BYTES));
903
+ const y = Fp.fromBytes(tail.subarray(Fp.BYTES, 2 * Fp.BYTES));
904
+ return {
905
+ x: x2,
906
+ y
907
+ };
908
+ });
909
+ function weierstrassEquation(x2) {
910
+ const {
911
+ a,
912
+ b
913
+ } = CURVE;
914
+ const x22 = Fp.sqr(x2);
915
+ const x3 = Fp.mul(x22, x2);
916
+ return Fp.add(Fp.add(x3, Fp.mul(x2, a)), b);
917
+ }
918
+ if (!Fp.eql(Fp.sqr(CURVE.Gy), weierstrassEquation(CURVE.Gx))) throw new Error("bad generator point: equation left != right");
919
+ function isWithinCurveOrder(num) {
920
+ return typeof num === "bigint" && _0n4 < num && num < CURVE.n;
921
+ }
922
+ function assertGE(num) {
923
+ if (!isWithinCurveOrder(num)) throw new Error("Expected valid bigint: 0 < bigint < curve.n");
924
+ }
925
+ function normPrivateKeyToScalar(key) {
926
+ const {
927
+ allowedPrivateKeyLengths: lengths,
928
+ nByteLength,
929
+ wrapPrivateKey,
930
+ n
931
+ } = CURVE;
932
+ if (lengths && typeof key !== "bigint") {
933
+ if (key instanceof Uint8Array) key = bytesToHex(key);
934
+ if (typeof key !== "string" || !lengths.includes(key.length)) throw new Error("Invalid key");
935
+ key = key.padStart(nByteLength * 2, "0");
936
+ }
937
+ let num;
938
+ try {
939
+ num = typeof key === "bigint" ? key : bytesToNumberBE(ensureBytes("private key", key, nByteLength));
940
+ } catch (error) {
941
+ throw new Error(`private key must be ${nByteLength} bytes, hex or bigint, not ${typeof key}`);
942
+ }
943
+ if (wrapPrivateKey) num = mod(num, n);
944
+ assertGE(num);
945
+ return num;
946
+ }
947
+ const pointPrecomputes = /* @__PURE__ */new Map();
948
+ function assertPrjPoint(other) {
949
+ if (!(other instanceof Point)) throw new Error("ProjectivePoint expected");
950
+ }
951
+ class Point {
952
+ constructor(px, py, pz) {
953
+ this.px = px;
954
+ this.py = py;
955
+ this.pz = pz;
956
+ if (px == null || !Fp.isValid(px)) throw new Error("x required");
957
+ if (py == null || !Fp.isValid(py)) throw new Error("y required");
958
+ if (pz == null || !Fp.isValid(pz)) throw new Error("z required");
959
+ }
960
+ // Does not validate if the point is on-curve.
961
+ // Use fromHex instead, or call assertValidity() later.
962
+ static fromAffine(p) {
963
+ const {
964
+ x: x2,
965
+ y
966
+ } = p || {};
967
+ if (!p || !Fp.isValid(x2) || !Fp.isValid(y)) throw new Error("invalid affine point");
968
+ if (p instanceof Point) throw new Error("projective point not allowed");
969
+ const is0 = i => Fp.eql(i, Fp.ZERO);
970
+ if (is0(x2) && is0(y)) return Point.ZERO;
971
+ return new Point(x2, y, Fp.ONE);
972
+ }
973
+ get x() {
974
+ return this.toAffine().x;
975
+ }
976
+ get y() {
977
+ return this.toAffine().y;
978
+ }
979
+ /**
980
+ * Takes a bunch of Projective Points but executes only one
981
+ * inversion on all of them. Inversion is very slow operation,
982
+ * so this improves performance massively.
983
+ * Optimization: converts a list of projective points to a list of identical points with Z=1.
984
+ */
985
+ static normalizeZ(points) {
986
+ const toInv = Fp.invertBatch(points.map(p => p.pz));
987
+ return points.map((p, i) => p.toAffine(toInv[i])).map(Point.fromAffine);
988
+ }
989
+ /**
990
+ * Converts hash string or Uint8Array to Point.
991
+ * @param hex short/long ECDSA hex
992
+ */
993
+ static fromHex(hex) {
994
+ const P = Point.fromAffine(fromBytes(ensureBytes("pointHex", hex)));
995
+ P.assertValidity();
996
+ return P;
997
+ }
998
+ // Multiplies generator point by privateKey.
999
+ static fromPrivateKey(privateKey) {
1000
+ return Point.BASE.multiply(normPrivateKeyToScalar(privateKey));
1001
+ }
1002
+ // "Private method", don't use it directly
1003
+ _setWindowSize(windowSize) {
1004
+ this._WINDOW_SIZE = windowSize;
1005
+ pointPrecomputes.delete(this);
1006
+ }
1007
+ // A point on curve is valid if it conforms to equation.
1008
+ assertValidity() {
1009
+ if (this.is0()) {
1010
+ if (CURVE.allowInfinityPoint) return;
1011
+ throw new Error("bad point: ZERO");
1012
+ }
1013
+ const {
1014
+ x: x2,
1015
+ y
1016
+ } = this.toAffine();
1017
+ if (!Fp.isValid(x2) || !Fp.isValid(y)) throw new Error("bad point: x or y not FE");
1018
+ const left = Fp.sqr(y);
1019
+ const right = weierstrassEquation(x2);
1020
+ if (!Fp.eql(left, right)) throw new Error("bad point: equation left != right");
1021
+ if (!this.isTorsionFree()) throw new Error("bad point: not in prime-order subgroup");
1022
+ }
1023
+ hasEvenY() {
1024
+ const {
1025
+ y
1026
+ } = this.toAffine();
1027
+ if (Fp.isOdd) return !Fp.isOdd(y);
1028
+ throw new Error("Field doesn't support isOdd");
1029
+ }
1030
+ /**
1031
+ * Compare one point to another.
1032
+ */
1033
+ equals(other) {
1034
+ assertPrjPoint(other);
1035
+ const {
1036
+ px: X1,
1037
+ py: Y1,
1038
+ pz: Z1
1039
+ } = this;
1040
+ const {
1041
+ px: X2,
1042
+ py: Y2,
1043
+ pz: Z2
1044
+ } = other;
1045
+ const U1 = Fp.eql(Fp.mul(X1, Z2), Fp.mul(X2, Z1));
1046
+ const U2 = Fp.eql(Fp.mul(Y1, Z2), Fp.mul(Y2, Z1));
1047
+ return U1 && U2;
1048
+ }
1049
+ /**
1050
+ * Flips point to one corresponding to (x, -y) in Affine coordinates.
1051
+ */
1052
+ negate() {
1053
+ return new Point(this.px, Fp.neg(this.py), this.pz);
1054
+ }
1055
+ // Renes-Costello-Batina exception-free doubling formula.
1056
+ // There is 30% faster Jacobian formula, but it is not complete.
1057
+ // https://eprint.iacr.org/2015/1060, algorithm 3
1058
+ // Cost: 8M + 3S + 3*a + 2*b3 + 15add.
1059
+ double() {
1060
+ const {
1061
+ a,
1062
+ b
1063
+ } = CURVE;
1064
+ const b3 = Fp.mul(b, _3n2);
1065
+ const {
1066
+ px: X1,
1067
+ py: Y1,
1068
+ pz: Z1
1069
+ } = this;
1070
+ let X3 = Fp.ZERO,
1071
+ Y3 = Fp.ZERO,
1072
+ Z3 = Fp.ZERO;
1073
+ let t0 = Fp.mul(X1, X1);
1074
+ let t1 = Fp.mul(Y1, Y1);
1075
+ let t2 = Fp.mul(Z1, Z1);
1076
+ let t3 = Fp.mul(X1, Y1);
1077
+ t3 = Fp.add(t3, t3);
1078
+ Z3 = Fp.mul(X1, Z1);
1079
+ Z3 = Fp.add(Z3, Z3);
1080
+ X3 = Fp.mul(a, Z3);
1081
+ Y3 = Fp.mul(b3, t2);
1082
+ Y3 = Fp.add(X3, Y3);
1083
+ X3 = Fp.sub(t1, Y3);
1084
+ Y3 = Fp.add(t1, Y3);
1085
+ Y3 = Fp.mul(X3, Y3);
1086
+ X3 = Fp.mul(t3, X3);
1087
+ Z3 = Fp.mul(b3, Z3);
1088
+ t2 = Fp.mul(a, t2);
1089
+ t3 = Fp.sub(t0, t2);
1090
+ t3 = Fp.mul(a, t3);
1091
+ t3 = Fp.add(t3, Z3);
1092
+ Z3 = Fp.add(t0, t0);
1093
+ t0 = Fp.add(Z3, t0);
1094
+ t0 = Fp.add(t0, t2);
1095
+ t0 = Fp.mul(t0, t3);
1096
+ Y3 = Fp.add(Y3, t0);
1097
+ t2 = Fp.mul(Y1, Z1);
1098
+ t2 = Fp.add(t2, t2);
1099
+ t0 = Fp.mul(t2, t3);
1100
+ X3 = Fp.sub(X3, t0);
1101
+ Z3 = Fp.mul(t2, t1);
1102
+ Z3 = Fp.add(Z3, Z3);
1103
+ Z3 = Fp.add(Z3, Z3);
1104
+ return new Point(X3, Y3, Z3);
1105
+ }
1106
+ // Renes-Costello-Batina exception-free addition formula.
1107
+ // There is 30% faster Jacobian formula, but it is not complete.
1108
+ // https://eprint.iacr.org/2015/1060, algorithm 1
1109
+ // Cost: 12M + 0S + 3*a + 3*b3 + 23add.
1110
+ add(other) {
1111
+ assertPrjPoint(other);
1112
+ const {
1113
+ px: X1,
1114
+ py: Y1,
1115
+ pz: Z1
1116
+ } = this;
1117
+ const {
1118
+ px: X2,
1119
+ py: Y2,
1120
+ pz: Z2
1121
+ } = other;
1122
+ let X3 = Fp.ZERO,
1123
+ Y3 = Fp.ZERO,
1124
+ Z3 = Fp.ZERO;
1125
+ const a = CURVE.a;
1126
+ const b3 = Fp.mul(CURVE.b, _3n2);
1127
+ let t0 = Fp.mul(X1, X2);
1128
+ let t1 = Fp.mul(Y1, Y2);
1129
+ let t2 = Fp.mul(Z1, Z2);
1130
+ let t3 = Fp.add(X1, Y1);
1131
+ let t4 = Fp.add(X2, Y2);
1132
+ t3 = Fp.mul(t3, t4);
1133
+ t4 = Fp.add(t0, t1);
1134
+ t3 = Fp.sub(t3, t4);
1135
+ t4 = Fp.add(X1, Z1);
1136
+ let t5 = Fp.add(X2, Z2);
1137
+ t4 = Fp.mul(t4, t5);
1138
+ t5 = Fp.add(t0, t2);
1139
+ t4 = Fp.sub(t4, t5);
1140
+ t5 = Fp.add(Y1, Z1);
1141
+ X3 = Fp.add(Y2, Z2);
1142
+ t5 = Fp.mul(t5, X3);
1143
+ X3 = Fp.add(t1, t2);
1144
+ t5 = Fp.sub(t5, X3);
1145
+ Z3 = Fp.mul(a, t4);
1146
+ X3 = Fp.mul(b3, t2);
1147
+ Z3 = Fp.add(X3, Z3);
1148
+ X3 = Fp.sub(t1, Z3);
1149
+ Z3 = Fp.add(t1, Z3);
1150
+ Y3 = Fp.mul(X3, Z3);
1151
+ t1 = Fp.add(t0, t0);
1152
+ t1 = Fp.add(t1, t0);
1153
+ t2 = Fp.mul(a, t2);
1154
+ t4 = Fp.mul(b3, t4);
1155
+ t1 = Fp.add(t1, t2);
1156
+ t2 = Fp.sub(t0, t2);
1157
+ t2 = Fp.mul(a, t2);
1158
+ t4 = Fp.add(t4, t2);
1159
+ t0 = Fp.mul(t1, t4);
1160
+ Y3 = Fp.add(Y3, t0);
1161
+ t0 = Fp.mul(t5, t4);
1162
+ X3 = Fp.mul(t3, X3);
1163
+ X3 = Fp.sub(X3, t0);
1164
+ t0 = Fp.mul(t3, t1);
1165
+ Z3 = Fp.mul(t5, Z3);
1166
+ Z3 = Fp.add(Z3, t0);
1167
+ return new Point(X3, Y3, Z3);
1168
+ }
1169
+ subtract(other) {
1170
+ return this.add(other.negate());
1171
+ }
1172
+ is0() {
1173
+ return this.equals(Point.ZERO);
1174
+ }
1175
+ wNAF(n) {
1176
+ return wnaf.wNAFCached(this, pointPrecomputes, n, comp => {
1177
+ const toInv = Fp.invertBatch(comp.map(p => p.pz));
1178
+ return comp.map((p, i) => p.toAffine(toInv[i])).map(Point.fromAffine);
1179
+ });
1180
+ }
1181
+ /**
1182
+ * Non-constant-time multiplication. Uses double-and-add algorithm.
1183
+ * It's faster, but should only be used when you don't care about
1184
+ * an exposed private key e.g. sig verification, which works over *public* keys.
1185
+ */
1186
+ multiplyUnsafe(n) {
1187
+ const I = Point.ZERO;
1188
+ if (n === _0n4) return I;
1189
+ assertGE(n);
1190
+ if (n === _1n4) return this;
1191
+ const {
1192
+ endo
1193
+ } = CURVE;
1194
+ if (!endo) return wnaf.unsafeLadder(this, n);
1195
+ let {
1196
+ k1neg,
1197
+ k1,
1198
+ k2neg,
1199
+ k2
1200
+ } = endo.splitScalar(n);
1201
+ let k1p = I;
1202
+ let k2p = I;
1203
+ let d = this;
1204
+ while (k1 > _0n4 || k2 > _0n4) {
1205
+ if (k1 & _1n4) k1p = k1p.add(d);
1206
+ if (k2 & _1n4) k2p = k2p.add(d);
1207
+ d = d.double();
1208
+ k1 >>= _1n4;
1209
+ k2 >>= _1n4;
1210
+ }
1211
+ if (k1neg) k1p = k1p.negate();
1212
+ if (k2neg) k2p = k2p.negate();
1213
+ k2p = new Point(Fp.mul(k2p.px, endo.beta), k2p.py, k2p.pz);
1214
+ return k1p.add(k2p);
1215
+ }
1216
+ /**
1217
+ * Constant time multiplication.
1218
+ * Uses wNAF method. Windowed method may be 10% faster,
1219
+ * but takes 2x longer to generate and consumes 2x memory.
1220
+ * Uses precomputes when available.
1221
+ * Uses endomorphism for Koblitz curves.
1222
+ * @param scalar by which the point would be multiplied
1223
+ * @returns New point
1224
+ */
1225
+ multiply(scalar) {
1226
+ assertGE(scalar);
1227
+ let n = scalar;
1228
+ let point, fake;
1229
+ const {
1230
+ endo
1231
+ } = CURVE;
1232
+ if (endo) {
1233
+ const {
1234
+ k1neg,
1235
+ k1,
1236
+ k2neg,
1237
+ k2
1238
+ } = endo.splitScalar(n);
1239
+ let {
1240
+ p: k1p,
1241
+ f: f1p
1242
+ } = this.wNAF(k1);
1243
+ let {
1244
+ p: k2p,
1245
+ f: f2p
1246
+ } = this.wNAF(k2);
1247
+ k1p = wnaf.constTimeNegate(k1neg, k1p);
1248
+ k2p = wnaf.constTimeNegate(k2neg, k2p);
1249
+ k2p = new Point(Fp.mul(k2p.px, endo.beta), k2p.py, k2p.pz);
1250
+ point = k1p.add(k2p);
1251
+ fake = f1p.add(f2p);
1252
+ } else {
1253
+ const {
1254
+ p,
1255
+ f
1256
+ } = this.wNAF(n);
1257
+ point = p;
1258
+ fake = f;
1259
+ }
1260
+ return Point.normalizeZ([point, fake])[0];
1261
+ }
1262
+ /**
1263
+ * Efficiently calculate `aP + bQ`. Unsafe, can expose private key, if used incorrectly.
1264
+ * Not using Strauss-Shamir trick: precomputation tables are faster.
1265
+ * The trick could be useful if both P and Q are not G (not in our case).
1266
+ * @returns non-zero affine point
1267
+ */
1268
+ multiplyAndAddUnsafe(Q, a, b) {
1269
+ const G = Point.BASE;
1270
+ const mul = (P, a2) => a2 === _0n4 || a2 === _1n4 || !P.equals(G) ? P.multiplyUnsafe(a2) : P.multiply(a2);
1271
+ const sum = mul(this, a).add(mul(Q, b));
1272
+ return sum.is0() ? void 0 : sum;
1273
+ }
1274
+ // Converts Projective point to affine (x, y) coordinates.
1275
+ // Can accept precomputed Z^-1 - for example, from invertBatch.
1276
+ // (x, y, z) ∋ (x=x/z, y=y/z)
1277
+ toAffine(iz) {
1278
+ const {
1279
+ px: x2,
1280
+ py: y,
1281
+ pz: z
1282
+ } = this;
1283
+ const is0 = this.is0();
1284
+ if (iz == null) iz = is0 ? Fp.ONE : Fp.inv(z);
1285
+ const ax = Fp.mul(x2, iz);
1286
+ const ay = Fp.mul(y, iz);
1287
+ const zz = Fp.mul(z, iz);
1288
+ if (is0) return {
1289
+ x: Fp.ZERO,
1290
+ y: Fp.ZERO
1291
+ };
1292
+ if (!Fp.eql(zz, Fp.ONE)) throw new Error("invZ was invalid");
1293
+ return {
1294
+ x: ax,
1295
+ y: ay
1296
+ };
1297
+ }
1298
+ isTorsionFree() {
1299
+ const {
1300
+ h: cofactor,
1301
+ isTorsionFree
1302
+ } = CURVE;
1303
+ if (cofactor === _1n4) return true;
1304
+ if (isTorsionFree) return isTorsionFree(Point, this);
1305
+ throw new Error("isTorsionFree() has not been declared for the elliptic curve");
1306
+ }
1307
+ clearCofactor() {
1308
+ const {
1309
+ h: cofactor,
1310
+ clearCofactor
1311
+ } = CURVE;
1312
+ if (cofactor === _1n4) return this;
1313
+ if (clearCofactor) return clearCofactor(Point, this);
1314
+ return this.multiplyUnsafe(CURVE.h);
1315
+ }
1316
+ toRawBytes(isCompressed = true) {
1317
+ this.assertValidity();
1318
+ return toBytes3(Point, this, isCompressed);
1319
+ }
1320
+ toHex(isCompressed = true) {
1321
+ return bytesToHex(this.toRawBytes(isCompressed));
1322
+ }
1323
+ }
1324
+ Point.BASE = new Point(CURVE.Gx, CURVE.Gy, Fp.ONE);
1325
+ Point.ZERO = new Point(Fp.ZERO, Fp.ONE, Fp.ZERO);
1326
+ const _bits = CURVE.nBitLength;
1327
+ const wnaf = wNAF(Point, CURVE.endo ? Math.ceil(_bits / 2) : _bits);
1328
+ return {
1329
+ CURVE,
1330
+ ProjectivePoint: Point,
1331
+ normPrivateKeyToScalar,
1332
+ weierstrassEquation,
1333
+ isWithinCurveOrder
1334
+ };
1335
+ }
1336
+ function validateOpts(curve) {
1337
+ const opts = validateBasic(curve);
1338
+ validateObject(opts, {
1339
+ hash: "hash",
1340
+ hmac: "function",
1341
+ randomBytes: "function"
1342
+ }, {
1343
+ bits2int: "function",
1344
+ bits2int_modN: "function",
1345
+ lowS: "boolean"
1346
+ });
1347
+ return Object.freeze({
1348
+ lowS: true,
1349
+ ...opts
1350
+ });
1351
+ }
1352
+ function weierstrass(curveDef) {
1353
+ const CURVE = validateOpts(curveDef);
1354
+ const {
1355
+ Fp,
1356
+ n: CURVE_ORDER
1357
+ } = CURVE;
1358
+ const compressedLen = Fp.BYTES + 1;
1359
+ const uncompressedLen = 2 * Fp.BYTES + 1;
1360
+ function isValidFieldElement(num) {
1361
+ return _0n4 < num && num < Fp.ORDER;
1362
+ }
1363
+ function modN(a) {
1364
+ return mod(a, CURVE_ORDER);
1365
+ }
1366
+ function invN(a) {
1367
+ return invert(a, CURVE_ORDER);
1368
+ }
1369
+ const {
1370
+ ProjectivePoint: Point,
1371
+ normPrivateKeyToScalar,
1372
+ weierstrassEquation,
1373
+ isWithinCurveOrder
1374
+ } = weierstrassPoints({
1375
+ ...CURVE,
1376
+ toBytes(c, point, isCompressed) {
1377
+ const a = point.toAffine();
1378
+ const x2 = Fp.toBytes(a.x);
1379
+ const cat = concatBytes;
1380
+ if (isCompressed) {
1381
+ return cat(Uint8Array.from([point.hasEvenY() ? 2 : 3]), x2);
1382
+ } else {
1383
+ return cat(Uint8Array.from([4]), x2, Fp.toBytes(a.y));
1384
+ }
1385
+ },
1386
+ fromBytes(bytes) {
1387
+ const len = bytes.length;
1388
+ const head = bytes[0];
1389
+ const tail = bytes.subarray(1);
1390
+ if (len === compressedLen && (head === 2 || head === 3)) {
1391
+ const x2 = bytesToNumberBE(tail);
1392
+ if (!isValidFieldElement(x2)) throw new Error("Point is not on curve");
1393
+ const y2 = weierstrassEquation(x2);
1394
+ let y = Fp.sqrt(y2);
1395
+ const isYOdd = (y & _1n4) === _1n4;
1396
+ const isHeadOdd = (head & 1) === 1;
1397
+ if (isHeadOdd !== isYOdd) y = Fp.neg(y);
1398
+ return {
1399
+ x: x2,
1400
+ y
1401
+ };
1402
+ } else if (len === uncompressedLen && head === 4) {
1403
+ const x2 = Fp.fromBytes(tail.subarray(0, Fp.BYTES));
1404
+ const y = Fp.fromBytes(tail.subarray(Fp.BYTES, 2 * Fp.BYTES));
1405
+ return {
1406
+ x: x2,
1407
+ y
1408
+ };
1409
+ } else {
1410
+ throw new Error(`Point of length ${len} was invalid. Expected ${compressedLen} compressed bytes or ${uncompressedLen} uncompressed bytes`);
1411
+ }
1412
+ }
1413
+ });
1414
+ const numToNByteStr = num => bytesToHex(numberToBytesBE(num, CURVE.nByteLength));
1415
+ function isBiggerThanHalfOrder(number) {
1416
+ const HALF = CURVE_ORDER >> _1n4;
1417
+ return number > HALF;
1418
+ }
1419
+ function normalizeS(s) {
1420
+ return isBiggerThanHalfOrder(s) ? modN(-s) : s;
1421
+ }
1422
+ const slcNum = (b, from, to) => bytesToNumberBE(b.slice(from, to));
1423
+ class Signature {
1424
+ constructor(r, s, recovery) {
1425
+ this.r = r;
1426
+ this.s = s;
1427
+ this.recovery = recovery;
1428
+ this.assertValidity();
1429
+ }
1430
+ // pair (bytes of r, bytes of s)
1431
+ static fromCompact(hex) {
1432
+ const l = CURVE.nByteLength;
1433
+ hex = ensureBytes("compactSignature", hex, l * 2);
1434
+ return new Signature(slcNum(hex, 0, l), slcNum(hex, l, 2 * l));
1435
+ }
1436
+ // DER encoded ECDSA signature
1437
+ // https://bitcoin.stackexchange.com/questions/57644/what-are-the-parts-of-a-bitcoin-transaction-input-script
1438
+ static fromDER(hex) {
1439
+ const {
1440
+ r,
1441
+ s
1442
+ } = DER.toSig(ensureBytes("DER", hex));
1443
+ return new Signature(r, s);
1444
+ }
1445
+ assertValidity() {
1446
+ if (!isWithinCurveOrder(this.r)) throw new Error("r must be 0 < r < CURVE.n");
1447
+ if (!isWithinCurveOrder(this.s)) throw new Error("s must be 0 < s < CURVE.n");
1448
+ }
1449
+ addRecoveryBit(recovery) {
1450
+ return new Signature(this.r, this.s, recovery);
1451
+ }
1452
+ recoverPublicKey(msgHash) {
1453
+ const {
1454
+ r,
1455
+ s,
1456
+ recovery: rec
1457
+ } = this;
1458
+ const h = bits2int_modN(ensureBytes("msgHash", msgHash));
1459
+ if (rec == null || ![0, 1, 2, 3].includes(rec)) throw new Error("recovery id invalid");
1460
+ const radj = rec === 2 || rec === 3 ? r + CURVE.n : r;
1461
+ if (radj >= Fp.ORDER) throw new Error("recovery id 2 or 3 invalid");
1462
+ const prefix = (rec & 1) === 0 ? "02" : "03";
1463
+ const R = Point.fromHex(prefix + numToNByteStr(radj));
1464
+ const ir = invN(radj);
1465
+ const u1 = modN(-h * ir);
1466
+ const u2 = modN(s * ir);
1467
+ const Q = Point.BASE.multiplyAndAddUnsafe(R, u1, u2);
1468
+ if (!Q) throw new Error("point at infinify");
1469
+ Q.assertValidity();
1470
+ return Q;
1471
+ }
1472
+ // Signatures should be low-s, to prevent malleability.
1473
+ hasHighS() {
1474
+ return isBiggerThanHalfOrder(this.s);
1475
+ }
1476
+ normalizeS() {
1477
+ return this.hasHighS() ? new Signature(this.r, modN(-this.s), this.recovery) : this;
1478
+ }
1479
+ // DER-encoded
1480
+ toDERRawBytes() {
1481
+ return hexToBytes(this.toDERHex());
1482
+ }
1483
+ toDERHex() {
1484
+ return DER.hexFromSig({
1485
+ r: this.r,
1486
+ s: this.s
1487
+ });
1488
+ }
1489
+ // padded bytes of r, then padded bytes of s
1490
+ toCompactRawBytes() {
1491
+ return hexToBytes(this.toCompactHex());
1492
+ }
1493
+ toCompactHex() {
1494
+ return numToNByteStr(this.r) + numToNByteStr(this.s);
1495
+ }
1496
+ }
1497
+ const utils = {
1498
+ isValidPrivateKey(privateKey) {
1499
+ try {
1500
+ normPrivateKeyToScalar(privateKey);
1501
+ return true;
1502
+ } catch (error) {
1503
+ return false;
1504
+ }
1505
+ },
1506
+ normPrivateKeyToScalar,
1507
+ /**
1508
+ * Produces cryptographically secure private key from random of size (nBitLength+64)
1509
+ * as per FIPS 186 B.4.1 with modulo bias being neglible.
1510
+ */
1511
+ randomPrivateKey: () => {
1512
+ const rand = CURVE.randomBytes(Fp.BYTES + 8);
1513
+ const num = hashToPrivateScalar(rand, CURVE_ORDER);
1514
+ return numberToBytesBE(num, CURVE.nByteLength);
1515
+ },
1516
+ /**
1517
+ * Creates precompute table for an arbitrary EC point. Makes point "cached".
1518
+ * Allows to massively speed-up `point.multiply(scalar)`.
1519
+ * @returns cached point
1520
+ * @example
1521
+ * const fast = utils.precompute(8, ProjectivePoint.fromHex(someonesPubKey));
1522
+ * fast.multiply(privKey); // much faster ECDH now
1523
+ */
1524
+ precompute(windowSize = 8, point = Point.BASE) {
1525
+ point._setWindowSize(windowSize);
1526
+ point.multiply(BigInt(3));
1527
+ return point;
1528
+ }
1529
+ };
1530
+ function getPublicKey(privateKey, isCompressed = true) {
1531
+ return Point.fromPrivateKey(privateKey).toRawBytes(isCompressed);
1532
+ }
1533
+ function isProbPub(item) {
1534
+ const arr = item instanceof Uint8Array;
1535
+ const str = typeof item === "string";
1536
+ const len = (arr || str) && item.length;
1537
+ if (arr) return len === compressedLen || len === uncompressedLen;
1538
+ if (str) return len === 2 * compressedLen || len === 2 * uncompressedLen;
1539
+ if (item instanceof Point) return true;
1540
+ return false;
1541
+ }
1542
+ function getSharedSecret2(privateA, publicB, isCompressed = true) {
1543
+ if (isProbPub(privateA)) throw new Error("first arg must be private key");
1544
+ if (!isProbPub(publicB)) throw new Error("second arg must be public key");
1545
+ const b = Point.fromHex(publicB);
1546
+ return b.multiply(normPrivateKeyToScalar(privateA)).toRawBytes(isCompressed);
1547
+ }
1548
+ const bits2int = CURVE.bits2int || function (bytes) {
1549
+ const num = bytesToNumberBE(bytes);
1550
+ const delta = bytes.length * 8 - CURVE.nBitLength;
1551
+ return delta > 0 ? num >> BigInt(delta) : num;
1552
+ };
1553
+ const bits2int_modN = CURVE.bits2int_modN || function (bytes) {
1554
+ return modN(bits2int(bytes));
1555
+ };
1556
+ const ORDER_MASK = bitMask(CURVE.nBitLength);
1557
+ function int2octets(num) {
1558
+ if (typeof num !== "bigint") throw new Error("bigint expected");
1559
+ if (!(_0n4 <= num && num < ORDER_MASK)) throw new Error(`bigint expected < 2^${CURVE.nBitLength}`);
1560
+ return numberToBytesBE(num, CURVE.nByteLength);
1561
+ }
1562
+ function prepSig(msgHash, privateKey, opts = defaultSigOpts) {
1563
+ if (["recovered", "canonical"].some(k => k in opts)) throw new Error("sign() legacy options not supported");
1564
+ const {
1565
+ hash,
1566
+ randomBytes: randomBytes2
1567
+ } = CURVE;
1568
+ let {
1569
+ lowS,
1570
+ prehash,
1571
+ extraEntropy: ent
1572
+ } = opts;
1573
+ if (lowS == null) lowS = true;
1574
+ msgHash = ensureBytes("msgHash", msgHash);
1575
+ if (prehash) msgHash = ensureBytes("prehashed msgHash", hash(msgHash));
1576
+ const h1int = bits2int_modN(msgHash);
1577
+ const d = normPrivateKeyToScalar(privateKey);
1578
+ const seedArgs = [int2octets(d), int2octets(h1int)];
1579
+ if (ent != null) {
1580
+ const e = ent === true ? randomBytes2(Fp.BYTES) : ent;
1581
+ seedArgs.push(ensureBytes("extraEntropy", e, Fp.BYTES));
1582
+ }
1583
+ const seed = concatBytes(...seedArgs);
1584
+ const m = h1int;
1585
+ function k2sig(kBytes) {
1586
+ const k = bits2int(kBytes);
1587
+ if (!isWithinCurveOrder(k)) return;
1588
+ const ik = invN(k);
1589
+ const q = Point.BASE.multiply(k).toAffine();
1590
+ const r = modN(q.x);
1591
+ if (r === _0n4) return;
1592
+ const s = modN(ik * modN(m + r * d));
1593
+ if (s === _0n4) return;
1594
+ let recovery = (q.x === r ? 0 : 2) | Number(q.y & _1n4);
1595
+ let normS = s;
1596
+ if (lowS && isBiggerThanHalfOrder(s)) {
1597
+ normS = normalizeS(s);
1598
+ recovery ^= 1;
1599
+ }
1600
+ return new Signature(r, normS, recovery);
1601
+ }
1602
+ return {
1603
+ seed,
1604
+ k2sig
1605
+ };
1606
+ }
1607
+ const defaultSigOpts = {
1608
+ lowS: CURVE.lowS,
1609
+ prehash: false
1610
+ };
1611
+ const defaultVerOpts = {
1612
+ lowS: CURVE.lowS,
1613
+ prehash: false
1614
+ };
1615
+ function sign(msgHash, privKey, opts = defaultSigOpts) {
1616
+ const {
1617
+ seed,
1618
+ k2sig
1619
+ } = prepSig(msgHash, privKey, opts);
1620
+ const C = CURVE;
1621
+ const drbg = createHmacDrbg(C.hash.outputLen, C.nByteLength, C.hmac);
1622
+ return drbg(seed, k2sig);
1623
+ }
1624
+ Point.BASE._setWindowSize(8);
1625
+ function verify(signature, msgHash, publicKey, opts = defaultVerOpts) {
1626
+ const sg = signature;
1627
+ msgHash = ensureBytes("msgHash", msgHash);
1628
+ publicKey = ensureBytes("publicKey", publicKey);
1629
+ if ("strict" in opts) throw new Error("options.strict was renamed to lowS");
1630
+ const {
1631
+ lowS,
1632
+ prehash
1633
+ } = opts;
1634
+ let _sig = void 0;
1635
+ let P;
1636
+ try {
1637
+ if (typeof sg === "string" || sg instanceof Uint8Array) {
1638
+ try {
1639
+ _sig = Signature.fromDER(sg);
1640
+ } catch (derError) {
1641
+ if (!(derError instanceof DER.Err)) throw derError;
1642
+ _sig = Signature.fromCompact(sg);
1643
+ }
1644
+ } else if (typeof sg === "object" && typeof sg.r === "bigint" && typeof sg.s === "bigint") {
1645
+ const {
1646
+ r: r2,
1647
+ s: s2
1648
+ } = sg;
1649
+ _sig = new Signature(r2, s2);
1650
+ } else {
1651
+ throw new Error("PARSE");
1652
+ }
1653
+ P = Point.fromHex(publicKey);
1654
+ } catch (error) {
1655
+ if (error.message === "PARSE") throw new Error(`signature must be Signature instance, Uint8Array or hex string`);
1656
+ return false;
1657
+ }
1658
+ if (lowS && _sig.hasHighS()) return false;
1659
+ if (prehash) msgHash = CURVE.hash(msgHash);
1660
+ const {
1661
+ r,
1662
+ s
1663
+ } = _sig;
1664
+ const h = bits2int_modN(msgHash);
1665
+ const is = invN(s);
1666
+ const u1 = modN(h * is);
1667
+ const u2 = modN(r * is);
1668
+ const R = Point.BASE.multiplyAndAddUnsafe(P, u1, u2)?.toAffine();
1669
+ if (!R) return false;
1670
+ const v = modN(R.x);
1671
+ return v === r;
1672
+ }
1673
+ return {
1674
+ CURVE,
1675
+ getPublicKey,
1676
+ getSharedSecret: getSharedSecret2,
1677
+ sign,
1678
+ verify,
1679
+ ProjectivePoint: Point,
1680
+ Signature,
1681
+ utils
1682
+ };
1683
+ }
1684
+
1685
+ // src/sm2/rng.ts
1686
+ var DEFAULT_PRNG_POOL_SIZE = 16384;
1687
+ var prngPool = new Uint8Array(0);
1688
+ var _syncCrypto;
1689
+ async function initRNGPool() {
1690
+ if ("crypto" in globalThis) {
1691
+ _syncCrypto = globalThis.crypto;
1692
+ return;
1693
+ }
1694
+ if (prngPool.length > DEFAULT_PRNG_POOL_SIZE / 2) return;
1695
+ if ("wx" in globalThis && "getRandomValues" in globalThis.wx) {
1696
+ prngPool = await new Promise(r => {
1697
+ wx.getRandomValues({
1698
+ length: DEFAULT_PRNG_POOL_SIZE,
1699
+ success(res) {
1700
+ r(new Uint8Array(res.randomValues));
1701
+ }
1702
+ });
1703
+ });
1704
+ } else {
1705
+ try {
1706
+ if (globalThis.crypto) {
1707
+ _syncCrypto = globalThis.crypto;
1708
+ } else {
1709
+ const crypto = await import(/* webpackIgnore: true */
1710
+ "crypto");
1711
+ _syncCrypto = crypto.webcrypto;
1712
+ }
1713
+ const array = new Uint8Array(DEFAULT_PRNG_POOL_SIZE);
1714
+ _syncCrypto.getRandomValues(array);
1715
+ prngPool = array;
1716
+ } catch (error) {
1717
+ throw new Error("no available csprng, abort.");
1718
+ }
1719
+ }
1720
+ }
1721
+ initRNGPool();
1722
+ function consumePool(length) {
1723
+ if (prngPool.length > length) {
1724
+ const prng = prngPool.slice(0, length);
1725
+ prngPool = prngPool.slice(length);
1726
+ initRNGPool();
1727
+ return prng;
1728
+ } else {
1729
+ throw new Error("random number pool is not ready or insufficient, prevent getting too long random values or too often.");
1730
+ }
1731
+ }
1732
+ function randomBytes(length = 0) {
1733
+ const array = new Uint8Array(length);
1734
+ if (_syncCrypto) {
1735
+ return _syncCrypto.getRandomValues(array);
1736
+ } else {
1737
+ const result = consumePool(length);
1738
+ return result;
1739
+ }
1740
+ }
1741
+
1742
+ // src/sm3/utils.ts
1743
+ var u8a2 = a => a instanceof Uint8Array;
1744
+ var createView = arr => new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
1745
+ var isLE = new Uint8Array(new Uint32Array([287454020]).buffer)[0] === 68;
1746
+ if (!isLE) throw new Error("Non little-endian hardware is not supported");
1747
+ var hexes2 = Array.from({
1748
+ length: 256
1749
+ }, (v, i) => i.toString(16).padStart(2, "0"));
1750
+ function bytesToHex2(bytes) {
1751
+ if (!u8a2(bytes)) throw new Error("Uint8Array expected");
1752
+ let hex = "";
1753
+ for (let i = 0; i < bytes.length; i++) {
1754
+ hex += hexes2[bytes[i]];
1755
+ }
1756
+ return hex;
1757
+ }
1758
+ var te = typeof TextEncoder != "undefined" && /* @__PURE__ */new TextEncoder();
1759
+ var slc = (v, s, e) => {
1760
+ if (s == null || s < 0) s = 0;
1761
+ if (e == null || e > v.length) e = v.length;
1762
+ return new Uint8Array(v.subarray(s, e));
1763
+ };
1764
+ function strToU8(str) {
1765
+ if (te) return te.encode(str);
1766
+ const l = str.length;
1767
+ let ar = new Uint8Array(str.length + (str.length >> 1));
1768
+ let ai = 0;
1769
+ const w = v => {
1770
+ ar[ai++] = v;
1771
+ };
1772
+ for (let i = 0; i < l; ++i) {
1773
+ if (ai + 5 > ar.length) {
1774
+ const n = new Uint8Array(ai + 8 + (l - i << 1));
1775
+ n.set(ar);
1776
+ ar = n;
1777
+ }
1778
+ let c = str.charCodeAt(i);
1779
+ if (c < 128) w(c);else if (c < 2048) w(192 | c >> 6), w(128 | c & 63);else if (c > 55295 && c < 57344) c = 65536 + (c & 1023 << 10) | str.charCodeAt(++i) & 1023, w(240 | c >> 18), w(128 | c >> 12 & 63), w(128 | c >> 6 & 63), w(128 | c & 63);else w(224 | c >> 12), w(128 | c >> 6 & 63), w(128 | c & 63);
1780
+ }
1781
+ return slc(ar, 0, ai);
1782
+ }
1783
+ function toBytes(data) {
1784
+ if (typeof data === "string") data = strToU8(data);
1785
+ if (!u8a2(data)) throw new Error(`expected Uint8Array, got ${typeof data}`);
1786
+ return data;
1787
+ }
1788
+ var Hash = class {
1789
+ // Safe version that clones internal state
1790
+ clone() {
1791
+ return this._cloneInto();
1792
+ }
1793
+ };
1794
+ function wrapConstructor(hashCons) {
1795
+ const hashC = msg => hashCons().update(toBytes(msg)).digest();
1796
+ const tmp2 = hashCons();
1797
+ hashC.outputLen = tmp2.outputLen;
1798
+ hashC.blockLen = tmp2.blockLen;
1799
+ hashC.create = () => hashCons();
1800
+ return hashC;
1801
+ }
1802
+
1803
+ // src/sm2/sm3.ts
1804
+ var BoolA = (A, B, C) => A & B | A & C | B & C;
1805
+ var BoolB = (A, B, C) => A ^ B ^ C;
1806
+ var BoolC = (A, B, C) => A & B | ~A & C;
1807
+ function setBigUint64(view, byteOffset, value, isLE3) {
1808
+ if (typeof view.setBigUint64 === "function") return view.setBigUint64(byteOffset, value, isLE3);
1809
+ const _32n = BigInt(32);
1810
+ const _u32_max = BigInt(4294967295);
1811
+ const wh = Number(value >> _32n & _u32_max);
1812
+ const wl = Number(value & _u32_max);
1813
+ const h = isLE3 ? 4 : 0;
1814
+ const l = isLE3 ? 0 : 4;
1815
+ view.setUint32(byteOffset + h, wh, isLE3);
1816
+ view.setUint32(byteOffset + l, wl, isLE3);
1817
+ }
1818
+ function rotl(x2, n) {
1819
+ const s = n & 31;
1820
+ return x2 << s | x2 >>> 32 - s;
1821
+ }
1822
+ function P0(X) {
1823
+ return X ^ rotl(X, 9) ^ rotl(X, 17);
1824
+ }
1825
+ function P1(X) {
1826
+ return X ^ rotl(X, 15) ^ rotl(X, 23);
1827
+ }
1828
+ var SHA2 = class extends Hash {
1829
+ constructor(blockLen, outputLen, padOffset, isLE3) {
1830
+ super();
1831
+ this.blockLen = blockLen;
1832
+ this.outputLen = outputLen;
1833
+ this.padOffset = padOffset;
1834
+ this.isLE = isLE3;
1835
+ // For partial updates less than block size
1836
+ __publicField(this, "buffer");
1837
+ __publicField(this, "view");
1838
+ __publicField(this, "finished", false);
1839
+ __publicField(this, "length", 0);
1840
+ __publicField(this, "pos", 0);
1841
+ __publicField(this, "destroyed", false);
1842
+ this.buffer = new Uint8Array(blockLen);
1843
+ this.view = createView(this.buffer);
1844
+ }
1845
+ update(data) {
1846
+ const {
1847
+ view,
1848
+ buffer,
1849
+ blockLen
1850
+ } = this;
1851
+ data = toBytes(data);
1852
+ const len = data.length;
1853
+ for (let pos = 0; pos < len;) {
1854
+ const take = Math.min(blockLen - this.pos, len - pos);
1855
+ if (take === blockLen) {
1856
+ const dataView = createView(data);
1857
+ for (; blockLen <= len - pos; pos += blockLen) this.process(dataView, pos);
1858
+ continue;
1859
+ }
1860
+ buffer.set(data.subarray(pos, pos + take), this.pos);
1861
+ this.pos += take;
1862
+ pos += take;
1863
+ if (this.pos === blockLen) {
1864
+ this.process(view, 0);
1865
+ this.pos = 0;
1866
+ }
1867
+ }
1868
+ this.length += data.length;
1869
+ this.roundClean();
1870
+ return this;
1871
+ }
1872
+ digestInto(out) {
1873
+ this.finished = true;
1874
+ const {
1875
+ buffer,
1876
+ view,
1877
+ blockLen,
1878
+ isLE: isLE3
1879
+ } = this;
1880
+ let {
1881
+ pos
1882
+ } = this;
1883
+ buffer[pos++] = 128;
1884
+ this.buffer.subarray(pos).fill(0);
1885
+ if (this.padOffset > blockLen - pos) {
1886
+ this.process(view, 0);
1887
+ pos = 0;
1888
+ }
1889
+ for (let i = pos; i < blockLen; i++) buffer[i] = 0;
1890
+ setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE3);
1891
+ this.process(view, 0);
1892
+ const oview = createView(out);
1893
+ const len = this.outputLen;
1894
+ if (len % 4) throw new Error("_sha2: outputLen should be aligned to 32bit");
1895
+ const outLen = len / 4;
1896
+ const state = this.get();
1897
+ if (outLen > state.length) throw new Error("_sha2: outputLen bigger than state");
1898
+ for (let i = 0; i < outLen; i++) oview.setUint32(4 * i, state[i], isLE3);
1899
+ }
1900
+ digest() {
1901
+ const {
1902
+ buffer,
1903
+ outputLen
1904
+ } = this;
1905
+ this.digestInto(buffer);
1906
+ const res = buffer.slice(0, outputLen);
1907
+ this.destroy();
1908
+ return res;
1909
+ }
1910
+ _cloneInto(to) {
1911
+ to || (to = new this.constructor());
1912
+ to.set(...this.get());
1913
+ const {
1914
+ blockLen,
1915
+ buffer,
1916
+ length,
1917
+ finished,
1918
+ destroyed,
1919
+ pos
1920
+ } = this;
1921
+ to.length = length;
1922
+ to.pos = pos;
1923
+ to.finished = finished;
1924
+ to.destroyed = destroyed;
1925
+ if (length % blockLen) to.buffer.set(buffer);
1926
+ return to;
1927
+ }
1928
+ };
1929
+ var IV = new Uint32Array([1937774191, 1226093241, 388252375, 3666478592, 2842636476, 372324522, 3817729613, 2969243214]);
1930
+ var SM3_W = new Uint32Array(68);
1931
+ var SM3_M = new Uint32Array(64);
1932
+ var T1 = 2043430169;
1933
+ var T2 = 2055708042;
1934
+ var SM3 = class extends SHA2 {
1935
+ constructor() {
1936
+ super(64, 32, 8, false);
1937
+ // We cannot use array here since array allows indexing by variable
1938
+ // which means optimizer/compiler cannot use registers.
1939
+ __publicField(this, "A", IV[0] | 0);
1940
+ __publicField(this, "B", IV[1] | 0);
1941
+ __publicField(this, "C", IV[2] | 0);
1942
+ __publicField(this, "D", IV[3] | 0);
1943
+ __publicField(this, "E", IV[4] | 0);
1944
+ __publicField(this, "F", IV[5] | 0);
1945
+ __publicField(this, "G", IV[6] | 0);
1946
+ __publicField(this, "H", IV[7] | 0);
1947
+ }
1948
+ get() {
1949
+ const {
1950
+ A,
1951
+ B,
1952
+ C,
1953
+ D,
1954
+ E,
1955
+ F,
1956
+ G,
1957
+ H
1958
+ } = this;
1959
+ return [A, B, C, D, E, F, G, H];
1960
+ }
1961
+ // prettier-ignore
1962
+ set(A, B, C, D, E, F, G, H) {
1963
+ this.A = A | 0;
1964
+ this.B = B | 0;
1965
+ this.C = C | 0;
1966
+ this.D = D | 0;
1967
+ this.E = E | 0;
1968
+ this.F = F | 0;
1969
+ this.G = G | 0;
1970
+ this.H = H | 0;
1971
+ }
1972
+ process(view, offset) {
1973
+ for (let i = 0; i < 16; i++, offset += 4) SM3_W[i] = view.getUint32(offset, false);
1974
+ for (let i = 16; i < 68; i++) {
1975
+ SM3_W[i] = P1(SM3_W[i - 16] ^ SM3_W[i - 9] ^ rotl(SM3_W[i - 3], 15)) ^ rotl(SM3_W[i - 13], 7) ^ SM3_W[i - 6];
1976
+ }
1977
+ for (let i = 0; i < 64; i++) {
1978
+ SM3_M[i] = SM3_W[i] ^ SM3_W[i + 4];
1979
+ }
1980
+ let {
1981
+ A,
1982
+ B,
1983
+ C,
1984
+ D,
1985
+ E,
1986
+ F,
1987
+ G,
1988
+ H
1989
+ } = this;
1990
+ for (let j = 0; j < 64; j++) {
1991
+ let small = j >= 0 && j <= 15;
1992
+ let T = small ? T1 : T2;
1993
+ let SS1 = rotl(rotl(A, 12) + E + rotl(T, j), 7);
1994
+ let SS2 = SS1 ^ rotl(A, 12);
1995
+ let TT1 = (small ? BoolB(A, B, C) : BoolA(A, B, C)) + D + SS2 + SM3_M[j] | 0;
1996
+ let TT2 = (small ? BoolB(E, F, G) : BoolC(E, F, G)) + H + SS1 + SM3_W[j] | 0;
1997
+ D = C;
1998
+ C = rotl(B, 9);
1999
+ B = A;
2000
+ A = TT1;
2001
+ H = G;
2002
+ G = rotl(F, 19);
2003
+ F = E;
2004
+ E = P0(TT2);
2005
+ }
2006
+ A = A ^ this.A | 0;
2007
+ B = B ^ this.B | 0;
2008
+ C = C ^ this.C | 0;
2009
+ D = D ^ this.D | 0;
2010
+ E = E ^ this.E | 0;
2011
+ F = F ^ this.F | 0;
2012
+ G = G ^ this.G | 0;
2013
+ H = H ^ this.H | 0;
2014
+ this.set(A, B, C, D, E, F, G, H);
2015
+ }
2016
+ roundClean() {
2017
+ SM3_W.fill(0);
2018
+ }
2019
+ destroy() {
2020
+ this.set(0, 0, 0, 0, 0, 0, 0, 0);
2021
+ this.buffer.fill(0);
2022
+ }
2023
+ };
2024
+ var sm3 = wrapConstructor(() => new SM3());
2025
+
2026
+ // src/sm2/hmac.ts
2027
+ var HMAC = class extends Hash {
2028
+ constructor(hash, _key) {
2029
+ super();
2030
+ __publicField(this, "oHash");
2031
+ __publicField(this, "iHash");
2032
+ __publicField(this, "blockLen");
2033
+ __publicField(this, "outputLen");
2034
+ __publicField(this, "finished", false);
2035
+ __publicField(this, "destroyed", false);
2036
+ const key = toBytes(_key);
2037
+ this.iHash = hash.create();
2038
+ if (typeof this.iHash.update !== "function") throw new Error("Expected instance of class which extends utils.Hash");
2039
+ this.blockLen = this.iHash.blockLen;
2040
+ this.outputLen = this.iHash.outputLen;
2041
+ const blockLen = this.blockLen;
2042
+ const pad = new Uint8Array(blockLen);
2043
+ pad.set(key.length > blockLen ? hash.create().update(key).digest() : key);
2044
+ for (let i = 0; i < pad.length; i++) pad[i] ^= 54;
2045
+ this.iHash.update(pad);
2046
+ this.oHash = hash.create();
2047
+ for (let i = 0; i < pad.length; i++) pad[i] ^= 54 ^ 92;
2048
+ this.oHash.update(pad);
2049
+ pad.fill(0);
2050
+ }
2051
+ update(buf) {
2052
+ this.iHash.update(buf);
2053
+ return this;
2054
+ }
2055
+ digestInto(out) {
2056
+ this.finished = true;
2057
+ this.iHash.digestInto(out);
2058
+ this.oHash.update(out);
2059
+ this.oHash.digestInto(out);
2060
+ this.destroy();
2061
+ }
2062
+ digest() {
2063
+ const out = new Uint8Array(this.oHash.outputLen);
2064
+ this.digestInto(out);
2065
+ return out;
2066
+ }
2067
+ _cloneInto(to) {
2068
+ to || (to = Object.create(Object.getPrototypeOf(this), {}));
2069
+ const {
2070
+ oHash,
2071
+ iHash,
2072
+ finished,
2073
+ destroyed,
2074
+ blockLen,
2075
+ outputLen
2076
+ } = this;
2077
+ to = to;
2078
+ to.finished = finished;
2079
+ to.destroyed = destroyed;
2080
+ to.blockLen = blockLen;
2081
+ to.outputLen = outputLen;
2082
+ to.oHash = oHash._cloneInto(to.oHash);
2083
+ to.iHash = iHash._cloneInto(to.iHash);
2084
+ return to;
2085
+ }
2086
+ destroy() {
2087
+ this.destroyed = true;
2088
+ this.oHash.destroy();
2089
+ this.iHash.destroy();
2090
+ }
2091
+ };
2092
+ var hmac = (hash, key, message) => new HMAC(hash, key).update(message).digest();
2093
+ hmac.create = (hash, key) => new HMAC(hash, key);
2094
+
2095
+ // src/sm2/ec.ts
2096
+ var sm2Fp = Field(BigInt("115792089210356248756420345214020892766250353991924191454421193933289684991999"));
2097
+ var sm2Curve = weierstrass({
2098
+ // sm2: short weierstrass.
2099
+ a: BigInt("115792089210356248756420345214020892766250353991924191454421193933289684991996"),
2100
+ b: BigInt("18505919022281880113072981827955639221458448578012075254857346196103069175443"),
2101
+ Fp: sm2Fp,
2102
+ h: ONE,
2103
+ n: BigInt("115792089210356248756420345214020892766061623724957744567843809356293439045923"),
2104
+ Gx: BigInt("22963146547237050559479531362550074578802567295341616970375194840604139615431"),
2105
+ Gy: BigInt("85132369209828568825618990617112496413088388631904505083283536607588877201568"),
2106
+ hash: sm3,
2107
+ hmac: (key, ...msgs) => hmac(sm3, key, concatBytes(...msgs)),
2108
+ randomBytes
2109
+ });
2110
+ var field = Field(BigInt(sm2Curve.CURVE.n));
2111
+
2112
+ // src/sm2/utils.ts
2113
+ function generateKeyPairHex(str) {
2114
+ const privateKey = str ? numberToBytesBE(mod(BigInt(str), ONE) + ONE, 32) : sm2Curve.utils.randomPrivateKey();
2115
+ const publicKey = sm2Curve.getPublicKey(privateKey, false);
2116
+ const privPad = leftPad(bytesToHex(privateKey), 64);
2117
+ const pubPad = leftPad(bytesToHex(publicKey), 64);
2118
+ return {
2119
+ privateKey: privPad,
2120
+ publicKey: pubPad
2121
+ };
2122
+ }
2123
+ function compressPublicKeyHex(s) {
2124
+ if (s.length !== 130) throw new Error("Invalid public key to compress");
2125
+ const len = (s.length - 2) / 2;
2126
+ const xHex = s.substring(2, 2 + len);
2127
+ const y = hexToNumber(s.substring(len + 2, len + len + 2));
2128
+ let prefix = "03";
2129
+ if (mod(y, TWO) === ZERO) prefix = "02";
2130
+ return prefix + xHex;
2131
+ }
2132
+ function utf8ToHex(input) {
2133
+ const bytes = strToU8(input);
2134
+ return bytesToHex(bytes);
2135
+ }
2136
+ function leftPad(input, num) {
2137
+ if (input.length >= num) return input;
2138
+ return new Array(num - input.length + 1).join("0") + input;
2139
+ }
2140
+ function arrayToHex(arr) {
2141
+ return arr.map(item => {
2142
+ const hex = item.toString(16);
2143
+ return hex.length === 1 ? "0" + hex : hex;
2144
+ }).join("");
2145
+ }
2146
+ function arrayToUtf8(arr) {
2147
+ const str = [];
2148
+ for (let i = 0, len = arr.length; i < len; i++) {
2149
+ if (arr[i] >= 240 && arr[i] <= 247) {
2150
+ str.push(String.fromCodePoint(((arr[i] & 7) << 18) + ((arr[i + 1] & 63) << 12) + ((arr[i + 2] & 63) << 6) + (arr[i + 3] & 63)));
2151
+ i += 3;
2152
+ } else if (arr[i] >= 224 && arr[i] <= 239) {
2153
+ str.push(String.fromCodePoint(((arr[i] & 15) << 12) + ((arr[i + 1] & 63) << 6) + (arr[i + 2] & 63)));
2154
+ i += 2;
2155
+ } else if (arr[i] >= 192 && arr[i] <= 223) {
2156
+ str.push(String.fromCodePoint(((arr[i] & 31) << 6) + (arr[i + 1] & 63)));
2157
+ i++;
2158
+ } else {
2159
+ str.push(String.fromCodePoint(arr[i]));
2160
+ }
2161
+ }
2162
+ return str.join("");
2163
+ }
2164
+ function hexToArray(hexStr) {
2165
+ let hexStrLength = hexStr.length;
2166
+ if (hexStrLength % 2 !== 0) {
2167
+ hexStr = leftPad(hexStr, hexStrLength + 1);
2168
+ }
2169
+ hexStrLength = hexStr.length;
2170
+ const wordLength = hexStrLength / 2;
2171
+ const words = new Uint8Array(wordLength);
2172
+ for (let i = 0; i < wordLength; i++) {
2173
+ words[i] = parseInt(hexStr.substring(i * 2, i * 2 + 2), 16);
2174
+ }
2175
+ return words;
2176
+ }
2177
+ function verifyPublicKey(publicKey) {
2178
+ const point = sm2Curve.ProjectivePoint.fromHex(publicKey);
2179
+ if (!point) return false;
2180
+ try {
2181
+ point.assertValidity();
2182
+ return true;
2183
+ } catch (error) {
2184
+ return false;
2185
+ }
2186
+ }
2187
+ function comparePublicKeyHex(publicKey1, publicKey2) {
2188
+ const point1 = sm2Curve.ProjectivePoint.fromHex(publicKey1);
2189
+ if (!point1) return false;
2190
+ const point2 = sm2Curve.ProjectivePoint.fromHex(publicKey2);
2191
+ if (!point2) return false;
2192
+ return point1.equals(point2);
2193
+ }
2194
+
2195
+ // src/sm3/index.ts
2196
+ function utf8ToArray(str) {
2197
+ const arr = [];
2198
+ for (let i = 0, len = str.length; i < len; i++) {
2199
+ const point = str.codePointAt(i);
2200
+ if (point <= 127) {
2201
+ arr.push(point);
2202
+ } else if (point <= 2047) {
2203
+ arr.push(192 | point >>> 6);
2204
+ arr.push(128 | point & 63);
2205
+ } else if (point <= 55295 || point >= 57344 && point <= 65535) {
2206
+ arr.push(224 | point >>> 12);
2207
+ arr.push(128 | point >>> 6 & 63);
2208
+ arr.push(128 | point & 63);
2209
+ } else if (point >= 65536 && point <= 1114111) {
2210
+ i++;
2211
+ arr.push(240 | point >>> 18 & 28);
2212
+ arr.push(128 | point >>> 12 & 63);
2213
+ arr.push(128 | point >>> 6 & 63);
2214
+ arr.push(128 | point & 63);
2215
+ } else {
2216
+ arr.push(point);
2217
+ throw new Error("input is not supported");
2218
+ }
2219
+ }
2220
+ return new Uint8Array(arr);
2221
+ }
2222
+ function sm32(input, options) {
2223
+ input = typeof input === "string" ? utf8ToArray(input) : input;
2224
+ if (options) {
2225
+ const mode = options.mode || "hmac";
2226
+ if (mode !== "hmac") throw new Error("invalid mode");
2227
+ let key = options.key;
2228
+ if (!key) throw new Error("invalid key");
2229
+ key = typeof key === "string" ? hexToArray(key) : key;
2230
+ return bytesToHex2(hmac(sm3, key, input));
2231
+ }
2232
+ return bytesToHex2(sm3(input));
2233
+ }
2234
+
2235
+ // src/sm2/kdf.ts
2236
+ function kdf(z, keylen, iv) {
2237
+ z = typeof z === "string" ? utf8ToArray(z) : z;
2238
+ const IV2 = iv == null ? EmptyArray : typeof iv === "string" ? utf8ToArray(iv) : iv;
2239
+ let msg = new Uint8Array(keylen);
2240
+ let ct = 1;
2241
+ let offset = 0;
2242
+ let t = EmptyArray;
2243
+ const ctShift = new Uint8Array(4);
2244
+ const nextT = () => {
2245
+ ctShift[0] = ct >> 24 & 255;
2246
+ ctShift[1] = ct >> 16 & 255;
2247
+ ctShift[2] = ct >> 8 & 255;
2248
+ ctShift[3] = ct & 255;
2249
+ t = sm3(concatBytes(z, ctShift, IV2));
2250
+ ct++;
2251
+ offset = 0;
2252
+ };
2253
+ nextT();
2254
+ for (let i = 0, len = msg.length; i < len; i++) {
2255
+ if (offset === t.length) nextT();
2256
+ msg[i] = t[offset++] & 255;
2257
+ }
2258
+ return msg;
2259
+ }
2260
+
2261
+ // src/sm2/kx.ts
2262
+ var wPow2 = hexToNumber("80000000000000000000000000000000");
2263
+ var wPow2Sub1 = hexToNumber("7fffffffffffffffffffffffffffffff");
2264
+ function calculateSharedKey(keypairA, ephemeralKeypairA, publicKeyB, ephemeralPublicKeyB, sharedKeyLength, isRecipient = false, idA = "1234567812345678", idB = "1234567812345678") {
2265
+ const RA = sm2Curve.ProjectivePoint.fromHex(ephemeralKeypairA.publicKey);
2266
+ const RB = sm2Curve.ProjectivePoint.fromHex(ephemeralPublicKeyB);
2267
+ const PB = sm2Curve.ProjectivePoint.fromHex(publicKeyB);
2268
+ let ZA = getZ(keypairA.publicKey, idA);
2269
+ let ZB = getZ(publicKeyB, idB);
2270
+ if (isRecipient) {
2271
+ [ZA, ZB] = [ZB, ZA];
2272
+ }
2273
+ const rA = hexToNumber(ephemeralKeypairA.privateKey);
2274
+ const dA = hexToNumber(keypairA.privateKey);
2275
+ const x1 = RA.x;
2276
+ const x1_ = wPow2 + (x1 & wPow2Sub1);
2277
+ const tA = field.add(dA, field.mulN(x1_, rA));
2278
+ const x2 = RB.x;
2279
+ const x2_ = field.add(wPow2, x2 & wPow2Sub1);
2280
+ const U = RB.multiply(x2_).add(PB).multiply(tA);
2281
+ const xU = hexToArray(leftPad(numberToHexUnpadded(U.x), 64));
2282
+ const yU = hexToArray(leftPad(numberToHexUnpadded(U.y), 64));
2283
+ const KA = kdf(concatBytes(xU, yU, ZA, ZB), sharedKeyLength);
2284
+ return KA;
2285
+ }
2286
+
2287
+ // src/sm2/index.ts
2288
+ var {
2289
+ getSharedSecret
2290
+ } = sm2Curve;
2291
+ function xorCipherStream(x2, y2, msg) {
2292
+ const stream = kdf(concatBytes(x2, y2), msg.length);
2293
+ for (let i = 0, len = msg.length; i < len; i++) {
2294
+ msg[i] ^= stream[i] & 255;
2295
+ }
2296
+ }
2297
+ var C1C2C3 = 0;
2298
+ var EmptyArray = new Uint8Array();
2299
+ function doEncrypt(msg, publicKey, cipherMode = 1, options) {
2300
+ const msgArr = typeof msg === "string" ? hexToArray(utf8ToHex(msg)) : Uint8Array.from(msg);
2301
+ const publicKeyPoint = typeof publicKey === "string" ? sm2Curve.ProjectivePoint.fromHex(publicKey) : publicKey;
2302
+ const keypair = generateKeyPairHex();
2303
+ const k = hexToNumber(keypair.privateKey);
2304
+ let c1 = keypair.publicKey;
2305
+ if (c1.length > 128) c1 = c1.substring(c1.length - 128);
2306
+ const p = publicKeyPoint.multiply(k);
2307
+ const x2 = hexToArray(leftPad(numberToHexUnpadded(p.x), 64));
2308
+ const y2 = hexToArray(leftPad(numberToHexUnpadded(p.y), 64));
2309
+ const c3 = bytesToHex2(sm3(concatBytes(x2, msgArr, y2)));
2310
+ xorCipherStream(x2, y2, msgArr);
2311
+ const c2 = bytesToHex2(msgArr);
2312
+ if (options?.asn1) {
2313
+ const point = sm2Curve.ProjectivePoint.fromHex(keypair.publicKey);
2314
+ const encode = cipherMode === C1C2C3 ? encodeEnc(point.x, point.y, c2, c3) : encodeEnc(point.x, point.y, c3, c2);
2315
+ return encode;
2316
+ }
2317
+ return cipherMode === C1C2C3 ? c1 + c2 + c3 : c1 + c3 + c2;
2318
+ }
2319
+ function doDecrypt(encryptData, privateKey, cipherMode = 1, options) {
2320
+ const {
2321
+ output = "string",
2322
+ asn1 = false
2323
+ } = options || {};
2324
+ const privateKeyInteger = hexToNumber(privateKey);
2325
+ let c1;
2326
+ let c2;
2327
+ let c3;
2328
+ if (asn1) {
2329
+ const {
2330
+ x: x3,
2331
+ y,
2332
+ cipher,
2333
+ hash
2334
+ } = decodeEnc(encryptData);
2335
+ c1 = sm2Curve.ProjectivePoint.fromAffine({
2336
+ x: x3,
2337
+ y
2338
+ });
2339
+ c3 = hash;
2340
+ c2 = cipher;
2341
+ if (cipherMode === C1C2C3) {
2342
+ [c2, c3] = [c3, c2];
2343
+ }
2344
+ } else {
2345
+ c1 = sm2Curve.ProjectivePoint.fromHex("04" + encryptData.substring(0, 128));
2346
+ c3 = encryptData.substring(128, 128 + 64);
2347
+ c2 = encryptData.substring(128 + 64);
2348
+ if (cipherMode === C1C2C3) {
2349
+ c3 = encryptData.substring(encryptData.length - 64);
2350
+ c2 = encryptData.substring(128, encryptData.length - 64);
2351
+ }
2352
+ }
2353
+ const msg = hexToArray(c2);
2354
+ const p = c1.multiply(privateKeyInteger);
2355
+ const x2 = hexToArray(leftPad(numberToHexUnpadded(p.x), 64));
2356
+ const y2 = hexToArray(leftPad(numberToHexUnpadded(p.y), 64));
2357
+ xorCipherStream(x2, y2, msg);
2358
+ const checkC3 = arrayToHex(Array.from(sm3(concatBytes(x2, msg, y2))));
2359
+ if (checkC3 === c3.toLowerCase()) {
2360
+ return output === "array" ? msg : arrayToUtf8(msg);
2361
+ } else {
2362
+ return output === "array" ? [] : "";
2363
+ }
2364
+ }
2365
+ function doSignature(msg, privateKey, options = {}) {
2366
+ let {
2367
+ pointPool,
2368
+ der,
2369
+ hash,
2370
+ publicKey,
2371
+ userId
2372
+ } = options;
2373
+ let hashHex = typeof msg === "string" ? utf8ToHex(msg) : arrayToHex(Array.from(msg));
2374
+ if (hash) {
2375
+ publicKey = publicKey || getPublicKeyFromPrivateKey(privateKey);
2376
+ hashHex = getHash(hashHex, publicKey, userId);
2377
+ }
2378
+ const dA = hexToNumber(privateKey);
2379
+ const e = hexToNumber(hashHex);
2380
+ let k = null;
2381
+ let r = null;
2382
+ let s = null;
2383
+ do {
2384
+ do {
2385
+ let point;
2386
+ if (pointPool && pointPool.length) {
2387
+ point = pointPool.pop();
2388
+ } else {
2389
+ point = getPoint();
2390
+ }
2391
+ k = point.k;
2392
+ r = field.add(e, point.x1);
2393
+ } while (r === ZERO || r + k === sm2Curve.CURVE.n);
2394
+ s = field.mul(field.inv(field.addN(dA, ONE)), field.subN(k, field.mulN(r, dA)));
2395
+ } while (s === ZERO);
2396
+ if (der) return encodeDer(r, s);
2397
+ return leftPad(numberToHexUnpadded(r), 64) + leftPad(numberToHexUnpadded(s), 64);
2398
+ }
2399
+ function doVerifySignature(msg, signHex, publicKey, options = {}) {
2400
+ let hashHex;
2401
+ const {
2402
+ hash,
2403
+ der,
2404
+ userId
2405
+ } = options;
2406
+ const publicKeyHex = typeof publicKey === "string" ? publicKey : publicKey.toHex(false);
2407
+ if (hash) {
2408
+ hashHex = getHash(typeof msg === "string" ? utf8ToHex(msg) : msg, publicKeyHex, userId);
2409
+ } else {
2410
+ hashHex = typeof msg === "string" ? utf8ToHex(msg) : arrayToHex(Array.from(msg));
2411
+ }
2412
+ let r;
2413
+ let s;
2414
+ if (der) {
2415
+ const decodeDerObj = decodeDer(signHex);
2416
+ r = decodeDerObj.r;
2417
+ s = decodeDerObj.s;
2418
+ } else {
2419
+ r = hexToNumber(signHex.substring(0, 64));
2420
+ s = hexToNumber(signHex.substring(64));
2421
+ }
2422
+ const PA = typeof publicKey === "string" ? sm2Curve.ProjectivePoint.fromHex(publicKey) : publicKey;
2423
+ const e = hexToNumber(hashHex);
2424
+ const t = field.add(r, s);
2425
+ if (t === ZERO) return false;
2426
+ const x1y1 = sm2Curve.ProjectivePoint.BASE.multiply(s).add(PA.multiply(t));
2427
+ const R = field.add(e, x1y1.x);
2428
+ return r === R;
2429
+ }
2430
+ function getZ(publicKey, userId = "1234567812345678") {
2431
+ userId = utf8ToHex(userId);
2432
+ const a = leftPad(numberToHexUnpadded(sm2Curve.CURVE.a), 64);
2433
+ const b = leftPad(numberToHexUnpadded(sm2Curve.CURVE.b), 64);
2434
+ const gx = leftPad(numberToHexUnpadded(sm2Curve.ProjectivePoint.BASE.x), 64);
2435
+ const gy = leftPad(numberToHexUnpadded(sm2Curve.ProjectivePoint.BASE.y), 64);
2436
+ let px;
2437
+ let py;
2438
+ if (publicKey.length === 128) {
2439
+ px = publicKey.substring(0, 64);
2440
+ py = publicKey.substring(64, 128);
2441
+ } else {
2442
+ const point = sm2Curve.ProjectivePoint.fromHex(publicKey);
2443
+ px = leftPad(numberToHexUnpadded(point.x), 64);
2444
+ py = leftPad(numberToHexUnpadded(point.y), 64);
2445
+ }
2446
+ const data = hexToArray(userId + a + b + gx + gy + px + py);
2447
+ const entl = userId.length * 4;
2448
+ const z = sm3(concatBytes(new Uint8Array([entl >> 8 & 255, entl & 255]), data));
2449
+ return z;
2450
+ }
2451
+ function getHash(hashHex, publicKey, userId = "1234567812345678") {
2452
+ const z = getZ(publicKey, userId);
2453
+ return bytesToHex2(sm3(concatBytes(z, typeof hashHex === "string" ? hexToArray(hashHex) : hashHex)));
2454
+ }
2455
+ function precomputePublicKey(publicKey, windowSize) {
2456
+ const point = sm2Curve.ProjectivePoint.fromHex(publicKey);
2457
+ return sm2Curve.utils.precompute(windowSize, point);
2458
+ }
2459
+ function getPublicKeyFromPrivateKey(privateKey) {
2460
+ const pubKey = sm2Curve.getPublicKey(privateKey, false);
2461
+ const pubPad = leftPad(bytesToHex(pubKey), 64);
2462
+ return pubPad;
2463
+ }
2464
+ function getPoint() {
2465
+ const keypair = generateKeyPairHex();
2466
+ const PA = sm2Curve.ProjectivePoint.fromHex(keypair.publicKey);
2467
+ const k = hexToNumber(keypair.privateKey);
2468
+ return {
2469
+ ...keypair,
2470
+ k,
2471
+ x1: PA.x
2472
+ };
2473
+ }
2474
+
2475
+ // src/sm4/index.ts
2476
+ var sm4_exports = _exports.sm4 = {};
2477
+ __export(sm4_exports, {
2478
+ decrypt: () => decrypt,
2479
+ encrypt: () => encrypt,
2480
+ sm4: () => sm4
2481
+ });
2482
+
2483
+ // node_modules/.pnpm/@noble+ciphers@1.2.1/node_modules/@noble/ciphers/esm/_assert.js
2484
+ function isBytes(a) {
2485
+ return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array";
2486
+ }
2487
+ function abytes(b, ...lengths) {
2488
+ if (!isBytes(b)) throw new Error("Uint8Array expected");
2489
+ if (lengths.length > 0 && !lengths.includes(b.length)) throw new Error("Uint8Array expected of length " + lengths + ", got length=" + b.length);
2490
+ }
2491
+ function aexists(instance, checkFinished = true) {
2492
+ if (instance.destroyed) throw new Error("Hash instance has been destroyed");
2493
+ if (checkFinished && instance.finished) throw new Error("Hash#digest() has already been called");
2494
+ }
2495
+ function aoutput(out, instance) {
2496
+ abytes(out);
2497
+ const min = instance.outputLen;
2498
+ if (out.length < min) {
2499
+ throw new Error("digestInto() expects output buffer of length at least " + min);
2500
+ }
2501
+ }
2502
+
2503
+ // node_modules/.pnpm/@noble+ciphers@1.2.1/node_modules/@noble/ciphers/esm/utils.js
2504
+ var u32 = arr => new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));
2505
+ var createView2 = arr => new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
2506
+ var isLE2 = new Uint8Array(new Uint32Array([287454020]).buffer)[0] === 68;
2507
+ if (!isLE2) throw new Error("Non little-endian hardware is not supported");
2508
+ function utf8ToBytes2(str) {
2509
+ if (typeof str !== "string") throw new Error("string expected");
2510
+ return new Uint8Array(new TextEncoder().encode(str));
2511
+ }
2512
+ function toBytes2(data) {
2513
+ if (typeof data === "string") data = utf8ToBytes2(data);else if (isBytes(data)) data = copyBytes(data);else throw new Error("Uint8Array expected, got " + typeof data);
2514
+ return data;
2515
+ }
2516
+ function setBigUint642(view, byteOffset, value, isLE3) {
2517
+ if (typeof view.setBigUint64 === "function") return view.setBigUint64(byteOffset, value, isLE3);
2518
+ const _32n = BigInt(32);
2519
+ const _u32_max = BigInt(4294967295);
2520
+ const wh = Number(value >> _32n & _u32_max);
2521
+ const wl = Number(value & _u32_max);
2522
+ const h = isLE3 ? 4 : 0;
2523
+ const l = isLE3 ? 0 : 4;
2524
+ view.setUint32(byteOffset + h, wh, isLE3);
2525
+ view.setUint32(byteOffset + l, wl, isLE3);
2526
+ }
2527
+ function copyBytes(bytes) {
2528
+ return Uint8Array.from(bytes);
2529
+ }
2530
+ function clean(...arrays) {
2531
+ for (let i = 0; i < arrays.length; i++) {
2532
+ arrays[i].fill(0);
2533
+ }
2534
+ }
2535
+
2536
+ // node_modules/.pnpm/@noble+ciphers@1.2.1/node_modules/@noble/ciphers/esm/_polyval.js
2537
+ var BLOCK_SIZE = 16;
2538
+ var ZEROS16 = /* @__PURE__ */new Uint8Array(16);
2539
+ var ZEROS32 = u32(ZEROS16);
2540
+ var POLY = 225;
2541
+ var mul2 = (s0, s1, s2, s3) => {
2542
+ const hiBit = s3 & 1;
2543
+ return {
2544
+ s3: s2 << 31 | s3 >>> 1,
2545
+ s2: s1 << 31 | s2 >>> 1,
2546
+ s1: s0 << 31 | s1 >>> 1,
2547
+ s0: s0 >>> 1 ^ POLY << 24 & -(hiBit & 1)
2548
+ // reduce % poly
2549
+ };
2550
+ };
2551
+ var swapLE = n => (n >>> 0 & 255) << 24 | (n >>> 8 & 255) << 16 | (n >>> 16 & 255) << 8 | n >>> 24 & 255 | 0;
2552
+ function _toGHASHKey(k) {
2553
+ k.reverse();
2554
+ const hiBit = k[15] & 1;
2555
+ let carry = 0;
2556
+ for (let i = 0; i < k.length; i++) {
2557
+ const t = k[i];
2558
+ k[i] = t >>> 1 | carry;
2559
+ carry = (t & 1) << 7;
2560
+ }
2561
+ k[0] ^= -hiBit & 225;
2562
+ return k;
2563
+ }
2564
+ var estimateWindow = bytes => {
2565
+ if (bytes > 64 * 1024) return 8;
2566
+ if (bytes > 1024) return 4;
2567
+ return 2;
2568
+ };
2569
+ var GHASH = class {
2570
+ // We select bits per window adaptively based on expectedLength
2571
+ constructor(key, expectedLength) {
2572
+ this.blockLen = BLOCK_SIZE;
2573
+ this.outputLen = BLOCK_SIZE;
2574
+ this.s0 = 0;
2575
+ this.s1 = 0;
2576
+ this.s2 = 0;
2577
+ this.s3 = 0;
2578
+ this.finished = false;
2579
+ key = toBytes2(key);
2580
+ abytes(key, 16);
2581
+ const kView = createView2(key);
2582
+ let k0 = kView.getUint32(0, false);
2583
+ let k1 = kView.getUint32(4, false);
2584
+ let k2 = kView.getUint32(8, false);
2585
+ let k3 = kView.getUint32(12, false);
2586
+ const doubles = [];
2587
+ for (let i = 0; i < 128; i++) {
2588
+ doubles.push({
2589
+ s0: swapLE(k0),
2590
+ s1: swapLE(k1),
2591
+ s2: swapLE(k2),
2592
+ s3: swapLE(k3)
2593
+ });
2594
+ ({
2595
+ s0: k0,
2596
+ s1: k1,
2597
+ s2: k2,
2598
+ s3: k3
2599
+ } = mul2(k0, k1, k2, k3));
2600
+ }
2601
+ const W = estimateWindow(expectedLength || 1024);
2602
+ if (![1, 2, 4, 8].includes(W)) throw new Error("ghash: invalid window size, expected 2, 4 or 8");
2603
+ this.W = W;
2604
+ const bits = 128;
2605
+ const windows = bits / W;
2606
+ const windowSize = this.windowSize = 2 ** W;
2607
+ const items = [];
2608
+ for (let w = 0; w < windows; w++) {
2609
+ for (let byte = 0; byte < windowSize; byte++) {
2610
+ let s0 = 0,
2611
+ s1 = 0,
2612
+ s2 = 0,
2613
+ s3 = 0;
2614
+ for (let j = 0; j < W; j++) {
2615
+ const bit = byte >>> W - j - 1 & 1;
2616
+ if (!bit) continue;
2617
+ const {
2618
+ s0: d0,
2619
+ s1: d1,
2620
+ s2: d2,
2621
+ s3: d3
2622
+ } = doubles[W * w + j];
2623
+ s0 ^= d0, s1 ^= d1, s2 ^= d2, s3 ^= d3;
2624
+ }
2625
+ items.push({
2626
+ s0,
2627
+ s1,
2628
+ s2,
2629
+ s3
2630
+ });
2631
+ }
2632
+ }
2633
+ this.t = items;
2634
+ }
2635
+ _updateBlock(s0, s1, s2, s3) {
2636
+ s0 ^= this.s0, s1 ^= this.s1, s2 ^= this.s2, s3 ^= this.s3;
2637
+ const {
2638
+ W,
2639
+ t,
2640
+ windowSize
2641
+ } = this;
2642
+ let o0 = 0,
2643
+ o1 = 0,
2644
+ o2 = 0,
2645
+ o3 = 0;
2646
+ const mask = (1 << W) - 1;
2647
+ let w = 0;
2648
+ for (const num of [s0, s1, s2, s3]) {
2649
+ for (let bytePos = 0; bytePos < 4; bytePos++) {
2650
+ const byte = num >>> 8 * bytePos & 255;
2651
+ for (let bitPos = 8 / W - 1; bitPos >= 0; bitPos--) {
2652
+ const bit = byte >>> W * bitPos & mask;
2653
+ const {
2654
+ s0: e0,
2655
+ s1: e1,
2656
+ s2: e2,
2657
+ s3: e3
2658
+ } = t[w * windowSize + bit];
2659
+ o0 ^= e0, o1 ^= e1, o2 ^= e2, o3 ^= e3;
2660
+ w += 1;
2661
+ }
2662
+ }
2663
+ }
2664
+ this.s0 = o0;
2665
+ this.s1 = o1;
2666
+ this.s2 = o2;
2667
+ this.s3 = o3;
2668
+ }
2669
+ update(data) {
2670
+ data = toBytes2(data);
2671
+ aexists(this);
2672
+ const b32 = u32(data);
2673
+ const blocks = Math.floor(data.length / BLOCK_SIZE);
2674
+ const left = data.length % BLOCK_SIZE;
2675
+ for (let i = 0; i < blocks; i++) {
2676
+ this._updateBlock(b32[i * 4 + 0], b32[i * 4 + 1], b32[i * 4 + 2], b32[i * 4 + 3]);
2677
+ }
2678
+ if (left) {
2679
+ ZEROS16.set(data.subarray(blocks * BLOCK_SIZE));
2680
+ this._updateBlock(ZEROS32[0], ZEROS32[1], ZEROS32[2], ZEROS32[3]);
2681
+ clean(ZEROS32);
2682
+ }
2683
+ return this;
2684
+ }
2685
+ destroy() {
2686
+ const {
2687
+ t
2688
+ } = this;
2689
+ for (const elm of t) {
2690
+ elm.s0 = 0, elm.s1 = 0, elm.s2 = 0, elm.s3 = 0;
2691
+ }
2692
+ }
2693
+ digestInto(out) {
2694
+ aexists(this);
2695
+ aoutput(out, this);
2696
+ this.finished = true;
2697
+ const {
2698
+ s0,
2699
+ s1,
2700
+ s2,
2701
+ s3
2702
+ } = this;
2703
+ const o32 = u32(out);
2704
+ o32[0] = s0;
2705
+ o32[1] = s1;
2706
+ o32[2] = s2;
2707
+ o32[3] = s3;
2708
+ return out;
2709
+ }
2710
+ digest() {
2711
+ const res = new Uint8Array(BLOCK_SIZE);
2712
+ this.digestInto(res);
2713
+ this.destroy();
2714
+ return res;
2715
+ }
2716
+ };
2717
+ var Polyval = class extends GHASH {
2718
+ constructor(key, expectedLength) {
2719
+ key = toBytes2(key);
2720
+ const ghKey = _toGHASHKey(copyBytes(key));
2721
+ super(ghKey, expectedLength);
2722
+ clean(ghKey);
2723
+ }
2724
+ update(data) {
2725
+ data = toBytes2(data);
2726
+ aexists(this);
2727
+ const b32 = u32(data);
2728
+ const left = data.length % BLOCK_SIZE;
2729
+ const blocks = Math.floor(data.length / BLOCK_SIZE);
2730
+ for (let i = 0; i < blocks; i++) {
2731
+ this._updateBlock(swapLE(b32[i * 4 + 3]), swapLE(b32[i * 4 + 2]), swapLE(b32[i * 4 + 1]), swapLE(b32[i * 4 + 0]));
2732
+ }
2733
+ if (left) {
2734
+ ZEROS16.set(data.subarray(blocks * BLOCK_SIZE));
2735
+ this._updateBlock(swapLE(ZEROS32[3]), swapLE(ZEROS32[2]), swapLE(ZEROS32[1]), swapLE(ZEROS32[0]));
2736
+ clean(ZEROS32);
2737
+ }
2738
+ return this;
2739
+ }
2740
+ digestInto(out) {
2741
+ aexists(this);
2742
+ aoutput(out, this);
2743
+ this.finished = true;
2744
+ const {
2745
+ s0,
2746
+ s1,
2747
+ s2,
2748
+ s3
2749
+ } = this;
2750
+ const o32 = u32(out);
2751
+ o32[0] = s0;
2752
+ o32[1] = s1;
2753
+ o32[2] = s2;
2754
+ o32[3] = s3;
2755
+ return out.reverse();
2756
+ }
2757
+ };
2758
+ function wrapConstructorWithKey(hashCons) {
2759
+ const hashC = (msg, key) => hashCons(key, msg.length).update(toBytes2(msg)).digest();
2760
+ const tmp2 = hashCons(new Uint8Array(16), 0);
2761
+ hashC.outputLen = tmp2.outputLen;
2762
+ hashC.blockLen = tmp2.blockLen;
2763
+ hashC.create = (key, expectedLength) => hashCons(key, expectedLength);
2764
+ return hashC;
2765
+ }
2766
+ var ghash = wrapConstructorWithKey((key, expectedLength) => new GHASH(key, expectedLength));
2767
+ var polyval = wrapConstructorWithKey((key, expectedLength) => new Polyval(key, expectedLength));
2768
+
2769
+ // src/sm4/index.ts
2770
+ var DECRYPT = 0;
2771
+ var ROUND = 32;
2772
+ var BLOCK = 16;
2773
+ var Sbox = Uint8Array.from([214, 144, 233, 254, 204, 225, 61, 183, 22, 182, 20, 194, 40, 251, 44, 5, 43, 103, 154, 118, 42, 190, 4, 195, 170, 68, 19, 38, 73, 134, 6, 153, 156, 66, 80, 244, 145, 239, 152, 122, 51, 84, 11, 67, 237, 207, 172, 98, 228, 179, 28, 169, 201, 8, 232, 149, 128, 223, 148, 250, 117, 143, 63, 166, 71, 7, 167, 252, 243, 115, 23, 186, 131, 89, 60, 25, 230, 133, 79, 168, 104, 107, 129, 178, 113, 100, 218, 139, 248, 235, 15, 75, 112, 86, 157, 53, 30, 36, 14, 94, 99, 88, 209, 162, 37, 34, 124, 59, 1, 33, 120, 135, 212, 0, 70, 87, 159, 211, 39, 82, 76, 54, 2, 231, 160, 196, 200, 158, 234, 191, 138, 210, 64, 199, 56, 181, 163, 247, 242, 206, 249, 97, 21, 161, 224, 174, 93, 164, 155, 52, 26, 85, 173, 147, 50, 48, 245, 140, 177, 227, 29, 246, 226, 46, 130, 102, 202, 96, 192, 41, 35, 171, 13, 83, 78, 111, 213, 219, 55, 69, 222, 253, 142, 47, 3, 255, 106, 114, 109, 108, 91, 81, 141, 27, 175, 146, 187, 221, 188, 127, 17, 217, 92, 65, 31, 16, 90, 216, 10, 193, 49, 136, 165, 205, 123, 189, 45, 116, 208, 18, 184, 229, 180, 176, 137, 105, 151, 74, 12, 150, 119, 126, 101, 185, 241, 9, 197, 110, 198, 132, 24, 240, 125, 236, 58, 220, 77, 32, 121, 238, 95, 62, 215, 203, 57, 72]);
2774
+ var CK = new Uint32Array([462357, 472066609, 943670861, 1415275113, 1886879365, 2358483617, 2830087869, 3301692121, 3773296373, 4228057617, 404694573, 876298825, 1347903077, 1819507329, 2291111581, 2762715833, 3234320085, 3705924337, 4177462797, 337322537, 808926789, 1280531041, 1752135293, 2223739545, 2695343797, 3166948049, 3638552301, 4110090761, 269950501, 741554753, 1213159005, 1684763257]);
2775
+ function byteSub(a) {
2776
+ return (Sbox[a >>> 24 & 255] & 255) << 24 | (Sbox[a >>> 16 & 255] & 255) << 16 | (Sbox[a >>> 8 & 255] & 255) << 8 | Sbox[a & 255] & 255;
2777
+ }
2778
+ var x = new Uint32Array(4);
2779
+ var tmp = new Uint32Array(4);
2780
+ function sms4Crypt(input, output, roundKey) {
2781
+ let x0 = 0,
2782
+ x1 = 0,
2783
+ x2 = 0,
2784
+ x3 = 0,
2785
+ tmp0 = 0,
2786
+ tmp1 = 0,
2787
+ tmp2 = 0,
2788
+ tmp3 = 0;
2789
+ tmp0 = input[0] & 255;
2790
+ tmp1 = input[1] & 255;
2791
+ tmp2 = input[2] & 255;
2792
+ tmp3 = input[3] & 255;
2793
+ x0 = tmp0 << 24 | tmp1 << 16 | tmp2 << 8 | tmp3;
2794
+ tmp0 = input[4] & 255;
2795
+ tmp1 = input[5] & 255;
2796
+ tmp2 = input[6] & 255;
2797
+ tmp3 = input[7] & 255;
2798
+ x1 = tmp0 << 24 | tmp1 << 16 | tmp2 << 8 | tmp3;
2799
+ tmp0 = input[8] & 255;
2800
+ tmp1 = input[9] & 255;
2801
+ tmp2 = input[10] & 255;
2802
+ tmp3 = input[11] & 255;
2803
+ x2 = tmp0 << 24 | tmp1 << 16 | tmp2 << 8 | tmp3;
2804
+ tmp0 = input[12] & 255;
2805
+ tmp1 = input[13] & 255;
2806
+ tmp2 = input[14] & 255;
2807
+ tmp3 = input[15] & 255;
2808
+ x3 = tmp0 << 24 | tmp1 << 16 | tmp2 << 8 | tmp3;
2809
+ for (let r = 0; r < 32; r += 4) {
2810
+ tmp0 = x1 ^ x2 ^ x3 ^ roundKey[r];
2811
+ tmp0 = byteSub(tmp0);
2812
+ x0 ^= tmp0 ^ (tmp0 << 2 | tmp0 >>> 30) ^ (tmp0 << 10 | tmp0 >>> 22) ^ (tmp0 << 18 | tmp0 >>> 14) ^ (tmp0 << 24 | tmp0 >>> 8);
2813
+ tmp1 = x2 ^ x3 ^ x0 ^ roundKey[r + 1];
2814
+ tmp1 = byteSub(tmp1);
2815
+ x1 ^= tmp1 ^ (tmp1 << 2 | tmp1 >>> 30) ^ (tmp1 << 10 | tmp1 >>> 22) ^ (tmp1 << 18 | tmp1 >>> 14) ^ (tmp1 << 24 | tmp1 >>> 8);
2816
+ tmp2 = x3 ^ x0 ^ x1 ^ roundKey[r + 2];
2817
+ tmp2 = byteSub(tmp2);
2818
+ x2 ^= tmp2 ^ (tmp2 << 2 | tmp2 >>> 30) ^ (tmp2 << 10 | tmp2 >>> 22) ^ (tmp2 << 18 | tmp2 >>> 14) ^ (tmp2 << 24 | tmp2 >>> 8);
2819
+ tmp3 = x0 ^ x1 ^ x2 ^ roundKey[r + 3];
2820
+ tmp3 = byteSub(tmp3);
2821
+ x3 ^= tmp3 ^ (tmp3 << 2 | tmp3 >>> 30) ^ (tmp3 << 10 | tmp3 >>> 22) ^ (tmp3 << 18 | tmp3 >>> 14) ^ (tmp3 << 24 | tmp3 >>> 8);
2822
+ }
2823
+ output[0] = x3 >>> 24 & 255;
2824
+ output[1] = x3 >>> 16 & 255;
2825
+ output[2] = x3 >>> 8 & 255;
2826
+ output[3] = x3 & 255;
2827
+ output[4] = x2 >>> 24 & 255;
2828
+ output[5] = x2 >>> 16 & 255;
2829
+ output[6] = x2 >>> 8 & 255;
2830
+ output[7] = x2 & 255;
2831
+ output[8] = x1 >>> 24 & 255;
2832
+ output[9] = x1 >>> 16 & 255;
2833
+ output[10] = x1 >>> 8 & 255;
2834
+ output[11] = x1 & 255;
2835
+ output[12] = x0 >>> 24 & 255;
2836
+ output[13] = x0 >>> 16 & 255;
2837
+ output[14] = x0 >>> 8 & 255;
2838
+ output[15] = x0 & 255;
2839
+ }
2840
+ function sms4KeyExt(key, roundKey, cryptFlag) {
2841
+ let x0 = 0,
2842
+ x1 = 0,
2843
+ x2 = 0,
2844
+ x3 = 0,
2845
+ mid = 0;
2846
+ x0 = (key[0] & 255) << 24 | (key[1] & 255) << 16 | (key[2] & 255) << 8 | key[3] & 255;
2847
+ x1 = (key[4] & 255) << 24 | (key[5] & 255) << 16 | (key[6] & 255) << 8 | key[7] & 255;
2848
+ x2 = (key[8] & 255) << 24 | (key[9] & 255) << 16 | (key[10] & 255) << 8 | key[11] & 255;
2849
+ x3 = (key[12] & 255) << 24 | (key[13] & 255) << 16 | (key[14] & 255) << 8 | key[15] & 255;
2850
+ x0 ^= 2746333894;
2851
+ x1 ^= 1453994832;
2852
+ x2 ^= 1736282519;
2853
+ x3 ^= 2993693404;
2854
+ for (let r = 0; r < 32; r += 4) {
2855
+ mid = x1 ^ x2 ^ x3 ^ CK[r + 0];
2856
+ mid = byteSub(mid);
2857
+ x0 ^= mid ^ (mid << 13 | mid >>> 19) ^ (mid << 23 | mid >>> 9);
2858
+ roundKey[r + 0] = x0;
2859
+ mid = x2 ^ x3 ^ x0 ^ CK[r + 1];
2860
+ mid = byteSub(mid);
2861
+ x1 ^= mid ^ (mid << 13 | mid >>> 19) ^ (mid << 23 | mid >>> 9);
2862
+ roundKey[r + 1] = x1;
2863
+ mid = x3 ^ x0 ^ x1 ^ CK[r + 2];
2864
+ mid = byteSub(mid);
2865
+ x2 ^= mid ^ (mid << 13 | mid >>> 19) ^ (mid << 23 | mid >>> 9);
2866
+ roundKey[r + 2] = x2;
2867
+ mid = x0 ^ x1 ^ x2 ^ CK[r + 3];
2868
+ mid = byteSub(mid);
2869
+ x3 ^= mid ^ (mid << 13 | mid >>> 19) ^ (mid << 23 | mid >>> 9);
2870
+ roundKey[r + 3] = x3;
2871
+ }
2872
+ if (cryptFlag === DECRYPT) {
2873
+ for (let r = 0; r < 16; r++) {
2874
+ [roundKey[r], roundKey[31 - r]] = [roundKey[31 - r], roundKey[r]];
2875
+ }
2876
+ }
2877
+ }
2878
+ function incrementCounter(counter) {
2879
+ for (let i = counter.length - 1; i >= 0; i--) {
2880
+ counter[i]++;
2881
+ if (counter[i] !== 0) break;
2882
+ }
2883
+ }
2884
+ function sm4Gcm(inArray, key, ivArray, aadArray, cryptFlag, tagArray) {
2885
+ const tagLength = 16;
2886
+ function deriveKeys() {
2887
+ const roundKey2 = new Uint32Array(ROUND);
2888
+ sms4KeyExt(key, roundKey2, 1);
2889
+ const authKey = new Uint8Array(16).fill(0);
2890
+ const h2 = new Uint8Array(16);
2891
+ sms4Crypt(authKey, h2, roundKey2);
2892
+ let j02;
2893
+ if (ivArray.length === 12) {
2894
+ j02 = new Uint8Array(16);
2895
+ j02.set(ivArray, 0);
2896
+ j02[15] = 1;
2897
+ } else {
2898
+ const g = ghash.create(h2);
2899
+ g.update(ivArray);
2900
+ const lenIv = new Uint8Array(16);
2901
+ const view = createView2(lenIv);
2902
+ setBigUint642(view, 8, BigInt(ivArray.length * 8), false);
2903
+ g.update(lenIv);
2904
+ j02 = g.digest();
2905
+ }
2906
+ const counter2 = new Uint8Array(j02);
2907
+ incrementCounter(counter2);
2908
+ const tagMask2 = new Uint8Array(16);
2909
+ sms4Crypt(j02, tagMask2, roundKey2);
2910
+ return {
2911
+ roundKey: roundKey2,
2912
+ h: h2,
2913
+ j0: j02,
2914
+ counter: counter2,
2915
+ tagMask: tagMask2
2916
+ };
2917
+ }
2918
+ function computeTag(h2, data) {
2919
+ const aadLength = aadArray.length;
2920
+ const dataLength = data.length;
2921
+ const g = ghash.create(h2);
2922
+ if (aadLength > 0) {
2923
+ g.update(aadArray);
2924
+ }
2925
+ g.update(data);
2926
+ const lenBlock = new Uint8Array(16);
2927
+ const view = createView2(lenBlock);
2928
+ setBigUint642(view, 0, BigInt(aadLength * 8), false);
2929
+ setBigUint642(view, 8, BigInt(dataLength * 8), false);
2930
+ g.update(lenBlock);
2931
+ return g.digest();
2932
+ }
2933
+ const {
2934
+ roundKey,
2935
+ h,
2936
+ j0,
2937
+ counter,
2938
+ tagMask
2939
+ } = deriveKeys();
2940
+ if (cryptFlag === DECRYPT && tagArray) {
2941
+ const calculatedTag = computeTag(h, inArray);
2942
+ for (let i = 0; i < 16; i++) {
2943
+ calculatedTag[i] ^= tagMask[i];
2944
+ }
2945
+ let tagMatch = 0;
2946
+ for (let i = 0; i < 16; i++) {
2947
+ tagMatch |= calculatedTag[i] ^ tagArray[i];
2948
+ }
2949
+ if (tagMatch !== 0) {
2950
+ throw new Error("authentication tag mismatch");
2951
+ }
2952
+ }
2953
+ const outArray = new Uint8Array(inArray.length);
2954
+ let point = 0;
2955
+ let restLen = inArray.length;
2956
+ while (restLen >= BLOCK) {
2957
+ const blockOut = new Uint8Array(BLOCK);
2958
+ sms4Crypt(counter, blockOut, roundKey);
2959
+ for (let i = 0; i < BLOCK && i < restLen; i++) {
2960
+ outArray[point + i] = inArray[point + i] ^ blockOut[i];
2961
+ }
2962
+ incrementCounter(counter);
2963
+ point += BLOCK;
2964
+ restLen -= BLOCK;
2965
+ }
2966
+ if (restLen > 0) {
2967
+ const blockOut = new Uint8Array(BLOCK);
2968
+ sms4Crypt(counter, blockOut, roundKey);
2969
+ for (let i = 0; i < restLen; i++) {
2970
+ outArray[point + i] = inArray[point + i] ^ blockOut[i];
2971
+ }
2972
+ }
2973
+ if (cryptFlag !== DECRYPT) {
2974
+ const calculatedTag = computeTag(h, outArray);
2975
+ for (let i = 0; i < 16; i++) {
2976
+ calculatedTag[i] ^= tagMask[i];
2977
+ }
2978
+ return {
2979
+ output: outArray,
2980
+ tag: calculatedTag
2981
+ };
2982
+ }
2983
+ return {
2984
+ output: outArray
2985
+ };
2986
+ }
2987
+ var blockOutput = new Uint8Array(16);
2988
+ function sm4(inArray, key, cryptFlag, options = {}) {
2989
+ let {
2990
+ padding = "pkcs#7",
2991
+ mode,
2992
+ iv = new Uint8Array(16),
2993
+ output,
2994
+ associatedData,
2995
+ outputTag,
2996
+ tag
2997
+ } = options;
2998
+ if (mode === "gcm") {
2999
+ const keyArray = typeof key === "string" ? hexToArray(key) : Uint8Array.from(key);
3000
+ const ivArray = typeof iv === "string" ? hexToArray(iv) : Uint8Array.from(iv);
3001
+ const aadArray = associatedData ? typeof associatedData === "string" ? hexToArray(associatedData) : Uint8Array.from(associatedData) : new Uint8Array(0);
3002
+ let inputArray;
3003
+ if (typeof inArray === "string") {
3004
+ if (cryptFlag !== DECRYPT) {
3005
+ inputArray = utf8ToArray(inArray);
3006
+ } else {
3007
+ inputArray = hexToArray(inArray);
3008
+ }
3009
+ } else {
3010
+ inputArray = Uint8Array.from(inArray);
3011
+ }
3012
+ const tagArray = tag ? typeof tag === "string" ? hexToArray(tag) : Uint8Array.from(tag) : void 0;
3013
+ const result = sm4Gcm(inputArray, keyArray, ivArray, aadArray, cryptFlag, tagArray);
3014
+ if (output === "array") {
3015
+ if (outputTag && cryptFlag !== DECRYPT) {
3016
+ return result;
3017
+ }
3018
+ return result.output;
3019
+ } else {
3020
+ if (outputTag && cryptFlag !== DECRYPT) {
3021
+ return {
3022
+ output: bytesToHex2(result.output),
3023
+ tag: result.tag ? bytesToHex2(result.tag) : void 0
3024
+ };
3025
+ }
3026
+ if (cryptFlag !== DECRYPT) {
3027
+ return {
3028
+ output: bytesToHex2(result.output),
3029
+ tag: result.tag ? bytesToHex2(result.tag) : void 0
3030
+ };
3031
+ } else {
3032
+ return arrayToUtf8(result.output);
3033
+ }
3034
+ }
3035
+ }
3036
+ if (mode === "cbc") {
3037
+ if (typeof iv === "string") iv = hexToArray(iv);
3038
+ if (iv.length !== 128 / 8) {
3039
+ throw new Error("iv is invalid");
3040
+ }
3041
+ }
3042
+ if (typeof key === "string") key = hexToArray(key);
3043
+ if (key.length !== 128 / 8) {
3044
+ throw new Error("key is invalid");
3045
+ }
3046
+ if (typeof inArray === "string") {
3047
+ if (cryptFlag !== DECRYPT) {
3048
+ inArray = utf8ToArray(inArray);
3049
+ } else {
3050
+ inArray = hexToArray(inArray);
3051
+ }
3052
+ } else {
3053
+ inArray = Uint8Array.from(inArray);
3054
+ }
3055
+ if ((padding === "pkcs#5" || padding === "pkcs#7") && cryptFlag !== DECRYPT) {
3056
+ const paddingCount = BLOCK - inArray.length % BLOCK;
3057
+ const newArray = new Uint8Array(inArray.length + paddingCount);
3058
+ newArray.set(inArray, 0);
3059
+ for (let i = 0; i < paddingCount; i++) newArray[inArray.length + i] = paddingCount;
3060
+ inArray = newArray;
3061
+ }
3062
+ const roundKey = new Uint32Array(ROUND);
3063
+ sms4KeyExt(key, roundKey, cryptFlag);
3064
+ let outArray = new Uint8Array(inArray.length);
3065
+ let lastVector = iv;
3066
+ let restLen = inArray.length;
3067
+ let point = 0;
3068
+ while (restLen >= BLOCK) {
3069
+ const input = inArray.subarray(point, point + 16);
3070
+ if (mode === "cbc") {
3071
+ for (let i = 0; i < BLOCK; i++) {
3072
+ if (cryptFlag !== DECRYPT) {
3073
+ input[i] ^= lastVector[i];
3074
+ }
3075
+ }
3076
+ }
3077
+ sms4Crypt(input, blockOutput, roundKey);
3078
+ for (let i = 0; i < BLOCK; i++) {
3079
+ if (mode === "cbc") {
3080
+ if (cryptFlag === DECRYPT) {
3081
+ blockOutput[i] ^= lastVector[i];
3082
+ }
3083
+ }
3084
+ outArray[point + i] = blockOutput[i];
3085
+ }
3086
+ if (mode === "cbc") {
3087
+ if (cryptFlag !== DECRYPT) {
3088
+ lastVector = blockOutput;
3089
+ } else {
3090
+ lastVector = input;
3091
+ }
3092
+ }
3093
+ restLen -= BLOCK;
3094
+ point += BLOCK;
3095
+ }
3096
+ if ((padding === "pkcs#5" || padding === "pkcs#7") && cryptFlag === DECRYPT) {
3097
+ const len = outArray.length;
3098
+ const paddingCount = outArray[len - 1];
3099
+ for (let i = 1; i <= paddingCount; i++) {
3100
+ if (outArray[len - i] !== paddingCount) throw new Error("padding is invalid");
3101
+ }
3102
+ outArray = outArray.slice(0, len - paddingCount);
3103
+ }
3104
+ if (output !== "array") {
3105
+ if (cryptFlag !== DECRYPT) {
3106
+ return bytesToHex2(outArray);
3107
+ } else {
3108
+ return arrayToUtf8(outArray);
3109
+ }
3110
+ } else {
3111
+ return outArray;
3112
+ }
3113
+ }
3114
+ function encrypt(inArray, key, options = {}) {
3115
+ return sm4(inArray, key, 1, options);
3116
+ }
3117
+ function decrypt(inArray, key, options = {}) {
3118
+ return sm4(inArray, key, 0, options);
3119
+ }
3120
+
3121
+ /*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */
3122
+ /*! Bundled license information:
3123
+
3124
+ @noble/curves/esm/abstract/utils.js:
3125
+ (*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
3126
+
3127
+ @noble/curves/esm/abstract/modular.js:
3128
+ (*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
3129
+
3130
+ @noble/curves/esm/abstract/curve.js:
3131
+ (*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
3132
+
3133
+ @noble/curves/esm/abstract/weierstrass.js:
3134
+ (*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
3135
+
3136
+ @noble/ciphers/esm/utils.js:
3137
+ (*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) *)
3138
+ */
3139
+ });