sm-crypto-v2 1.4.0 → 1.5.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.
package/dist/index.js CHANGED
@@ -17,17 +17,17 @@ var __copyProps = (to, from, except, desc) => {
17
17
  }
18
18
  return to;
19
19
  };
20
- var __toESM = (mod4, isNodeMode, target) => (target = mod4 != null ? __create(__getProtoOf(mod4)) : {}, __copyProps(
21
- isNodeMode || !mod4 || !mod4.__esModule ? __defProp(target, "default", { value: mod4, enumerable: true }) : target,
22
- mod4
20
+ var __toESM = (mod2, isNodeMode, target) => (target = mod2 != null ? __create(__getProtoOf(mod2)) : {}, __copyProps(
21
+ isNodeMode || !mod2 || !mod2.__esModule ? __defProp(target, "default", { value: mod2, enumerable: true }) : target,
22
+ mod2
23
23
  ));
24
- var __toCommonJS = (mod4) => __copyProps(__defProp({}, "__esModule", { value: true }), mod4);
24
+ var __toCommonJS = (mod2) => __copyProps(__defProp({}, "__esModule", { value: true }), mod2);
25
25
 
26
26
  // src/index.ts
27
27
  var src_exports = {};
28
28
  __export(src_exports, {
29
29
  sm2: () => sm2_exports,
30
- sm3: () => sm3_exports,
30
+ sm3: () => sm32,
31
31
  sm4: () => sm4_exports
32
32
  });
33
33
  module.exports = __toCommonJS(src_exports);
@@ -35,12 +35,12 @@ module.exports = __toCommonJS(src_exports);
35
35
  // src/sm2/index.ts
36
36
  var sm2_exports = {};
37
37
  __export(sm2_exports, {
38
+ EmptyArray: () => EmptyArray,
38
39
  arrayToHex: () => arrayToHex,
39
40
  arrayToUtf8: () => arrayToUtf8,
40
41
  calculateSharedKey: () => calculateSharedKey,
41
42
  comparePublicKeyHex: () => comparePublicKeyHex,
42
43
  compressPublicKeyHex: () => compressPublicKeyHex,
43
- concatArray: () => concatArray,
44
44
  doDecrypt: () => doDecrypt,
45
45
  doEncrypt: () => doEncrypt,
46
46
  doSignature: () => doSignature,
@@ -51,7 +51,7 @@ __export(sm2_exports, {
51
51
  getPublicKeyFromPrivateKey: () => getPublicKeyFromPrivateKey,
52
52
  hexToArray: () => hexToArray,
53
53
  initRNGPool: () => initRNGPool,
54
- leftPad: () => leftPad2,
54
+ leftPad: () => leftPad,
55
55
  utf8ToHex: () => utf8ToHex,
56
56
  verifyPublicKey: () => verifyPublicKey
57
57
  });
@@ -186,181 +186,7 @@ var utils2 = __toESM(require("@noble/curves/abstract/utils"));
186
186
  var import_weierstrass = require("@noble/curves/abstract/weierstrass");
187
187
  var import_modular = require("@noble/curves/abstract/modular");
188
188
 
189
- // src/sm2/sm3.ts
190
- var W = new Uint32Array(68);
191
- var M = new Uint32Array(64);
192
- function rotl(x, n) {
193
- const s = n & 31;
194
- return x << s | x >>> 32 - s;
195
- }
196
- function xor(x, y) {
197
- const result = new Uint8Array(x.length);
198
- for (let i = x.length - 1; i >= 0; i--)
199
- result[i] = (x[i] ^ y[i]) & 255;
200
- return result;
201
- }
202
- function P0(X) {
203
- return X ^ rotl(X, 9) ^ rotl(X, 17);
204
- }
205
- function P1(X) {
206
- return X ^ rotl(X, 15) ^ rotl(X, 23);
207
- }
208
- function sm3(array) {
209
- let len = array.length * 8;
210
- let k = len % 512;
211
- k = k >= 448 ? 512 - k % 448 - 1 : 448 - k - 1;
212
- const kArr = new Array((k - 7) / 8);
213
- const lenArr = new Array(8);
214
- for (let i = 0, len2 = kArr.length; i < len2; i++)
215
- kArr[i] = 0;
216
- for (let i = 0, len2 = lenArr.length; i < len2; i++)
217
- lenArr[i] = 0;
218
- let lenString = len.toString(2);
219
- for (let i = 7; i >= 0; i--) {
220
- if (lenString.length > 8) {
221
- const start = lenString.length - 8;
222
- lenArr[i] = parseInt(lenString.substring(start), 2);
223
- lenString = lenString.substring(0, start);
224
- } else if (lenString.length > 0) {
225
- lenArr[i] = parseInt(lenString, 2);
226
- lenString = "";
227
- }
228
- }
229
- const m = Uint8Array.from([...array, 128, ...kArr, ...lenArr]);
230
- const dataView = new DataView(m.buffer, 0);
231
- const n = m.length / 64;
232
- const V = new Uint32Array([1937774191, 1226093241, 388252375, 3666478592, 2842636476, 372324522, 3817729613, 2969243214]);
233
- for (let i = 0; i < n; i++) {
234
- W.fill(0);
235
- M.fill(0);
236
- const start = 16 * i;
237
- for (let j = 0; j < 16; j++) {
238
- W[j] = dataView.getUint32((start + j) * 4, false);
239
- }
240
- for (let j = 16; j < 68; j++) {
241
- W[j] = P1(W[j - 16] ^ W[j - 9] ^ rotl(W[j - 3], 15)) ^ rotl(W[j - 13], 7) ^ W[j - 6];
242
- }
243
- for (let j = 0; j < 64; j++) {
244
- M[j] = W[j] ^ W[j + 4];
245
- }
246
- const T1 = 2043430169;
247
- const T2 = 2055708042;
248
- let A = V[0];
249
- let B = V[1];
250
- let C = V[2];
251
- let D = V[3];
252
- let E = V[4];
253
- let F = V[5];
254
- let G = V[6];
255
- let H = V[7];
256
- let SS1;
257
- let SS2;
258
- let TT1;
259
- let TT2;
260
- let T;
261
- for (let j = 0; j < 64; j++) {
262
- T = j >= 0 && j <= 15 ? T1 : T2;
263
- SS1 = rotl(rotl(A, 12) + E + rotl(T, j), 7);
264
- SS2 = SS1 ^ rotl(A, 12);
265
- TT1 = (j >= 0 && j <= 15 ? A ^ B ^ C : A & B | A & C | B & C) + D + SS2 + M[j];
266
- TT2 = (j >= 0 && j <= 15 ? E ^ F ^ G : E & F | ~E & G) + H + SS1 + W[j];
267
- D = C;
268
- C = rotl(B, 9);
269
- B = A;
270
- A = TT1;
271
- H = G;
272
- G = rotl(F, 19);
273
- F = E;
274
- E = P0(TT2);
275
- }
276
- V[0] ^= A;
277
- V[1] ^= B;
278
- V[2] ^= C;
279
- V[3] ^= D;
280
- V[4] ^= E;
281
- V[5] ^= F;
282
- V[6] ^= G;
283
- V[7] ^= H;
284
- }
285
- const result = new Uint8Array(V.length * 4);
286
- for (let i = 0, len2 = V.length; i < len2; i++) {
287
- const word = V[i];
288
- result[i * 4] = (word & 4278190080) >>> 24;
289
- result[i * 4 + 1] = (word & 16711680) >>> 16;
290
- result[i * 4 + 2] = (word & 65280) >>> 8;
291
- result[i * 4 + 3] = word & 255;
292
- }
293
- return result;
294
- }
295
- var blockLen = 64;
296
- var iPad = new Uint8Array(blockLen);
297
- var oPad = new Uint8Array(blockLen);
298
- for (let i = 0; i < blockLen; i++) {
299
- iPad[i] = 54;
300
- oPad[i] = 92;
301
- }
302
- function hmac(input, key) {
303
- if (key.length > blockLen)
304
- key = sm3(key);
305
- while (key.length < blockLen) {
306
- const padKey = new Uint8Array(blockLen);
307
- padKey.set(key);
308
- key = padKey;
309
- }
310
- const iPadKey = xor(key, iPad);
311
- const oPadKey = xor(key, oPad);
312
- const hash = sm3(concatArray(iPadKey, input));
313
- return sm3(concatArray(oPadKey, hash));
314
- }
315
-
316
- // src/sm3/index.ts
317
- var sm3_exports = {};
318
- __export(sm3_exports, {
319
- sm3: () => sm32,
320
- utf8ToArray: () => utf8ToArray
321
- });
322
- function utf8ToArray(str) {
323
- const arr = [];
324
- for (let i = 0, len = str.length; i < len; i++) {
325
- const point = str.codePointAt(i);
326
- if (point <= 127) {
327
- arr.push(point);
328
- } else if (point <= 2047) {
329
- arr.push(192 | point >>> 6);
330
- arr.push(128 | point & 63);
331
- } else if (point <= 55295 || point >= 57344 && point <= 65535) {
332
- arr.push(224 | point >>> 12);
333
- arr.push(128 | point >>> 6 & 63);
334
- arr.push(128 | point & 63);
335
- } else if (point >= 65536 && point <= 1114111) {
336
- i++;
337
- arr.push(240 | point >>> 18 & 28);
338
- arr.push(128 | point >>> 12 & 63);
339
- arr.push(128 | point >>> 6 & 63);
340
- arr.push(128 | point & 63);
341
- } else {
342
- arr.push(point);
343
- throw new Error("input is not supported");
344
- }
345
- }
346
- return new Uint8Array(arr);
347
- }
348
- function sm32(input, options) {
349
- input = typeof input === "string" ? utf8ToArray(input) : input;
350
- if (options) {
351
- const mode = options.mode || "hmac";
352
- if (mode !== "hmac")
353
- throw new Error("invalid mode");
354
- let key = options.key;
355
- if (!key)
356
- throw new Error("invalid key");
357
- key = typeof key === "string" ? hexToArray(key) : key;
358
- return arrayToHex(Array.from(hmac(input, key)));
359
- }
360
- return arrayToHex(Array.from(sm3(input)));
361
- }
362
-
363
- // src/sm2/ec.ts
189
+ // src/sm2/rng.ts
364
190
  var DEFAULT_PRNG_POOL_SIZE = 16384;
365
191
  var prngPool = new Uint8Array(0);
366
192
  var _syncCrypto;
@@ -415,13 +241,304 @@ function randomBytes(length = 0) {
415
241
  return result;
416
242
  }
417
243
  }
418
- function createHash() {
419
- const hashC = (msg) => sm3(typeof msg === "string" ? utf8ToArray(msg) : msg);
420
- hashC.outputLen = 256;
421
- hashC.blockLen = 512;
422
- hashC.create = () => sm3(Uint8Array.from([]));
244
+
245
+ // src/sm3/utils.ts
246
+ var u8a = (a) => a instanceof Uint8Array;
247
+ var createView = (arr) => new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
248
+ var isLE = new Uint8Array(new Uint32Array([287454020]).buffer)[0] === 68;
249
+ if (!isLE)
250
+ throw new Error("Non little-endian hardware is not supported");
251
+ var hexes = Array.from({ length: 256 }, (v, i) => i.toString(16).padStart(2, "0"));
252
+ function bytesToHex(bytes) {
253
+ if (!u8a(bytes))
254
+ throw new Error("Uint8Array expected");
255
+ let hex = "";
256
+ for (let i = 0; i < bytes.length; i++) {
257
+ hex += hexes[bytes[i]];
258
+ }
259
+ return hex;
260
+ }
261
+ function utf8ToBytes(str) {
262
+ if (typeof str !== "string")
263
+ throw new Error(`utf8ToBytes expected string, got ${typeof str}`);
264
+ return new Uint8Array(new TextEncoder().encode(str));
265
+ }
266
+ function toBytes(data) {
267
+ if (typeof data === "string")
268
+ data = utf8ToBytes(data);
269
+ if (!u8a(data))
270
+ throw new Error(`expected Uint8Array, got ${typeof data}`);
271
+ return data;
272
+ }
273
+ var Hash = class {
274
+ clone() {
275
+ return this._cloneInto();
276
+ }
277
+ };
278
+ function wrapConstructor(hashCons) {
279
+ const hashC = (msg) => hashCons().update(toBytes(msg)).digest();
280
+ const tmp2 = hashCons();
281
+ hashC.outputLen = tmp2.outputLen;
282
+ hashC.blockLen = tmp2.blockLen;
283
+ hashC.create = () => hashCons();
423
284
  return hashC;
424
285
  }
286
+
287
+ // src/sm2/sm3.ts
288
+ var BoolA = (A, B, C) => A & B | A & C | B & C;
289
+ var BoolB = (A, B, C) => A ^ B ^ C;
290
+ var BoolC = (A, B, C) => A & B | ~A & C;
291
+ function setBigUint64(view, byteOffset, value, isLE2) {
292
+ if (typeof view.setBigUint64 === "function")
293
+ return view.setBigUint64(byteOffset, value, isLE2);
294
+ const _32n = BigInt(32);
295
+ const _u32_max = BigInt(4294967295);
296
+ const wh = Number(value >> _32n & _u32_max);
297
+ const wl = Number(value & _u32_max);
298
+ const h = isLE2 ? 4 : 0;
299
+ const l = isLE2 ? 0 : 4;
300
+ view.setUint32(byteOffset + h, wh, isLE2);
301
+ view.setUint32(byteOffset + l, wl, isLE2);
302
+ }
303
+ function rotl(x2, n) {
304
+ const s = n & 31;
305
+ return x2 << s | x2 >>> 32 - s;
306
+ }
307
+ function P0(X) {
308
+ return X ^ rotl(X, 9) ^ rotl(X, 17);
309
+ }
310
+ function P1(X) {
311
+ return X ^ rotl(X, 15) ^ rotl(X, 23);
312
+ }
313
+ var SHA2 = class extends Hash {
314
+ constructor(blockLen, outputLen, padOffset, isLE2) {
315
+ super();
316
+ this.blockLen = blockLen;
317
+ this.outputLen = outputLen;
318
+ this.padOffset = padOffset;
319
+ this.isLE = isLE2;
320
+ this.buffer = new Uint8Array(blockLen);
321
+ this.view = createView(this.buffer);
322
+ }
323
+ buffer;
324
+ view;
325
+ finished = false;
326
+ length = 0;
327
+ pos = 0;
328
+ destroyed = false;
329
+ update(data) {
330
+ const { view, buffer, blockLen } = this;
331
+ data = toBytes(data);
332
+ const len = data.length;
333
+ for (let pos = 0; pos < len; ) {
334
+ const take = Math.min(blockLen - this.pos, len - pos);
335
+ if (take === blockLen) {
336
+ const dataView = createView(data);
337
+ for (; blockLen <= len - pos; pos += blockLen)
338
+ this.process(dataView, pos);
339
+ continue;
340
+ }
341
+ buffer.set(data.subarray(pos, pos + take), this.pos);
342
+ this.pos += take;
343
+ pos += take;
344
+ if (this.pos === blockLen) {
345
+ this.process(view, 0);
346
+ this.pos = 0;
347
+ }
348
+ }
349
+ this.length += data.length;
350
+ this.roundClean();
351
+ return this;
352
+ }
353
+ digestInto(out) {
354
+ this.finished = true;
355
+ const { buffer, view, blockLen, isLE: isLE2 } = this;
356
+ let { pos } = this;
357
+ buffer[pos++] = 128;
358
+ this.buffer.subarray(pos).fill(0);
359
+ if (this.padOffset > blockLen - pos) {
360
+ this.process(view, 0);
361
+ pos = 0;
362
+ }
363
+ for (let i = pos; i < blockLen; i++)
364
+ buffer[i] = 0;
365
+ setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE2);
366
+ this.process(view, 0);
367
+ const oview = createView(out);
368
+ const len = this.outputLen;
369
+ if (len % 4)
370
+ throw new Error("_sha2: outputLen should be aligned to 32bit");
371
+ const outLen = len / 4;
372
+ const state = this.get();
373
+ if (outLen > state.length)
374
+ throw new Error("_sha2: outputLen bigger than state");
375
+ for (let i = 0; i < outLen; i++)
376
+ oview.setUint32(4 * i, state[i], isLE2);
377
+ }
378
+ digest() {
379
+ const { buffer, outputLen } = this;
380
+ this.digestInto(buffer);
381
+ const res = buffer.slice(0, outputLen);
382
+ this.destroy();
383
+ return res;
384
+ }
385
+ _cloneInto(to) {
386
+ to ||= new this.constructor();
387
+ to.set(...this.get());
388
+ const { blockLen, buffer, length, finished, destroyed, pos } = this;
389
+ to.length = length;
390
+ to.pos = pos;
391
+ to.finished = finished;
392
+ to.destroyed = destroyed;
393
+ if (length % blockLen)
394
+ to.buffer.set(buffer);
395
+ return to;
396
+ }
397
+ };
398
+ var IV = new Uint32Array([1937774191, 1226093241, 388252375, 3666478592, 2842636476, 372324522, 3817729613, 2969243214]);
399
+ var SM3_W = new Uint32Array(68);
400
+ var SM3_M = new Uint32Array(64);
401
+ var T1 = 2043430169;
402
+ var T2 = 2055708042;
403
+ var SM3 = class extends SHA2 {
404
+ A = IV[0] | 0;
405
+ B = IV[1] | 0;
406
+ C = IV[2] | 0;
407
+ D = IV[3] | 0;
408
+ E = IV[4] | 0;
409
+ F = IV[5] | 0;
410
+ G = IV[6] | 0;
411
+ H = IV[7] | 0;
412
+ constructor() {
413
+ super(64, 32, 8, false);
414
+ }
415
+ get() {
416
+ const { A, B, C, D, E, F, G, H } = this;
417
+ return [A, B, C, D, E, F, G, H];
418
+ }
419
+ set(A, B, C, D, E, F, G, H) {
420
+ this.A = A | 0;
421
+ this.B = B | 0;
422
+ this.C = C | 0;
423
+ this.D = D | 0;
424
+ this.E = E | 0;
425
+ this.F = F | 0;
426
+ this.G = G | 0;
427
+ this.H = H | 0;
428
+ }
429
+ process(view, offset) {
430
+ for (let i = 0; i < 16; i++, offset += 4)
431
+ SM3_W[i] = view.getUint32(offset, false);
432
+ for (let i = 16; i < 68; i++) {
433
+ 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];
434
+ }
435
+ for (let i = 0; i < 64; i++) {
436
+ SM3_M[i] = SM3_W[i] ^ SM3_W[i + 4];
437
+ }
438
+ let { A, B, C, D, E, F, G, H } = this;
439
+ for (let j = 0; j < 64; j++) {
440
+ let small = j >= 0 && j <= 15;
441
+ let T = small ? T1 : T2;
442
+ let SS1 = rotl(rotl(A, 12) + E + rotl(T, j), 7);
443
+ let SS2 = SS1 ^ rotl(A, 12);
444
+ let TT1 = (small ? BoolB(A, B, C) : BoolA(A, B, C)) + D + SS2 + SM3_M[j] | 0;
445
+ let TT2 = (small ? BoolB(E, F, G) : BoolC(E, F, G)) + H + SS1 + SM3_W[j] | 0;
446
+ D = C;
447
+ C = rotl(B, 9);
448
+ B = A;
449
+ A = TT1;
450
+ H = G;
451
+ G = rotl(F, 19);
452
+ F = E;
453
+ E = P0(TT2);
454
+ }
455
+ A = A ^ this.A | 0;
456
+ B = B ^ this.B | 0;
457
+ C = C ^ this.C | 0;
458
+ D = D ^ this.D | 0;
459
+ E = E ^ this.E | 0;
460
+ F = F ^ this.F | 0;
461
+ G = G ^ this.G | 0;
462
+ H = H ^ this.H | 0;
463
+ this.set(A, B, C, D, E, F, G, H);
464
+ }
465
+ roundClean() {
466
+ SM3_W.fill(0);
467
+ }
468
+ destroy() {
469
+ this.set(0, 0, 0, 0, 0, 0, 0, 0);
470
+ this.buffer.fill(0);
471
+ }
472
+ };
473
+ var sm3 = wrapConstructor(() => new SM3());
474
+
475
+ // src/sm2/hmac.ts
476
+ var HMAC = class extends Hash {
477
+ oHash;
478
+ iHash;
479
+ blockLen;
480
+ outputLen;
481
+ finished = false;
482
+ destroyed = false;
483
+ constructor(hash, _key) {
484
+ super();
485
+ const key = toBytes(_key);
486
+ this.iHash = hash.create();
487
+ if (typeof this.iHash.update !== "function")
488
+ throw new Error("Expected instance of class which extends utils.Hash");
489
+ this.blockLen = this.iHash.blockLen;
490
+ this.outputLen = this.iHash.outputLen;
491
+ const blockLen = this.blockLen;
492
+ const pad = new Uint8Array(blockLen);
493
+ pad.set(key.length > blockLen ? hash.create().update(key).digest() : key);
494
+ for (let i = 0; i < pad.length; i++)
495
+ pad[i] ^= 54;
496
+ this.iHash.update(pad);
497
+ this.oHash = hash.create();
498
+ for (let i = 0; i < pad.length; i++)
499
+ pad[i] ^= 54 ^ 92;
500
+ this.oHash.update(pad);
501
+ pad.fill(0);
502
+ }
503
+ update(buf) {
504
+ this.iHash.update(buf);
505
+ return this;
506
+ }
507
+ digestInto(out) {
508
+ this.finished = true;
509
+ this.iHash.digestInto(out);
510
+ this.oHash.update(out);
511
+ this.oHash.digestInto(out);
512
+ this.destroy();
513
+ }
514
+ digest() {
515
+ const out = new Uint8Array(this.oHash.outputLen);
516
+ this.digestInto(out);
517
+ return out;
518
+ }
519
+ _cloneInto(to) {
520
+ to ||= Object.create(Object.getPrototypeOf(this), {});
521
+ const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this;
522
+ to = to;
523
+ to.finished = finished;
524
+ to.destroyed = destroyed;
525
+ to.blockLen = blockLen;
526
+ to.outputLen = outputLen;
527
+ to.oHash = oHash._cloneInto(to.oHash);
528
+ to.iHash = iHash._cloneInto(to.iHash);
529
+ return to;
530
+ }
531
+ destroy() {
532
+ this.destroyed = true;
533
+ this.oHash.destroy();
534
+ this.iHash.destroy();
535
+ }
536
+ };
537
+ var hmac = (hash, key, message) => new HMAC(hash, key).update(message).digest();
538
+ hmac.create = (hash, key) => new HMAC(hash, key);
539
+
540
+ // src/sm2/ec.ts
541
+ var import_utils3 = require("@noble/curves/abstract/utils");
425
542
  var sm2Fp = (0, import_modular.Field)(BigInt("115792089210356248756420345214020892766250353991924191454421193933289684991999"));
426
543
  var sm2Curve = (0, import_weierstrass.weierstrass)({
427
544
  a: BigInt("115792089210356248756420345214020892766250353991924191454421193933289684991996"),
@@ -431,18 +548,19 @@ var sm2Curve = (0, import_weierstrass.weierstrass)({
431
548
  n: BigInt("115792089210356248756420345214020892766061623724957744567843809356293439045923"),
432
549
  Gx: BigInt("22963146547237050559479531362550074578802567295341616970375194840604139615431"),
433
550
  Gy: BigInt("85132369209828568825618990617112496413088388631904505083283536607588877201568"),
434
- hash: createHash(),
435
- hmac: (key, ...msgs) => hmac(concatArray(...msgs), key),
551
+ hash: sm3,
552
+ hmac: (key, ...msgs) => hmac(sm3, key, (0, import_utils3.concatBytes)(...msgs)),
436
553
  randomBytes
437
554
  });
555
+ var field = (0, import_modular.Field)(BigInt(sm2Curve.CURVE.n));
438
556
 
439
557
  // src/sm2/utils.ts
440
558
  var import_modular2 = require("@noble/curves/abstract/modular");
441
559
  function generateKeyPairHex(str) {
442
560
  const privateKey = str ? utils2.numberToBytesBE((0, import_modular2.mod)(BigInt(str), ONE) + ONE, 32) : sm2Curve.utils.randomPrivateKey();
443
561
  const publicKey = sm2Curve.getPublicKey(privateKey, false);
444
- const privPad = leftPad2(utils2.bytesToHex(privateKey), 64);
445
- const pubPad = leftPad2(utils2.bytesToHex(publicKey), 64);
562
+ const privPad = leftPad(utils2.bytesToHex(privateKey), 64);
563
+ const pubPad = leftPad(utils2.bytesToHex(publicKey), 64);
446
564
  return { privateKey: privPad, publicKey: pubPad };
447
565
  }
448
566
  function compressPublicKeyHex(s) {
@@ -471,7 +589,7 @@ function utf8ToHex(input) {
471
589
  }
472
590
  return hexChars.join("");
473
591
  }
474
- function leftPad2(input, num) {
592
+ function leftPad(input, num) {
475
593
  if (input.length >= num)
476
594
  return input;
477
595
  return new Array(num - input.length + 1).join("0") + input;
@@ -503,7 +621,7 @@ function arrayToUtf8(arr) {
503
621
  function hexToArray(hexStr) {
504
622
  let hexStrLength = hexStr.length;
505
623
  if (hexStrLength % 2 !== 0) {
506
- hexStr = leftPad2(hexStr, hexStrLength + 1);
624
+ hexStr = leftPad(hexStr, hexStrLength + 1);
507
625
  }
508
626
  hexStrLength = hexStr.length;
509
627
  const wordLength = hexStrLength / 2;
@@ -517,9 +635,9 @@ function verifyPublicKey(publicKey) {
517
635
  const point = sm2Curve.ProjectivePoint.fromHex(publicKey);
518
636
  if (!point)
519
637
  return false;
520
- const x = point.x;
638
+ const x2 = point.x;
521
639
  const y = point.y;
522
- return sm2Fp.sqr(y) === sm2Fp.add(sm2Fp.add(sm2Fp.mul(x, sm2Fp.sqr(x)), sm2Fp.mul(x, sm2Curve.CURVE.a)), sm2Curve.CURVE.b);
640
+ return sm2Fp.sqr(y) === sm2Fp.add(sm2Fp.addN(sm2Fp.mulN(x2, sm2Fp.sqrN(x2)), sm2Fp.mulN(x2, sm2Curve.CURVE.a)), sm2Curve.CURVE.b);
523
641
  }
524
642
  function comparePublicKeyHex(publicKey1, publicKey2) {
525
643
  const point1 = sm2Curve.ProjectivePoint.fromHex(publicKey1);
@@ -530,36 +648,26 @@ function comparePublicKeyHex(publicKey1, publicKey2) {
530
648
  return false;
531
649
  return point1.equals(point2);
532
650
  }
533
- function concatArray(...arrays) {
534
- let totalLength = arrays.reduce((acc, value) => acc + value.length, 0);
535
- if (!arrays.length)
536
- return new Uint8Array();
537
- let result = new Uint8Array(totalLength);
538
- let length = 0;
539
- for (let array of arrays) {
540
- result.set(array, length);
541
- length += array.length;
542
- }
543
- return result;
544
- }
545
651
 
546
652
  // src/sm2/index.ts
547
- var mod2 = __toESM(require("@noble/curves/abstract/modular"));
548
653
  var utils4 = __toESM(require("@noble/curves/abstract/utils"));
549
654
 
550
655
  // src/sm2/kx.ts
551
656
  var utils3 = __toESM(require("@noble/curves/abstract/utils"));
552
- var import_modular3 = require("@noble/curves/abstract/modular");
553
- var field = (0, import_modular3.Field)(BigInt(sm2Curve.CURVE.n));
554
657
  var wPow2 = utils3.hexToNumber("80000000000000000000000000000000");
555
658
  var wPow2Sub1 = utils3.hexToNumber("7fffffffffffffffffffffffffffffff");
556
659
  function hkdf(z, keylen) {
557
- let t = new Uint8Array();
558
660
  let msg = new Uint8Array(keylen);
559
661
  let ct = 1;
560
662
  let offset = 0;
663
+ let t = EmptyArray;
664
+ const ctShift = new Uint8Array(4);
561
665
  const nextT = () => {
562
- t = sm3(Uint8Array.from([...z, ct >> 24 & 255, ct >> 16 & 255, ct >> 8 & 255, ct & 255]));
666
+ ctShift[0] = ct >> 24 & 255;
667
+ ctShift[1] = ct >> 16 & 255;
668
+ ctShift[2] = ct >> 8 & 255;
669
+ ctShift[3] = ct & 255;
670
+ t = sm3(utils3.concatBytes(z, ctShift));
563
671
  ct++;
564
672
  offset = 0;
565
673
  };
@@ -581,18 +689,19 @@ function calculateSharedKey(keypairA, ephemeralKeypairA, publicKeyB, ephemeralPu
581
689
  const dA = utils3.hexToNumber(keypairA.privateKey);
582
690
  const x1 = RA.x;
583
691
  const x1_ = field.add(wPow2, x1 & wPow2Sub1);
584
- const tA = field.add(dA, field.mul(x1_, rA));
692
+ const tA = field.add(dA, field.mulN(x1_, rA));
585
693
  const x2 = RB.x;
586
694
  const x2_ = field.add(wPow2, x2 & wPow2Sub1);
587
695
  const U = RB.multiply(x2_).add(PB).multiply(tA);
588
- const xU = hexToArray(leftPad2(utils3.numberToHexUnpadded(U.x), 64));
589
- const yU = hexToArray(leftPad2(utils3.numberToHexUnpadded(U.y), 64));
590
- const KA = hkdf(concatArray(xU, yU, ZA, ZB), sharedKeyLength);
696
+ const xU = hexToArray(leftPad(utils3.numberToHexUnpadded(U.x), 64));
697
+ const yU = hexToArray(leftPad(utils3.numberToHexUnpadded(U.y), 64));
698
+ const KA = hkdf(utils3.concatBytes(xU, yU, ZA, ZB), sharedKeyLength);
591
699
  return KA;
592
700
  }
593
701
 
594
702
  // src/sm2/index.ts
595
703
  var C1C2C3 = 0;
704
+ var EmptyArray = new Uint8Array();
596
705
  function doEncrypt(msg, publicKey, cipherMode = 1) {
597
706
  const msgArr = typeof msg === "string" ? hexToArray(utf8ToHex(msg)) : Uint8Array.from(msg);
598
707
  const publicKeyPoint = sm2Curve.ProjectivePoint.fromHex(publicKey);
@@ -602,26 +711,33 @@ function doEncrypt(msg, publicKey, cipherMode = 1) {
602
711
  if (c1.length > 128)
603
712
  c1 = c1.substring(c1.length - 128);
604
713
  const p = publicKeyPoint.multiply(k);
605
- const x2 = hexToArray(leftPad2(utils4.numberToHexUnpadded(p.x), 64));
606
- const y2 = hexToArray(leftPad2(utils4.numberToHexUnpadded(p.y), 64));
607
- const c3 = arrayToHex(Array.from(sm3(concatArray(x2, msgArr, y2))));
714
+ const x2 = hexToArray(leftPad(utils4.numberToHexUnpadded(p.x), 64));
715
+ const y2 = hexToArray(leftPad(utils4.numberToHexUnpadded(p.y), 64));
716
+ const c3 = bytesToHex(sm3(utils4.concatBytes(x2, msgArr, y2)));
717
+ xorCipherStream(x2, y2, msgArr);
718
+ const c2 = bytesToHex(msgArr);
719
+ return cipherMode === C1C2C3 ? c1 + c2 + c3 : c1 + c3 + c2;
720
+ }
721
+ function xorCipherStream(x2, y2, msg) {
608
722
  let ct = 1;
609
723
  let offset = 0;
610
- let t = new Uint8Array();
611
- const z = concatArray(x2, y2);
724
+ let t = EmptyArray;
725
+ const ctShift = new Uint8Array(4);
612
726
  const nextT = () => {
613
- t = sm3(Uint8Array.from([...z, ct >> 24 & 255, ct >> 16 & 255, ct >> 8 & 255, ct & 255]));
727
+ ctShift[0] = ct >> 24 & 255;
728
+ ctShift[1] = ct >> 16 & 255;
729
+ ctShift[2] = ct >> 8 & 255;
730
+ ctShift[3] = ct & 255;
731
+ t = sm3(utils4.concatBytes(x2, y2, ctShift));
614
732
  ct++;
615
733
  offset = 0;
616
734
  };
617
735
  nextT();
618
- for (let i = 0, len = msgArr.length; i < len; i++) {
736
+ for (let i = 0, len = msg.length; i < len; i++) {
619
737
  if (offset === t.length)
620
738
  nextT();
621
- msgArr[i] ^= t[offset++] & 255;
739
+ msg[i] ^= t[offset++] & 255;
622
740
  }
623
- const c2 = arrayToHex(Array.from(msgArr));
624
- return cipherMode === C1C2C3 ? c1 + c2 + c3 : c1 + c3 + c2;
625
741
  }
626
742
  function doDecrypt(encryptData, privateKey, cipherMode = 1, {
627
743
  output = "string"
@@ -636,24 +752,10 @@ function doDecrypt(encryptData, privateKey, cipherMode = 1, {
636
752
  const msg = hexToArray(c2);
637
753
  const c1 = sm2Curve.ProjectivePoint.fromHex("04" + encryptData.substring(0, 128));
638
754
  const p = c1.multiply(privateKeyInteger);
639
- const x2 = hexToArray(leftPad2(utils4.numberToHexUnpadded(p.x), 64));
640
- const y2 = hexToArray(leftPad2(utils4.numberToHexUnpadded(p.y), 64));
641
- let ct = 1;
642
- let offset = 0;
643
- let t = new Uint8Array();
644
- const z = concatArray(x2, y2);
645
- const nextT = () => {
646
- t = sm3(Uint8Array.from([...z, ct >> 24 & 255, ct >> 16 & 255, ct >> 8 & 255, ct & 255]));
647
- ct++;
648
- offset = 0;
649
- };
650
- nextT();
651
- for (let i = 0, len = msg.length; i < len; i++) {
652
- if (offset === t.length)
653
- nextT();
654
- msg[i] ^= t[offset++] & 255;
655
- }
656
- const checkC3 = arrayToHex(Array.from(sm3(concatArray(x2, msg, y2))));
755
+ const x2 = hexToArray(leftPad(utils4.numberToHexUnpadded(p.x), 64));
756
+ const y2 = hexToArray(leftPad(utils4.numberToHexUnpadded(p.y), 64));
757
+ xorCipherStream(x2, y2, msg);
758
+ const checkC3 = arrayToHex(Array.from(sm3(utils4.concatBytes(x2, msg, y2))));
657
759
  if (checkC3 === c3.toLowerCase()) {
658
760
  return output === "array" ? msg : arrayToUtf8(msg);
659
761
  } else {
@@ -687,13 +789,13 @@ function doSignature(msg, privateKey, options = {}) {
687
789
  point = getPoint();
688
790
  }
689
791
  k = point.k;
690
- r = mod2.mod(e + point.x1, sm2Curve.CURVE.n);
792
+ r = field.add(e, point.x1);
691
793
  } while (r === ZERO || r + k === sm2Curve.CURVE.n);
692
- s = mod2.mod(mod2.invert(dA + ONE, sm2Curve.CURVE.n) * (k - r * dA), sm2Curve.CURVE.n);
794
+ s = field.mul(field.inv(field.addN(dA, ONE)), field.subN(k, field.mulN(r, dA)));
693
795
  } while (s === ZERO);
694
796
  if (der)
695
797
  return encodeDer(r, s);
696
- return leftPad2(utils4.numberToHexUnpadded(r), 64) + leftPad2(utils4.numberToHexUnpadded(s), 64);
798
+ return leftPad(utils4.numberToHexUnpadded(r), 64) + leftPad(utils4.numberToHexUnpadded(s), 64);
697
799
  }
698
800
  function doVerifySignature(msg, signHex, publicKey, options = {}) {
699
801
  let hashHex;
@@ -719,19 +821,19 @@ function doVerifySignature(msg, signHex, publicKey, options = {}) {
719
821
  }
720
822
  const PA = sm2Curve.ProjectivePoint.fromHex(publicKey);
721
823
  const e = utils4.hexToNumber(hashHex);
722
- const t = mod2.mod(r + s, sm2Curve.CURVE.n);
824
+ const t = field.add(r, s);
723
825
  if (t === ZERO)
724
826
  return false;
725
827
  const x1y1 = sm2Curve.ProjectivePoint.BASE.multiply(s).add(PA.multiply(t));
726
- const R = mod2.mod(e + x1y1.x, sm2Curve.CURVE.n);
828
+ const R = field.add(e, x1y1.x);
727
829
  return r === R;
728
830
  }
729
831
  function getHash(hashHex, publicKey, userId = "1234567812345678") {
730
832
  userId = utf8ToHex(userId);
731
- const a = leftPad2(utils4.numberToHexUnpadded(sm2Curve.CURVE.a), 64);
732
- const b = leftPad2(utils4.numberToHexUnpadded(sm2Curve.CURVE.b), 64);
733
- const gx = leftPad2(utils4.numberToHexUnpadded(sm2Curve.ProjectivePoint.BASE.x), 64);
734
- const gy = leftPad2(utils4.numberToHexUnpadded(sm2Curve.ProjectivePoint.BASE.y), 64);
833
+ const a = leftPad(utils4.numberToHexUnpadded(sm2Curve.CURVE.a), 64);
834
+ const b = leftPad(utils4.numberToHexUnpadded(sm2Curve.CURVE.b), 64);
835
+ const gx = leftPad(utils4.numberToHexUnpadded(sm2Curve.ProjectivePoint.BASE.x), 64);
836
+ const gy = leftPad(utils4.numberToHexUnpadded(sm2Curve.ProjectivePoint.BASE.y), 64);
735
837
  let px;
736
838
  let py;
737
839
  if (publicKey.length === 128) {
@@ -739,17 +841,17 @@ function getHash(hashHex, publicKey, userId = "1234567812345678") {
739
841
  py = publicKey.substring(64, 128);
740
842
  } else {
741
843
  const point = sm2Curve.ProjectivePoint.fromHex(publicKey);
742
- px = leftPad2(utils4.numberToHexUnpadded(point.x), 64);
743
- py = leftPad2(utils4.numberToHexUnpadded(point.y), 64);
844
+ px = leftPad(utils4.numberToHexUnpadded(point.x), 64);
845
+ py = leftPad(utils4.numberToHexUnpadded(point.y), 64);
744
846
  }
745
847
  const data = hexToArray(userId + a + b + gx + gy + px + py);
746
848
  const entl = userId.length * 4;
747
- const z = sm3(concatArray(new Uint8Array([entl >> 8 & 255, entl & 255]), data));
748
- return arrayToHex(Array.from(sm3(concatArray(z, typeof hashHex === "string" ? hexToArray(hashHex) : hashHex))));
849
+ const z = sm3(utils4.concatBytes(new Uint8Array([entl >> 8 & 255, entl & 255]), data));
850
+ return bytesToHex(sm3(utils4.concatBytes(z, typeof hashHex === "string" ? hexToArray(hashHex) : hashHex)));
749
851
  }
750
852
  function getPublicKeyFromPrivateKey(privateKey) {
751
853
  const pubKey = sm2Curve.getPublicKey(privateKey, false);
752
- const pubPad = leftPad2(utils4.bytesToHex(pubKey), 64);
854
+ const pubPad = leftPad(utils4.bytesToHex(pubKey), 64);
753
855
  return pubPad;
754
856
  }
755
857
  function getPoint() {
@@ -763,6 +865,48 @@ function getPoint() {
763
865
  };
764
866
  }
765
867
 
868
+ // src/sm3/index.ts
869
+ function utf8ToArray(str) {
870
+ const arr = [];
871
+ for (let i = 0, len = str.length; i < len; i++) {
872
+ const point = str.codePointAt(i);
873
+ if (point <= 127) {
874
+ arr.push(point);
875
+ } else if (point <= 2047) {
876
+ arr.push(192 | point >>> 6);
877
+ arr.push(128 | point & 63);
878
+ } else if (point <= 55295 || point >= 57344 && point <= 65535) {
879
+ arr.push(224 | point >>> 12);
880
+ arr.push(128 | point >>> 6 & 63);
881
+ arr.push(128 | point & 63);
882
+ } else if (point >= 65536 && point <= 1114111) {
883
+ i++;
884
+ arr.push(240 | point >>> 18 & 28);
885
+ arr.push(128 | point >>> 12 & 63);
886
+ arr.push(128 | point >>> 6 & 63);
887
+ arr.push(128 | point & 63);
888
+ } else {
889
+ arr.push(point);
890
+ throw new Error("input is not supported");
891
+ }
892
+ }
893
+ return new Uint8Array(arr);
894
+ }
895
+ function sm32(input, options) {
896
+ input = typeof input === "string" ? utf8ToArray(input) : input;
897
+ if (options) {
898
+ const mode = options.mode || "hmac";
899
+ if (mode !== "hmac")
900
+ throw new Error("invalid mode");
901
+ let key = options.key;
902
+ if (!key)
903
+ throw new Error("invalid key");
904
+ key = typeof key === "string" ? hexToArray(key) : key;
905
+ return bytesToHex(hmac(sm3, key, input));
906
+ }
907
+ return bytesToHex(sm3(input));
908
+ }
909
+
766
910
  // src/sm4/index.ts
767
911
  var sm4_exports = {};
768
912
  __export(sm4_exports, {
@@ -1074,9 +1218,9 @@ function l1(b) {
1074
1218
  function l2(b) {
1075
1219
  return b ^ rotl(b, 13) ^ rotl(b, 23);
1076
1220
  }
1221
+ var x = new Uint32Array(4);
1222
+ var tmp = new Uint32Array(4);
1077
1223
  function sms4Crypt(input, output, roundKey) {
1078
- const x = new Uint32Array(4);
1079
- const tmp = new Uint32Array(4);
1080
1224
  for (let i = 0; i < 4; i++) {
1081
1225
  tmp[0] = input[4 * i] & 255;
1082
1226
  tmp[1] = input[4 * i + 1] & 255;
@@ -1102,8 +1246,6 @@ function sms4Crypt(input, output, roundKey) {
1102
1246
  }
1103
1247
  }
1104
1248
  function sms4KeyExt(key, roundKey, cryptFlag) {
1105
- const x = new Uint32Array(4);
1106
- const tmp = new Uint32Array(4);
1107
1249
  for (let i = 0; i < 4; i++) {
1108
1250
  tmp[0] = key[0 + 4 * i] & 255;
1109
1251
  tmp[1] = key[1 + 4 * i] & 255;
@@ -1133,6 +1275,7 @@ function sms4KeyExt(key, roundKey, cryptFlag) {
1133
1275
  }
1134
1276
  }
1135
1277
  }
1278
+ var blockOutput = new Uint8Array(16);
1136
1279
  function sm4(inArray, key, cryptFlag, options = {}) {
1137
1280
  let {
1138
1281
  padding = "pkcs#7",
@@ -1176,8 +1319,7 @@ function sm4(inArray, key, cryptFlag, options = {}) {
1176
1319
  let restLen = inArray.length;
1177
1320
  let point = 0;
1178
1321
  while (restLen >= BLOCK) {
1179
- const input = inArray.slice(point, point + 16);
1180
- const output2 = new Uint8Array(16);
1322
+ const input = inArray.subarray(point, point + 16);
1181
1323
  if (mode === "cbc") {
1182
1324
  for (let i = 0; i < BLOCK; i++) {
1183
1325
  if (cryptFlag !== DECRYPT) {
@@ -1185,18 +1327,18 @@ function sm4(inArray, key, cryptFlag, options = {}) {
1185
1327
  }
1186
1328
  }
1187
1329
  }
1188
- sms4Crypt(input, output2, roundKey);
1330
+ sms4Crypt(input, blockOutput, roundKey);
1189
1331
  for (let i = 0; i < BLOCK; i++) {
1190
1332
  if (mode === "cbc") {
1191
1333
  if (cryptFlag === DECRYPT) {
1192
- output2[i] ^= lastVector[i];
1334
+ blockOutput[i] ^= lastVector[i];
1193
1335
  }
1194
1336
  }
1195
- outArray[point + i] = output2[i];
1337
+ outArray[point + i] = blockOutput[i];
1196
1338
  }
1197
1339
  if (mode === "cbc") {
1198
1340
  if (cryptFlag !== DECRYPT) {
1199
- lastVector = output2;
1341
+ lastVector = blockOutput;
1200
1342
  } else {
1201
1343
  lastVector = input;
1202
1344
  }
@@ -1215,7 +1357,7 @@ function sm4(inArray, key, cryptFlag, options = {}) {
1215
1357
  }
1216
1358
  if (output !== "array") {
1217
1359
  if (cryptFlag !== DECRYPT) {
1218
- return arrayToHex(Array.from(outArray));
1360
+ return bytesToHex(outArray);
1219
1361
  } else {
1220
1362
  return arrayToUtf8(outArray);
1221
1363
  }
@@ -1235,3 +1377,4 @@ function decrypt(inArray, key, options = {}) {
1235
1377
  sm3,
1236
1378
  sm4
1237
1379
  });
1380
+ /*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */