sm-crypto-v2 0.3.13 → 1.2.2

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.
package/dist/index.mjs CHANGED
@@ -16,21 +16,26 @@ __export(sm2_exports, {
16
16
  doEncrypt: () => doEncrypt,
17
17
  doSignature: () => doSignature,
18
18
  doVerifySignature: () => doVerifySignature,
19
- generateEcparam: () => generateEcparam,
20
19
  generateKeyPairHex: () => generateKeyPairHex,
21
- getGlobalCurve: () => getGlobalCurve,
22
20
  getHash: () => getHash,
23
21
  getPoint: () => getPoint,
24
22
  getPublicKeyFromPrivateKey: () => getPublicKeyFromPrivateKey,
25
23
  hexToArray: () => hexToArray,
26
- leftPad: () => leftPad,
24
+ leftPad: () => leftPad2,
27
25
  utf8ToHex: () => utf8ToHex,
28
26
  verifyPublicKey: () => verifyPublicKey
29
27
  });
30
- import { BigInteger as BigInteger4 } from "jsbn";
31
28
 
32
29
  // src/sm2/asn1.ts
33
- import { BigInteger } from "jsbn";
30
+ import * as utils from "@noble/curves/abstract/utils";
31
+
32
+ // src/sm2/bn.ts
33
+ var ZERO = BigInt(0);
34
+ var ONE = BigInt(1);
35
+ var TWO = BigInt(2);
36
+ var THREE = BigInt(3);
37
+
38
+ // src/sm2/asn1.ts
34
39
  function bigintToValue(bigint) {
35
40
  let h = bigint.toString(16);
36
41
  if (h[0] !== "-") {
@@ -39,7 +44,7 @@ function bigintToValue(bigint) {
39
44
  else if (!h.match(/^[0-7]/))
40
45
  h = "00" + h;
41
46
  } else {
42
- h = h.substr(1);
47
+ h = h.substring(1);
43
48
  let len = h.length;
44
49
  if (len % 2 === 1)
45
50
  len += 1;
@@ -48,8 +53,8 @@ function bigintToValue(bigint) {
48
53
  let maskString = "";
49
54
  for (let i = 0; i < len; i++)
50
55
  maskString += "f";
51
- let mask = new BigInteger(maskString, 16);
52
- let output = mask.xor(bigint).add(BigInteger.ONE);
56
+ let mask = utils.hexToNumber(maskString);
57
+ let output = (mask ^ bigint) + ONE;
53
58
  h = output.toString(16).replace(/^-/, "");
54
59
  }
55
60
  return h;
@@ -70,11 +75,11 @@ var ASN1Object = class {
70
75
  return this.tlv;
71
76
  }
72
77
  getLength() {
73
- const n3 = this.v.length / 2;
74
- let nHex = n3.toString(16);
78
+ const n = this.v.length / 2;
79
+ let nHex = n.toString(16);
75
80
  if (nHex.length % 2 === 1)
76
81
  nHex = "0" + nHex;
77
- if (n3 < 128) {
82
+ if (n < 128) {
78
83
  return nHex;
79
84
  } else {
80
85
  const head = 128 + nHex.length / 2;
@@ -117,8 +122,8 @@ function getL(str, start) {
117
122
  const l = str.substring(start + 2, start + 2 + len * 2);
118
123
  if (!l)
119
124
  return -1;
120
- const bigint = +l[0] < 8 ? new BigInteger(l, 16) : new BigInteger(l.substring(2), 16);
121
- return bigint.intValue();
125
+ const bigint = +l[0] < 8 ? utils.hexToNumber(l) : utils.hexToNumber(l.substring(2));
126
+ return +bigint.toString();
122
127
  }
123
128
  function getStartOfV(str, start) {
124
129
  const len = getLenOfL(str, start);
@@ -139,344 +144,23 @@ function decodeDer(input) {
139
144
  const vIndexS = getStartOfV(input, nextStart);
140
145
  const lS = getL(input, nextStart);
141
146
  const vS = input.substring(vIndexS, vIndexS + lS * 2);
142
- const r = new BigInteger(vR, 16);
143
- const s = new BigInteger(vS, 16);
147
+ const r = utils.hexToNumber(vR);
148
+ const s = utils.hexToNumber(vS);
144
149
  return { r, s };
145
150
  }
146
151
 
147
152
  // src/sm2/utils.ts
148
- import { BigInteger as BigInteger3, SecureRandom } from "jsbn";
153
+ import * as utils2 from "@noble/curves/abstract/utils";
149
154
 
150
155
  // src/sm2/ec.ts
151
- import { BigInteger as BigInteger2 } from "jsbn";
152
- var TWO = new BigInteger2("2");
153
- var THREE = new BigInteger2("3");
154
- var ECFieldElementFp = class {
155
- constructor(q, x) {
156
- this.q = q;
157
- this.x = x;
158
- }
159
- equals(other) {
160
- if (other === this)
161
- return true;
162
- return this.q.equals(other.q) && this.x.equals(other.x);
163
- }
164
- toBigInteger() {
165
- return this.x;
166
- }
167
- negate() {
168
- return new ECFieldElementFp(this.q, this.x.negate().mod(this.q));
169
- }
170
- add(b) {
171
- return new ECFieldElementFp(this.q, this.x.add(b.toBigInteger()).mod(this.q));
172
- }
173
- subtract(b) {
174
- return new ECFieldElementFp(this.q, this.x.subtract(b.toBigInteger()).mod(this.q));
175
- }
176
- multiply(b) {
177
- return new ECFieldElementFp(this.q, this.x.multiply(b.toBigInteger()).mod(this.q));
178
- }
179
- divide(b) {
180
- return new ECFieldElementFp(this.q, this.x.multiply(b.toBigInteger().modInverse(this.q)).mod(this.q));
181
- }
182
- square() {
183
- return new ECFieldElementFp(this.q, this.x.square().mod(this.q));
184
- }
185
- };
186
- var ECPointFp = class {
187
- constructor(curve3, x, y, z) {
188
- this.curve = curve3;
189
- this.x = x;
190
- this.y = y;
191
- this.z = z == null ? BigInteger2.ONE : z;
192
- this.zinv = null;
193
- }
194
- zinv;
195
- z;
196
- getX() {
197
- if (this.zinv === null)
198
- this.zinv = this.z.modInverse(this.curve.q);
199
- return this.curve.fromBigInteger(this.x.toBigInteger().multiply(this.zinv).mod(this.curve.q));
200
- }
201
- getY() {
202
- if (this.zinv === null)
203
- this.zinv = this.z.modInverse(this.curve.q);
204
- return this.curve.fromBigInteger(this.y.toBigInteger().multiply(this.zinv).mod(this.curve.q));
205
- }
206
- equals(other) {
207
- if (other === this)
208
- return true;
209
- if (this.isInfinity())
210
- return other.isInfinity();
211
- if (other.isInfinity())
212
- return this.isInfinity();
213
- const u = other.y.toBigInteger().multiply(this.z).subtract(this.y.toBigInteger().multiply(other.z)).mod(this.curve.q);
214
- if (!u.equals(BigInteger2.ZERO))
215
- return false;
216
- const v = other.x.toBigInteger().multiply(this.z).subtract(this.x.toBigInteger().multiply(other.z)).mod(this.curve.q);
217
- return v.equals(BigInteger2.ZERO);
218
- }
219
- isInfinity() {
220
- if (this.x === null && this.y === null)
221
- return true;
222
- return this.z.equals(BigInteger2.ZERO) && !this.y.toBigInteger().equals(BigInteger2.ZERO);
223
- }
224
- negate() {
225
- return new ECPointFp(this.curve, this.x, this.y.negate(), this.z);
226
- }
227
- add(b) {
228
- if (this.isInfinity())
229
- return b;
230
- if (b.isInfinity())
231
- return this;
232
- const x1 = this.x.toBigInteger();
233
- const y1 = this.y.toBigInteger();
234
- const z1 = this.z;
235
- const x2 = b.x.toBigInteger();
236
- const y2 = b.y.toBigInteger();
237
- const z2 = b.z;
238
- const q = this.curve.q;
239
- const w1 = x1.multiply(z2).mod(q);
240
- const w2 = x2.multiply(z1).mod(q);
241
- const w3 = w1.subtract(w2);
242
- const w4 = y1.multiply(z2).mod(q);
243
- const w5 = y2.multiply(z1).mod(q);
244
- const w6 = w4.subtract(w5);
245
- if (BigInteger2.ZERO.equals(w3)) {
246
- if (BigInteger2.ZERO.equals(w6)) {
247
- return this.twice();
248
- }
249
- return this.curve.infinity;
250
- }
251
- const w7 = w1.add(w2);
252
- const w8 = z1.multiply(z2).mod(q);
253
- const w9 = w3.square().mod(q);
254
- const w10 = w3.multiply(w9).mod(q);
255
- const w11 = w8.multiply(w6.square()).subtract(w7.multiply(w9)).mod(q);
256
- const x3 = w3.multiply(w11).mod(q);
257
- const y3 = w6.multiply(w9.multiply(w1).subtract(w11)).subtract(w4.multiply(w10)).mod(q);
258
- const z3 = w10.multiply(w8).mod(q);
259
- return new ECPointFp(this.curve, this.curve.fromBigInteger(x3), this.curve.fromBigInteger(y3), z3);
260
- }
261
- twice() {
262
- if (this.isInfinity())
263
- return this;
264
- if (!this.y.toBigInteger().signum())
265
- return this.curve.infinity;
266
- const x1 = this.x.toBigInteger();
267
- const y1 = this.y.toBigInteger();
268
- const z1 = this.z;
269
- const q = this.curve.q;
270
- const a = this.curve.a.toBigInteger();
271
- const w1 = x1.square().multiply(THREE).add(a.multiply(z1.square())).mod(q);
272
- const w2 = y1.shiftLeft(1).multiply(z1).mod(q);
273
- const w3 = y1.square().mod(q);
274
- const w4 = w3.multiply(x1).multiply(z1).mod(q);
275
- const w5 = w2.square().mod(q);
276
- const w6 = w1.square().subtract(w4.shiftLeft(3)).mod(q);
277
- const x3 = w2.multiply(w6).mod(q);
278
- const y3 = w1.multiply(w4.shiftLeft(2).subtract(w6)).subtract(w5.shiftLeft(1).multiply(w3)).mod(q);
279
- const z3 = w2.multiply(w5).mod(q);
280
- return new ECPointFp(this.curve, this.curve.fromBigInteger(x3), this.curve.fromBigInteger(y3), z3);
281
- }
282
- multiply(k) {
283
- if (this.isInfinity())
284
- return this;
285
- if (!k.signum())
286
- return this.curve.infinity;
287
- const k3 = k.multiply(THREE);
288
- const neg = this.negate();
289
- let Q = this;
290
- for (let i = k3.bitLength() - 2; i > 0; i--) {
291
- Q = Q.twice();
292
- const k3Bit = k3.testBit(i);
293
- const kBit = k.testBit(i);
294
- if (k3Bit !== kBit) {
295
- Q = Q.add(k3Bit ? this : neg);
296
- }
297
- }
298
- return Q;
299
- }
300
- };
301
- var ECCurveFp = class {
302
- constructor(q, a, b) {
303
- this.q = q;
304
- this.q = q;
305
- this.a = this.fromBigInteger(a);
306
- this.b = this.fromBigInteger(b);
307
- this.infinity = new ECPointFp(this, null, null);
308
- }
309
- infinity;
310
- a;
311
- b;
312
- equals(other) {
313
- if (other === this)
314
- return true;
315
- return this.q.equals(other.q) && this.a.equals(other.a) && this.b.equals(other.b);
316
- }
317
- fromBigInteger(x) {
318
- return new ECFieldElementFp(this.q, x);
319
- }
320
- decodePointHex(s) {
321
- switch (parseInt(s.substring(0, 2), 16)) {
322
- case 0:
323
- return this.infinity;
324
- case 2:
325
- case 3:
326
- const x = this.fromBigInteger(new BigInteger2(s.substring(2), 16));
327
- let y = this.fromBigInteger(x.multiply(x.square()).add(
328
- x.multiply(this.a)
329
- ).add(this.b).toBigInteger().modPow(
330
- this.q.divide(new BigInteger2("4")).add(BigInteger2.ONE),
331
- this.q
332
- ));
333
- if (!y.toBigInteger().mod(TWO).equals(new BigInteger2(s.substring(0, 2), 16).subtract(TWO))) {
334
- y = y.negate();
335
- }
336
- return new ECPointFp(this, x, y);
337
- case 4:
338
- case 6:
339
- case 7:
340
- const len = (s.length - 2) / 2;
341
- const xHex = s.substring(2, 2 + len);
342
- const yHex = s.substring(len + 2, len + 2 + len);
343
- return new ECPointFp(this, this.fromBigInteger(new BigInteger2(xHex, 16)), this.fromBigInteger(new BigInteger2(yHex, 16)));
344
- default:
345
- return null;
346
- }
347
- }
348
- };
349
-
350
- // src/sm2/utils.ts
351
- var rng = new SecureRandom();
352
- var { curve, G, n } = generateEcparam();
353
- function getGlobalCurve() {
354
- return curve;
355
- }
356
- function generateEcparam() {
357
- const p = new BigInteger3("FFFFFFFEFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00000000FFFFFFFFFFFFFFFF", 16);
358
- const a = new BigInteger3("FFFFFFFEFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00000000FFFFFFFFFFFFFFFC", 16);
359
- const b = new BigInteger3("28E9FA9E9D9F5E344D5A9E4BCF6509A7F39789F515AB8F92DDBCBD414D940E93", 16);
360
- const curve3 = new ECCurveFp(p, a, b);
361
- const gxHex = "32C4AE2C1F1981195F9904466A39C9948FE30BBFF2660BE1715A4589334C74C7";
362
- const gyHex = "BC3736A2F4F6779C59BDCEE36B692153D0A9877CC62A474002DF32E52139F0A0";
363
- const G3 = curve3.decodePointHex("04" + gxHex + gyHex);
364
- const n3 = new BigInteger3("FFFFFFFEFFFFFFFFFFFFFFFFFFFFFFFF7203DF6B21C6052B53BBF40939D54123", 16);
365
- return { curve: curve3, G: G3, n: n3 };
366
- }
367
- function generateKeyPairHex(a, b, c) {
368
- const random = typeof a === "string" ? new BigInteger3(a, b) : a ? new BigInteger3(a, b, c) : new BigInteger3(n.bitLength(), rng);
369
- const d = random.mod(n.subtract(BigInteger3.ONE)).add(BigInteger3.ONE);
370
- const privateKey = leftPad(d.toString(16), 64);
371
- const P = G.multiply(d);
372
- const Px = leftPad(P.getX().toBigInteger().toString(16), 64);
373
- const Py = leftPad(P.getY().toBigInteger().toString(16), 64);
374
- const publicKey = "04" + Px + Py;
375
- return { privateKey, publicKey };
376
- }
377
- function compressPublicKeyHex(s) {
378
- if (s.length !== 130)
379
- throw new Error("Invalid public key to compress");
380
- const len = (s.length - 2) / 2;
381
- const xHex = s.substring(2, 2 + len);
382
- const y = new BigInteger3(s.substring(len + 2, len + len + 2), 16);
383
- let prefix = "03";
384
- if (y.mod(new BigInteger3("2")).equals(BigInteger3.ZERO))
385
- prefix = "02";
386
- return prefix + xHex;
387
- }
388
- function utf8ToHex(input) {
389
- input = decodeURIComponent(encodeURIComponent(input));
390
- const length = input.length;
391
- const words = new Uint32Array((length >>> 2) + 1);
392
- for (let i = 0; i < length; i++) {
393
- words[i >>> 2] |= (input.charCodeAt(i) & 255) << 24 - i % 4 * 8;
394
- }
395
- const hexChars = [];
396
- for (let i = 0; i < length; i++) {
397
- const bite = words[i >>> 2] >>> 24 - i % 4 * 8 & 255;
398
- hexChars.push((bite >>> 4).toString(16));
399
- hexChars.push((bite & 15).toString(16));
400
- }
401
- return hexChars.join("");
402
- }
403
- function leftPad(input, num) {
404
- if (input.length >= num)
405
- return input;
406
- return new Array(num - input.length + 1).join("0") + input;
407
- }
408
- function arrayToHex(arr) {
409
- return arr.map((item) => {
410
- const hex = item.toString(16);
411
- return hex.length === 1 ? "0" + hex : hex;
412
- }).join("");
413
- }
414
- function arrayToUtf8(arr) {
415
- const str = [];
416
- for (let i = 0, len = arr.length; i < len; i++) {
417
- if (arr[i] >= 240 && arr[i] <= 247) {
418
- str.push(String.fromCodePoint(((arr[i] & 7) << 18) + ((arr[i + 1] & 63) << 12) + ((arr[i + 2] & 63) << 6) + (arr[i + 3] & 63)));
419
- i += 3;
420
- } else if (arr[i] >= 224 && arr[i] <= 239) {
421
- str.push(String.fromCodePoint(((arr[i] & 15) << 12) + ((arr[i + 1] & 63) << 6) + (arr[i + 2] & 63)));
422
- i += 2;
423
- } else if (arr[i] >= 192 && arr[i] <= 223) {
424
- str.push(String.fromCodePoint(((arr[i] & 31) << 6) + (arr[i + 1] & 63)));
425
- i++;
426
- } else {
427
- str.push(String.fromCodePoint(arr[i]));
428
- }
429
- }
430
- return str.join("");
431
- }
432
- function hexToArray(hexStr) {
433
- let hexStrLength = hexStr.length;
434
- if (hexStrLength % 2 !== 0) {
435
- hexStr = leftPad(hexStr, hexStrLength + 1);
436
- }
437
- hexStrLength = hexStr.length;
438
- const wordLength = hexStrLength / 2;
439
- const words = new Uint8Array(wordLength);
440
- for (let i = 0; i < wordLength; i++) {
441
- words[i] = parseInt(hexStr.substring(i * 2, i * 2 + 2), 16);
442
- }
443
- return words;
444
- }
445
- function verifyPublicKey(publicKey) {
446
- const point = curve.decodePointHex(publicKey);
447
- if (!point)
448
- return false;
449
- const x = point.getX();
450
- const y = point.getY();
451
- return y.square().equals(x.multiply(x.square()).add(x.multiply(curve.a)).add(curve.b));
452
- }
453
- function comparePublicKeyHex(publicKey1, publicKey2) {
454
- const point1 = curve.decodePointHex(publicKey1);
455
- if (!point1)
456
- return false;
457
- const point2 = curve.decodePointHex(publicKey2);
458
- if (!point2)
459
- return false;
460
- return point1.equals(point2);
461
- }
462
- function concatArray(...arrays) {
463
- let totalLength = arrays.reduce((acc, value) => acc + value.length, 0);
464
- if (!arrays.length)
465
- return new Uint8Array();
466
- let result = new Uint8Array(totalLength);
467
- let length = 0;
468
- for (let array of arrays) {
469
- result.set(array, length);
470
- length += array.length;
471
- }
472
- return result;
473
- }
156
+ import { weierstrass } from "@noble/curves/abstract/weierstrass";
157
+ import { Field } from "@noble/curves/abstract/modular";
474
158
 
475
159
  // src/sm2/sm3.ts
476
160
  var W = new Uint32Array(68);
477
161
  var M = new Uint32Array(64);
478
- function rotl(x, n3) {
479
- const s = n3 & 31;
162
+ function rotl(x, n) {
163
+ const s = n & 31;
480
164
  return x << s | x >>> 32 - s;
481
165
  }
482
166
  function xor(x, y) {
@@ -514,9 +198,9 @@ function sm3(array) {
514
198
  }
515
199
  const m = Uint8Array.from([...array, 128, ...kArr, ...lenArr]);
516
200
  const dataView = new DataView(m.buffer, 0);
517
- const n3 = m.length / 64;
201
+ const n = m.length / 64;
518
202
  const V = new Uint32Array([1937774191, 1226093241, 388252375, 3666478592, 2842636476, 372324522, 3817729613, 2969243214]);
519
- for (let i = 0; i < n3; i++) {
203
+ for (let i = 0; i < n; i++) {
520
204
  W.fill(0);
521
205
  M.fill(0);
522
206
  const start = 16 * i;
@@ -537,7 +221,7 @@ function sm3(array) {
537
221
  let D = V[3];
538
222
  let E = V[4];
539
223
  let F = V[5];
540
- let G3 = V[6];
224
+ let G = V[6];
541
225
  let H = V[7];
542
226
  let SS1;
543
227
  let SS2;
@@ -549,13 +233,13 @@ function sm3(array) {
549
233
  SS1 = rotl(rotl(A, 12) + E + rotl(T, j), 7);
550
234
  SS2 = SS1 ^ rotl(A, 12);
551
235
  TT1 = (j >= 0 && j <= 15 ? A ^ B ^ C : A & B | A & C | B & C) + D + SS2 + M[j];
552
- TT2 = (j >= 0 && j <= 15 ? E ^ F ^ G3 : E & F | ~E & G3) + H + SS1 + W[j];
236
+ TT2 = (j >= 0 && j <= 15 ? E ^ F ^ G : E & F | ~E & G) + H + SS1 + W[j];
553
237
  D = C;
554
238
  C = rotl(B, 9);
555
239
  B = A;
556
240
  A = TT1;
557
- H = G3;
558
- G3 = rotl(F, 19);
241
+ H = G;
242
+ G = rotl(F, 19);
559
243
  F = E;
560
244
  E = P0(TT2);
561
245
  }
@@ -565,7 +249,7 @@ function sm3(array) {
565
249
  V[3] ^= D;
566
250
  V[4] ^= E;
567
251
  V[5] ^= F;
568
- V[6] ^= G3;
252
+ V[6] ^= G;
569
253
  V[7] ^= H;
570
254
  }
571
255
  const result = new Uint8Array(V.length * 4);
@@ -599,20 +283,247 @@ function hmac(input, key) {
599
283
  return sm3(concatArray(oPadKey, hash));
600
284
  }
601
285
 
286
+ // src/sm3/index.ts
287
+ var sm3_exports = {};
288
+ __export(sm3_exports, {
289
+ sm3: () => sm32,
290
+ utf8ToArray: () => utf8ToArray
291
+ });
292
+ function utf8ToArray(str) {
293
+ const arr = [];
294
+ for (let i = 0, len = str.length; i < len; i++) {
295
+ const point = str.codePointAt(i);
296
+ if (point <= 127) {
297
+ arr.push(point);
298
+ } else if (point <= 2047) {
299
+ arr.push(192 | point >>> 6);
300
+ arr.push(128 | point & 63);
301
+ } else if (point <= 55295 || point >= 57344 && point <= 65535) {
302
+ arr.push(224 | point >>> 12);
303
+ arr.push(128 | point >>> 6 & 63);
304
+ arr.push(128 | point & 63);
305
+ } else if (point >= 65536 && point <= 1114111) {
306
+ i++;
307
+ arr.push(240 | point >>> 18 & 28);
308
+ arr.push(128 | point >>> 12 & 63);
309
+ arr.push(128 | point >>> 6 & 63);
310
+ arr.push(128 | point & 63);
311
+ } else {
312
+ arr.push(point);
313
+ throw new Error("input is not supported");
314
+ }
315
+ }
316
+ return new Uint8Array(arr);
317
+ }
318
+ function sm32(input, options) {
319
+ input = typeof input === "string" ? utf8ToArray(input) : input;
320
+ if (options) {
321
+ const mode = options.mode || "hmac";
322
+ if (mode !== "hmac")
323
+ throw new Error("invalid mode");
324
+ let key = options.key;
325
+ if (!key)
326
+ throw new Error("invalid key");
327
+ key = typeof key === "string" ? hexToArray(key) : key;
328
+ return arrayToHex(Array.from(hmac(input, key)));
329
+ }
330
+ return arrayToHex(Array.from(sm3(input)));
331
+ }
332
+
333
+ // src/sm2/ec.ts
334
+ var DEFAULT_PRNG_POOL_SIZE = 4096;
335
+ var prngPool = new Uint8Array(0);
336
+ async function FillPRNGPoolIfNeeded() {
337
+ if ("crypto" in globalThis)
338
+ return;
339
+ if (prngPool.length > DEFAULT_PRNG_POOL_SIZE / 2)
340
+ return;
341
+ if ("wx" in globalThis) {
342
+ prngPool = await new Promise((r) => {
343
+ wx.getRandomValues({
344
+ length: DEFAULT_PRNG_POOL_SIZE,
345
+ success(res) {
346
+ r(new Uint8Array(res.randomValues));
347
+ }
348
+ });
349
+ });
350
+ } else {
351
+ try {
352
+ const crypto = await import(
353
+ /* webpackIgnore: true */
354
+ "crypto"
355
+ );
356
+ const array = new Uint8Array(DEFAULT_PRNG_POOL_SIZE);
357
+ crypto.webcrypto.getRandomValues(array);
358
+ prngPool = array;
359
+ } catch (error) {
360
+ throw new Error("no available csprng, abort.");
361
+ }
362
+ }
363
+ }
364
+ FillPRNGPoolIfNeeded();
365
+ function consumePool(length) {
366
+ if (prngPool.length > length) {
367
+ const prng = prngPool.slice(0, length);
368
+ prngPool = prngPool.slice(length);
369
+ FillPRNGPoolIfNeeded();
370
+ return prng;
371
+ } else {
372
+ throw new Error("random number pool is insufficient, prevent getting too long random values or too often.");
373
+ }
374
+ }
375
+ function randomBytes(length = 0) {
376
+ const array = new Uint8Array(length);
377
+ if ("crypto" in globalThis) {
378
+ return globalThis.crypto.getRandomValues(array);
379
+ } else {
380
+ const result = consumePool(length);
381
+ return result;
382
+ }
383
+ }
384
+ function createHash() {
385
+ const hashC = (msg) => sm3(typeof msg === "string" ? utf8ToArray(msg) : msg);
386
+ hashC.outputLen = 256;
387
+ hashC.blockLen = 512;
388
+ hashC.create = () => sm3(Uint8Array.from([]));
389
+ return hashC;
390
+ }
391
+ var sm2Fp = Field(BigInt("115792089210356248756420345214020892766250353991924191454421193933289684991999"));
392
+ var sm2Curve = weierstrass({
393
+ a: BigInt("115792089210356248756420345214020892766250353991924191454421193933289684991996"),
394
+ b: BigInt("18505919022281880113072981827955639221458448578012075254857346196103069175443"),
395
+ Fp: sm2Fp,
396
+ h: ONE,
397
+ n: BigInt("115792089210356248756420345214020892766061623724957744567843809356293439045923"),
398
+ Gx: BigInt("22963146547237050559479531362550074578802567295341616970375194840604139615431"),
399
+ Gy: BigInt("85132369209828568825618990617112496413088388631904505083283536607588877201568"),
400
+ hash: createHash(),
401
+ hmac: (key, ...msgs) => hmac(concatArray(...msgs), key),
402
+ randomBytes
403
+ });
404
+
405
+ // src/sm2/utils.ts
406
+ import { mod } from "@noble/curves/abstract/modular";
407
+ function generateKeyPairHex(str) {
408
+ const privateKey = str ? utils2.numberToBytesBE(mod(BigInt(str), ONE) + ONE, 32) : sm2Curve.utils.randomPrivateKey();
409
+ const publicKey = sm2Curve.getPublicKey(privateKey, false);
410
+ const privPad = leftPad2(utils2.bytesToHex(privateKey), 64);
411
+ const pubPad = leftPad2(utils2.bytesToHex(publicKey), 64);
412
+ return { privateKey: privPad, publicKey: pubPad };
413
+ }
414
+ function compressPublicKeyHex(s) {
415
+ if (s.length !== 130)
416
+ throw new Error("Invalid public key to compress");
417
+ const len = (s.length - 2) / 2;
418
+ const xHex = s.substring(2, 2 + len);
419
+ const y = utils2.hexToNumber(s.substring(len + 2, len + len + 2));
420
+ let prefix = "03";
421
+ if (mod(y, TWO) === ZERO)
422
+ prefix = "02";
423
+ return prefix + xHex;
424
+ }
425
+ function utf8ToHex(input) {
426
+ input = decodeURIComponent(encodeURIComponent(input));
427
+ const length = input.length;
428
+ const words = new Uint32Array((length >>> 2) + 1);
429
+ for (let i = 0; i < length; i++) {
430
+ words[i >>> 2] |= (input.charCodeAt(i) & 255) << 24 - i % 4 * 8;
431
+ }
432
+ const hexChars = [];
433
+ for (let i = 0; i < length; i++) {
434
+ const bite = words[i >>> 2] >>> 24 - i % 4 * 8 & 255;
435
+ hexChars.push((bite >>> 4).toString(16));
436
+ hexChars.push((bite & 15).toString(16));
437
+ }
438
+ return hexChars.join("");
439
+ }
440
+ function leftPad2(input, num) {
441
+ if (input.length >= num)
442
+ return input;
443
+ return new Array(num - input.length + 1).join("0") + input;
444
+ }
445
+ function arrayToHex(arr) {
446
+ return arr.map((item) => {
447
+ const hex = item.toString(16);
448
+ return hex.length === 1 ? "0" + hex : hex;
449
+ }).join("");
450
+ }
451
+ function arrayToUtf8(arr) {
452
+ const str = [];
453
+ for (let i = 0, len = arr.length; i < len; i++) {
454
+ if (arr[i] >= 240 && arr[i] <= 247) {
455
+ str.push(String.fromCodePoint(((arr[i] & 7) << 18) + ((arr[i + 1] & 63) << 12) + ((arr[i + 2] & 63) << 6) + (arr[i + 3] & 63)));
456
+ i += 3;
457
+ } else if (arr[i] >= 224 && arr[i] <= 239) {
458
+ str.push(String.fromCodePoint(((arr[i] & 15) << 12) + ((arr[i + 1] & 63) << 6) + (arr[i + 2] & 63)));
459
+ i += 2;
460
+ } else if (arr[i] >= 192 && arr[i] <= 223) {
461
+ str.push(String.fromCodePoint(((arr[i] & 31) << 6) + (arr[i + 1] & 63)));
462
+ i++;
463
+ } else {
464
+ str.push(String.fromCodePoint(arr[i]));
465
+ }
466
+ }
467
+ return str.join("");
468
+ }
469
+ function hexToArray(hexStr) {
470
+ let hexStrLength = hexStr.length;
471
+ if (hexStrLength % 2 !== 0) {
472
+ hexStr = leftPad2(hexStr, hexStrLength + 1);
473
+ }
474
+ hexStrLength = hexStr.length;
475
+ const wordLength = hexStrLength / 2;
476
+ const words = new Uint8Array(wordLength);
477
+ for (let i = 0; i < wordLength; i++) {
478
+ words[i] = parseInt(hexStr.substring(i * 2, i * 2 + 2), 16);
479
+ }
480
+ return words;
481
+ }
482
+ function verifyPublicKey(publicKey) {
483
+ const point = sm2Curve.ProjectivePoint.fromHex(publicKey);
484
+ if (!point)
485
+ return false;
486
+ const x = point.x;
487
+ const y = point.y;
488
+ return sm2Fp.sqr(y) === sm2Fp.add(sm2Fp.add(sm2Fp.mul(x, sm2Fp.sqr(x)), sm2Fp.mul(x, sm2Curve.CURVE.a)), sm2Curve.CURVE.b);
489
+ }
490
+ function comparePublicKeyHex(publicKey1, publicKey2) {
491
+ const point1 = sm2Curve.ProjectivePoint.fromHex(publicKey1);
492
+ if (!point1)
493
+ return false;
494
+ const point2 = sm2Curve.ProjectivePoint.fromHex(publicKey2);
495
+ if (!point2)
496
+ return false;
497
+ return point1.equals(point2);
498
+ }
499
+ function concatArray(...arrays) {
500
+ let totalLength = arrays.reduce((acc, value) => acc + value.length, 0);
501
+ if (!arrays.length)
502
+ return new Uint8Array();
503
+ let result = new Uint8Array(totalLength);
504
+ let length = 0;
505
+ for (let array of arrays) {
506
+ result.set(array, length);
507
+ length += array.length;
508
+ }
509
+ return result;
510
+ }
511
+
602
512
  // src/sm2/index.ts
603
- var { G: G2, curve: curve2, n: n2 } = generateEcparam();
513
+ import * as mod2 from "@noble/curves/abstract/modular";
514
+ import * as utils3 from "@noble/curves/abstract/utils";
604
515
  var C1C2C3 = 0;
605
516
  function doEncrypt(msg, publicKey, cipherMode = 1) {
606
517
  const msgArr = typeof msg === "string" ? hexToArray(utf8ToHex(msg)) : Uint8Array.from(msg);
607
- const publicKeyPoint = getGlobalCurve().decodePointHex(publicKey);
518
+ const publicKeyPoint = sm2Curve.ProjectivePoint.fromHex(publicKey);
608
519
  const keypair = generateKeyPairHex();
609
- const k = new BigInteger4(keypair.privateKey, 16);
520
+ const k = utils3.hexToNumber(keypair.privateKey);
610
521
  let c1 = keypair.publicKey;
611
522
  if (c1.length > 128)
612
523
  c1 = c1.substring(c1.length - 128);
613
524
  const p = publicKeyPoint.multiply(k);
614
- const x2 = hexToArray(leftPad(p.getX().toBigInteger().toRadix(16), 64));
615
- const y2 = hexToArray(leftPad(p.getY().toBigInteger().toRadix(16), 64));
525
+ const x2 = hexToArray(leftPad2(utils3.numberToHexUnpadded(p.x), 64));
526
+ const y2 = hexToArray(leftPad2(utils3.numberToHexUnpadded(p.y), 64));
616
527
  const c3 = arrayToHex(Array.from(sm3(concatArray(x2, msgArr, y2))));
617
528
  let ct = 1;
618
529
  let offset = 0;
@@ -635,7 +546,7 @@ function doEncrypt(msg, publicKey, cipherMode = 1) {
635
546
  function doDecrypt(encryptData, privateKey, cipherMode = 1, {
636
547
  output = "string"
637
548
  } = {}) {
638
- const privateKeyInteger = new BigInteger4(privateKey, 16);
549
+ const privateKeyInteger = utils3.hexToNumber(privateKey);
639
550
  let c3 = encryptData.substring(128, 128 + 64);
640
551
  let c2 = encryptData.substring(128 + 64);
641
552
  if (cipherMode === C1C2C3) {
@@ -643,10 +554,10 @@ function doDecrypt(encryptData, privateKey, cipherMode = 1, {
643
554
  c2 = encryptData.substring(128, encryptData.length - 64);
644
555
  }
645
556
  const msg = hexToArray(c2);
646
- const c1 = getGlobalCurve().decodePointHex("04" + encryptData.substring(0, 128));
557
+ const c1 = sm2Curve.ProjectivePoint.fromHex("04" + encryptData.substring(0, 128));
647
558
  const p = c1.multiply(privateKeyInteger);
648
- const x2 = hexToArray(leftPad(p.getX().toBigInteger().toRadix(16), 64));
649
- const y2 = hexToArray(leftPad(p.getY().toBigInteger().toRadix(16), 64));
559
+ const x2 = hexToArray(leftPad2(utils3.numberToHexUnpadded(p.x), 64));
560
+ const y2 = hexToArray(leftPad2(utils3.numberToHexUnpadded(p.y), 64));
650
561
  let ct = 1;
651
562
  let offset = 0;
652
563
  let t = new Uint8Array();
@@ -682,8 +593,8 @@ function doSignature(msg, privateKey, options = {}) {
682
593
  publicKey = publicKey || getPublicKeyFromPrivateKey(privateKey);
683
594
  hashHex = getHash(hashHex, publicKey, userId);
684
595
  }
685
- const dA = new BigInteger4(privateKey, 16);
686
- const e = new BigInteger4(hashHex, 16);
596
+ const dA = utils3.hexToNumber(privateKey);
597
+ const e = utils3.hexToNumber(hashHex);
687
598
  let k = null;
688
599
  let r = null;
689
600
  let s = null;
@@ -696,13 +607,13 @@ function doSignature(msg, privateKey, options = {}) {
696
607
  point = getPoint();
697
608
  }
698
609
  k = point.k;
699
- r = e.add(point.x1).mod(n2);
700
- } while (r.equals(BigInteger4.ZERO) || r.add(k).equals(n2));
701
- s = dA.add(BigInteger4.ONE).modInverse(n2).multiply(k.subtract(r.multiply(dA))).mod(n2);
702
- } while (s.equals(BigInteger4.ZERO));
610
+ r = mod2.mod(e + point.x1, sm2Curve.CURVE.n);
611
+ } while (r === ZERO || r + k === sm2Curve.CURVE.n);
612
+ s = mod2.mod(mod2.invert(dA + ONE, sm2Curve.CURVE.n) * (k - r * dA), sm2Curve.CURVE.n);
613
+ } while (s === ZERO);
703
614
  if (der)
704
615
  return encodeDer(r, s);
705
- return leftPad(r.toString(16), 64) + leftPad(s.toString(16), 64);
616
+ return leftPad2(utils3.numberToHexUnpadded(r), 64) + leftPad2(utils3.numberToHexUnpadded(s), 64);
706
617
  }
707
618
  function doVerifySignature(msg, signHex, publicKey, options = {}) {
708
619
  let hashHex;
@@ -723,33 +634,33 @@ function doVerifySignature(msg, signHex, publicKey, options = {}) {
723
634
  r = decodeDerObj.r;
724
635
  s = decodeDerObj.s;
725
636
  } else {
726
- r = new BigInteger4(signHex.substring(0, 64), 16);
727
- s = new BigInteger4(signHex.substring(64), 16);
637
+ r = utils3.hexToNumber(signHex.substring(0, 64));
638
+ s = utils3.hexToNumber(signHex.substring(64));
728
639
  }
729
- const PA = curve2.decodePointHex(publicKey);
730
- const e = new BigInteger4(hashHex, 16);
731
- const t = r.add(s).mod(n2);
732
- if (t.equals(BigInteger4.ZERO))
640
+ const PA = sm2Curve.ProjectivePoint.fromHex(publicKey);
641
+ const e = utils3.hexToNumber(hashHex);
642
+ const t = mod2.mod(r + s, sm2Curve.CURVE.n);
643
+ if (t === ZERO)
733
644
  return false;
734
- const x1y1 = G2.multiply(s).add(PA.multiply(t));
735
- const R = e.add(x1y1.getX().toBigInteger()).mod(n2);
736
- return r.equals(R);
645
+ const x1y1 = sm2Curve.ProjectivePoint.BASE.multiply(s).add(PA.multiply(t));
646
+ const R = mod2.mod(e + x1y1.x, sm2Curve.CURVE.n);
647
+ return r === R;
737
648
  }
738
649
  function getHash(hashHex, publicKey, userId = "1234567812345678") {
739
650
  userId = utf8ToHex(userId);
740
- const a = leftPad(G2.curve.a.toBigInteger().toRadix(16), 64);
741
- const b = leftPad(G2.curve.b.toBigInteger().toRadix(16), 64);
742
- const gx = leftPad(G2.getX().toBigInteger().toRadix(16), 64);
743
- const gy = leftPad(G2.getY().toBigInteger().toRadix(16), 64);
651
+ const a = leftPad2(utils3.numberToHexUnpadded(sm2Curve.CURVE.a), 64);
652
+ const b = leftPad2(utils3.numberToHexUnpadded(sm2Curve.CURVE.b), 64);
653
+ const gx = leftPad2(utils3.numberToHexUnpadded(sm2Curve.ProjectivePoint.BASE.x), 64);
654
+ const gy = leftPad2(utils3.numberToHexUnpadded(sm2Curve.ProjectivePoint.BASE.y), 64);
744
655
  let px;
745
656
  let py;
746
657
  if (publicKey.length === 128) {
747
658
  px = publicKey.substring(0, 64);
748
659
  py = publicKey.substring(64, 128);
749
660
  } else {
750
- const point = G2.curve.decodePointHex(publicKey);
751
- px = leftPad(point.getX().toBigInteger().toRadix(16), 64);
752
- py = leftPad(point.getY().toBigInteger().toRadix(16), 64);
661
+ const point = sm2Curve.ProjectivePoint.fromHex(publicKey);
662
+ px = leftPad2(utils3.numberToHexUnpadded(point.x), 64);
663
+ py = leftPad2(utils3.numberToHexUnpadded(point.y), 64);
753
664
  }
754
665
  const data = hexToArray(userId + a + b + gx + gy + px + py);
755
666
  const entl = userId.length * 4;
@@ -757,68 +668,21 @@ function getHash(hashHex, publicKey, userId = "1234567812345678") {
757
668
  return arrayToHex(Array.from(sm3(concatArray(z, typeof hashHex === "string" ? hexToArray(hashHex) : hashHex))));
758
669
  }
759
670
  function getPublicKeyFromPrivateKey(privateKey) {
760
- const PA = G2.multiply(new BigInteger4(privateKey, 16));
761
- const x = leftPad(PA.getX().toBigInteger().toString(16), 64);
762
- const y = leftPad(PA.getY().toBigInteger().toString(16), 64);
763
- return "04" + x + y;
671
+ const pubKey = sm2Curve.getPublicKey(privateKey, false);
672
+ const pubPad = leftPad2(utils3.bytesToHex(pubKey), 64);
673
+ return pubPad;
764
674
  }
765
675
  function getPoint() {
766
676
  const keypair = generateKeyPairHex();
767
- const PA = curve2.decodePointHex(keypair.publicKey);
677
+ const PA = sm2Curve.ProjectivePoint.fromHex(keypair.publicKey);
678
+ const k = utils3.hexToNumber(keypair.privateKey);
768
679
  return {
769
680
  ...keypair,
770
- k: new BigInteger4(keypair.privateKey, 16),
771
- x1: PA.getX().toBigInteger()
681
+ k,
682
+ x1: PA.x
772
683
  };
773
684
  }
774
685
 
775
- // src/sm3/index.ts
776
- var sm3_exports = {};
777
- __export(sm3_exports, {
778
- sm3: () => sm32,
779
- utf8ToArray: () => utf8ToArray
780
- });
781
- function utf8ToArray(str) {
782
- const arr = [];
783
- for (let i = 0, len = str.length; i < len; i++) {
784
- const point = str.codePointAt(i);
785
- if (point <= 127) {
786
- arr.push(point);
787
- } else if (point <= 2047) {
788
- arr.push(192 | point >>> 6);
789
- arr.push(128 | point & 63);
790
- } else if (point <= 55295 || point >= 57344 && point <= 65535) {
791
- arr.push(224 | point >>> 12);
792
- arr.push(128 | point >>> 6 & 63);
793
- arr.push(128 | point & 63);
794
- } else if (point >= 65536 && point <= 1114111) {
795
- i++;
796
- arr.push(240 | point >>> 18 & 28);
797
- arr.push(128 | point >>> 12 & 63);
798
- arr.push(128 | point >>> 6 & 63);
799
- arr.push(128 | point & 63);
800
- } else {
801
- arr.push(point);
802
- throw new Error("input is not supported");
803
- }
804
- }
805
- return new Uint8Array(arr);
806
- }
807
- function sm32(input, options) {
808
- input = typeof input === "string" ? utf8ToArray(input) : input;
809
- if (options) {
810
- const mode = options.mode || "hmac";
811
- if (mode !== "hmac")
812
- throw new Error("invalid mode");
813
- let key = options.key;
814
- if (!key)
815
- throw new Error("invalid key");
816
- key = typeof key === "string" ? hexToArray(key) : key;
817
- return arrayToHex(Array.from(hmac(input, key)));
818
- }
819
- return arrayToHex(Array.from(sm3(input)));
820
- }
821
-
822
686
  // src/sm4/index.ts
823
687
  var sm4_exports = {};
824
688
  __export(sm4_exports, {