sm-crypto-v2 1.3.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,11 +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,
41
+ calculateSharedKey: () => calculateSharedKey,
40
42
  comparePublicKeyHex: () => comparePublicKeyHex,
41
43
  compressPublicKeyHex: () => compressPublicKeyHex,
42
- concatArray: () => concatArray,
43
44
  doDecrypt: () => doDecrypt,
44
45
  doEncrypt: () => doEncrypt,
45
46
  doSignature: () => doSignature,
@@ -50,7 +51,7 @@ __export(sm2_exports, {
50
51
  getPublicKeyFromPrivateKey: () => getPublicKeyFromPrivateKey,
51
52
  hexToArray: () => hexToArray,
52
53
  initRNGPool: () => initRNGPool,
53
- leftPad: () => leftPad2,
54
+ leftPad: () => leftPad,
54
55
  utf8ToHex: () => utf8ToHex,
55
56
  verifyPublicKey: () => verifyPublicKey
56
57
  });
@@ -185,181 +186,7 @@ var utils2 = __toESM(require("@noble/curves/abstract/utils"));
185
186
  var import_weierstrass = require("@noble/curves/abstract/weierstrass");
186
187
  var import_modular = require("@noble/curves/abstract/modular");
187
188
 
188
- // src/sm2/sm3.ts
189
- var W = new Uint32Array(68);
190
- var M = new Uint32Array(64);
191
- function rotl(x, n) {
192
- const s = n & 31;
193
- return x << s | x >>> 32 - s;
194
- }
195
- function xor(x, y) {
196
- const result = new Uint8Array(x.length);
197
- for (let i = x.length - 1; i >= 0; i--)
198
- result[i] = (x[i] ^ y[i]) & 255;
199
- return result;
200
- }
201
- function P0(X) {
202
- return X ^ rotl(X, 9) ^ rotl(X, 17);
203
- }
204
- function P1(X) {
205
- return X ^ rotl(X, 15) ^ rotl(X, 23);
206
- }
207
- function sm3(array) {
208
- let len = array.length * 8;
209
- let k = len % 512;
210
- k = k >= 448 ? 512 - k % 448 - 1 : 448 - k - 1;
211
- const kArr = new Array((k - 7) / 8);
212
- const lenArr = new Array(8);
213
- for (let i = 0, len2 = kArr.length; i < len2; i++)
214
- kArr[i] = 0;
215
- for (let i = 0, len2 = lenArr.length; i < len2; i++)
216
- lenArr[i] = 0;
217
- let lenString = len.toString(2);
218
- for (let i = 7; i >= 0; i--) {
219
- if (lenString.length > 8) {
220
- const start = lenString.length - 8;
221
- lenArr[i] = parseInt(lenString.substring(start), 2);
222
- lenString = lenString.substring(0, start);
223
- } else if (lenString.length > 0) {
224
- lenArr[i] = parseInt(lenString, 2);
225
- lenString = "";
226
- }
227
- }
228
- const m = Uint8Array.from([...array, 128, ...kArr, ...lenArr]);
229
- const dataView = new DataView(m.buffer, 0);
230
- const n = m.length / 64;
231
- const V = new Uint32Array([1937774191, 1226093241, 388252375, 3666478592, 2842636476, 372324522, 3817729613, 2969243214]);
232
- for (let i = 0; i < n; i++) {
233
- W.fill(0);
234
- M.fill(0);
235
- const start = 16 * i;
236
- for (let j = 0; j < 16; j++) {
237
- W[j] = dataView.getUint32((start + j) * 4, false);
238
- }
239
- for (let j = 16; j < 68; j++) {
240
- W[j] = P1(W[j - 16] ^ W[j - 9] ^ rotl(W[j - 3], 15)) ^ rotl(W[j - 13], 7) ^ W[j - 6];
241
- }
242
- for (let j = 0; j < 64; j++) {
243
- M[j] = W[j] ^ W[j + 4];
244
- }
245
- const T1 = 2043430169;
246
- const T2 = 2055708042;
247
- let A = V[0];
248
- let B = V[1];
249
- let C = V[2];
250
- let D = V[3];
251
- let E = V[4];
252
- let F = V[5];
253
- let G = V[6];
254
- let H = V[7];
255
- let SS1;
256
- let SS2;
257
- let TT1;
258
- let TT2;
259
- let T;
260
- for (let j = 0; j < 64; j++) {
261
- T = j >= 0 && j <= 15 ? T1 : T2;
262
- SS1 = rotl(rotl(A, 12) + E + rotl(T, j), 7);
263
- SS2 = SS1 ^ rotl(A, 12);
264
- TT1 = (j >= 0 && j <= 15 ? A ^ B ^ C : A & B | A & C | B & C) + D + SS2 + M[j];
265
- TT2 = (j >= 0 && j <= 15 ? E ^ F ^ G : E & F | ~E & G) + H + SS1 + W[j];
266
- D = C;
267
- C = rotl(B, 9);
268
- B = A;
269
- A = TT1;
270
- H = G;
271
- G = rotl(F, 19);
272
- F = E;
273
- E = P0(TT2);
274
- }
275
- V[0] ^= A;
276
- V[1] ^= B;
277
- V[2] ^= C;
278
- V[3] ^= D;
279
- V[4] ^= E;
280
- V[5] ^= F;
281
- V[6] ^= G;
282
- V[7] ^= H;
283
- }
284
- const result = new Uint8Array(V.length * 4);
285
- for (let i = 0, len2 = V.length; i < len2; i++) {
286
- const word = V[i];
287
- result[i * 4] = (word & 4278190080) >>> 24;
288
- result[i * 4 + 1] = (word & 16711680) >>> 16;
289
- result[i * 4 + 2] = (word & 65280) >>> 8;
290
- result[i * 4 + 3] = word & 255;
291
- }
292
- return result;
293
- }
294
- var blockLen = 64;
295
- var iPad = new Uint8Array(blockLen);
296
- var oPad = new Uint8Array(blockLen);
297
- for (let i = 0; i < blockLen; i++) {
298
- iPad[i] = 54;
299
- oPad[i] = 92;
300
- }
301
- function hmac(input, key) {
302
- if (key.length > blockLen)
303
- key = sm3(key);
304
- while (key.length < blockLen) {
305
- const padKey = new Uint8Array(blockLen);
306
- padKey.set(key);
307
- key = padKey;
308
- }
309
- const iPadKey = xor(key, iPad);
310
- const oPadKey = xor(key, oPad);
311
- const hash = sm3(concatArray(iPadKey, input));
312
- return sm3(concatArray(oPadKey, hash));
313
- }
314
-
315
- // src/sm3/index.ts
316
- var sm3_exports = {};
317
- __export(sm3_exports, {
318
- sm3: () => sm32,
319
- utf8ToArray: () => utf8ToArray
320
- });
321
- function utf8ToArray(str) {
322
- const arr = [];
323
- for (let i = 0, len = str.length; i < len; i++) {
324
- const point = str.codePointAt(i);
325
- if (point <= 127) {
326
- arr.push(point);
327
- } else if (point <= 2047) {
328
- arr.push(192 | point >>> 6);
329
- arr.push(128 | point & 63);
330
- } else if (point <= 55295 || point >= 57344 && point <= 65535) {
331
- arr.push(224 | point >>> 12);
332
- arr.push(128 | point >>> 6 & 63);
333
- arr.push(128 | point & 63);
334
- } else if (point >= 65536 && point <= 1114111) {
335
- i++;
336
- arr.push(240 | point >>> 18 & 28);
337
- arr.push(128 | point >>> 12 & 63);
338
- arr.push(128 | point >>> 6 & 63);
339
- arr.push(128 | point & 63);
340
- } else {
341
- arr.push(point);
342
- throw new Error("input is not supported");
343
- }
344
- }
345
- return new Uint8Array(arr);
346
- }
347
- function sm32(input, options) {
348
- input = typeof input === "string" ? utf8ToArray(input) : input;
349
- if (options) {
350
- const mode = options.mode || "hmac";
351
- if (mode !== "hmac")
352
- throw new Error("invalid mode");
353
- let key = options.key;
354
- if (!key)
355
- throw new Error("invalid key");
356
- key = typeof key === "string" ? hexToArray(key) : key;
357
- return arrayToHex(Array.from(hmac(input, key)));
358
- }
359
- return arrayToHex(Array.from(sm3(input)));
360
- }
361
-
362
- // src/sm2/ec.ts
189
+ // src/sm2/rng.ts
363
190
  var DEFAULT_PRNG_POOL_SIZE = 16384;
364
191
  var prngPool = new Uint8Array(0);
365
192
  var _syncCrypto;
@@ -414,13 +241,304 @@ function randomBytes(length = 0) {
414
241
  return result;
415
242
  }
416
243
  }
417
- function createHash() {
418
- const hashC = (msg) => sm3(typeof msg === "string" ? utf8ToArray(msg) : msg);
419
- hashC.outputLen = 256;
420
- hashC.blockLen = 512;
421
- 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();
422
284
  return hashC;
423
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");
424
542
  var sm2Fp = (0, import_modular.Field)(BigInt("115792089210356248756420345214020892766250353991924191454421193933289684991999"));
425
543
  var sm2Curve = (0, import_weierstrass.weierstrass)({
426
544
  a: BigInt("115792089210356248756420345214020892766250353991924191454421193933289684991996"),
@@ -430,18 +548,19 @@ var sm2Curve = (0, import_weierstrass.weierstrass)({
430
548
  n: BigInt("115792089210356248756420345214020892766061623724957744567843809356293439045923"),
431
549
  Gx: BigInt("22963146547237050559479531362550074578802567295341616970375194840604139615431"),
432
550
  Gy: BigInt("85132369209828568825618990617112496413088388631904505083283536607588877201568"),
433
- hash: createHash(),
434
- hmac: (key, ...msgs) => hmac(concatArray(...msgs), key),
551
+ hash: sm3,
552
+ hmac: (key, ...msgs) => hmac(sm3, key, (0, import_utils3.concatBytes)(...msgs)),
435
553
  randomBytes
436
554
  });
555
+ var field = (0, import_modular.Field)(BigInt(sm2Curve.CURVE.n));
437
556
 
438
557
  // src/sm2/utils.ts
439
558
  var import_modular2 = require("@noble/curves/abstract/modular");
440
559
  function generateKeyPairHex(str) {
441
560
  const privateKey = str ? utils2.numberToBytesBE((0, import_modular2.mod)(BigInt(str), ONE) + ONE, 32) : sm2Curve.utils.randomPrivateKey();
442
561
  const publicKey = sm2Curve.getPublicKey(privateKey, false);
443
- const privPad = leftPad2(utils2.bytesToHex(privateKey), 64);
444
- const pubPad = leftPad2(utils2.bytesToHex(publicKey), 64);
562
+ const privPad = leftPad(utils2.bytesToHex(privateKey), 64);
563
+ const pubPad = leftPad(utils2.bytesToHex(publicKey), 64);
445
564
  return { privateKey: privPad, publicKey: pubPad };
446
565
  }
447
566
  function compressPublicKeyHex(s) {
@@ -470,7 +589,7 @@ function utf8ToHex(input) {
470
589
  }
471
590
  return hexChars.join("");
472
591
  }
473
- function leftPad2(input, num) {
592
+ function leftPad(input, num) {
474
593
  if (input.length >= num)
475
594
  return input;
476
595
  return new Array(num - input.length + 1).join("0") + input;
@@ -502,7 +621,7 @@ function arrayToUtf8(arr) {
502
621
  function hexToArray(hexStr) {
503
622
  let hexStrLength = hexStr.length;
504
623
  if (hexStrLength % 2 !== 0) {
505
- hexStr = leftPad2(hexStr, hexStrLength + 1);
624
+ hexStr = leftPad(hexStr, hexStrLength + 1);
506
625
  }
507
626
  hexStrLength = hexStr.length;
508
627
  const wordLength = hexStrLength / 2;
@@ -516,9 +635,9 @@ function verifyPublicKey(publicKey) {
516
635
  const point = sm2Curve.ProjectivePoint.fromHex(publicKey);
517
636
  if (!point)
518
637
  return false;
519
- const x = point.x;
638
+ const x2 = point.x;
520
639
  const y = point.y;
521
- 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);
522
641
  }
523
642
  function comparePublicKeyHex(publicKey1, publicKey2) {
524
643
  const point1 = sm2Curve.ProjectivePoint.fromHex(publicKey1);
@@ -529,57 +648,101 @@ function comparePublicKeyHex(publicKey1, publicKey2) {
529
648
  return false;
530
649
  return point1.equals(point2);
531
650
  }
532
- function concatArray(...arrays) {
533
- let totalLength = arrays.reduce((acc, value) => acc + value.length, 0);
534
- if (!arrays.length)
535
- return new Uint8Array();
536
- let result = new Uint8Array(totalLength);
537
- let length = 0;
538
- for (let array of arrays) {
539
- result.set(array, length);
540
- length += array.length;
651
+
652
+ // src/sm2/index.ts
653
+ var utils4 = __toESM(require("@noble/curves/abstract/utils"));
654
+
655
+ // src/sm2/kx.ts
656
+ var utils3 = __toESM(require("@noble/curves/abstract/utils"));
657
+ var wPow2 = utils3.hexToNumber("80000000000000000000000000000000");
658
+ var wPow2Sub1 = utils3.hexToNumber("7fffffffffffffffffffffffffffffff");
659
+ function hkdf(z, keylen) {
660
+ let msg = new Uint8Array(keylen);
661
+ let ct = 1;
662
+ let offset = 0;
663
+ let t = EmptyArray;
664
+ const ctShift = new Uint8Array(4);
665
+ const nextT = () => {
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));
671
+ ct++;
672
+ offset = 0;
673
+ };
674
+ nextT();
675
+ for (let i = 0, len = msg.length; i < len; i++) {
676
+ if (offset === t.length)
677
+ nextT();
678
+ msg[i] = t[offset++] & 255;
541
679
  }
542
- return result;
680
+ return msg;
681
+ }
682
+ function calculateSharedKey(keypairA, ephemeralKeypairA, publicKeyB, ephemeralPublicKeyB, idA = "1234567812345678", idB = "1234567812345678", sharedKeyLength) {
683
+ const RA = sm2Curve.ProjectivePoint.fromHex(ephemeralKeypairA.publicKey);
684
+ const RB = sm2Curve.ProjectivePoint.fromHex(ephemeralPublicKeyB);
685
+ const PB = sm2Curve.ProjectivePoint.fromHex(publicKeyB);
686
+ const ZA = hexToArray(idA);
687
+ const ZB = hexToArray(idB);
688
+ const rA = utils3.hexToNumber(ephemeralKeypairA.privateKey);
689
+ const dA = utils3.hexToNumber(keypairA.privateKey);
690
+ const x1 = RA.x;
691
+ const x1_ = field.add(wPow2, x1 & wPow2Sub1);
692
+ const tA = field.add(dA, field.mulN(x1_, rA));
693
+ const x2 = RB.x;
694
+ const x2_ = field.add(wPow2, x2 & wPow2Sub1);
695
+ const U = RB.multiply(x2_).add(PB).multiply(tA);
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);
699
+ return KA;
543
700
  }
544
701
 
545
702
  // src/sm2/index.ts
546
- var mod2 = __toESM(require("@noble/curves/abstract/modular"));
547
- var utils3 = __toESM(require("@noble/curves/abstract/utils"));
548
703
  var C1C2C3 = 0;
704
+ var EmptyArray = new Uint8Array();
549
705
  function doEncrypt(msg, publicKey, cipherMode = 1) {
550
706
  const msgArr = typeof msg === "string" ? hexToArray(utf8ToHex(msg)) : Uint8Array.from(msg);
551
707
  const publicKeyPoint = sm2Curve.ProjectivePoint.fromHex(publicKey);
552
708
  const keypair = generateKeyPairHex();
553
- const k = utils3.hexToNumber(keypair.privateKey);
709
+ const k = utils4.hexToNumber(keypair.privateKey);
554
710
  let c1 = keypair.publicKey;
555
711
  if (c1.length > 128)
556
712
  c1 = c1.substring(c1.length - 128);
557
713
  const p = publicKeyPoint.multiply(k);
558
- const x2 = hexToArray(leftPad2(utils3.numberToHexUnpadded(p.x), 64));
559
- const y2 = hexToArray(leftPad2(utils3.numberToHexUnpadded(p.y), 64));
560
- 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) {
561
722
  let ct = 1;
562
723
  let offset = 0;
563
- let t = new Uint8Array();
564
- const z = concatArray(x2, y2);
724
+ let t = EmptyArray;
725
+ const ctShift = new Uint8Array(4);
565
726
  const nextT = () => {
566
- 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));
567
732
  ct++;
568
733
  offset = 0;
569
734
  };
570
735
  nextT();
571
- for (let i = 0, len = msgArr.length; i < len; i++) {
736
+ for (let i = 0, len = msg.length; i < len; i++) {
572
737
  if (offset === t.length)
573
738
  nextT();
574
- msgArr[i] ^= t[offset++] & 255;
739
+ msg[i] ^= t[offset++] & 255;
575
740
  }
576
- const c2 = arrayToHex(Array.from(msgArr));
577
- return cipherMode === C1C2C3 ? c1 + c2 + c3 : c1 + c3 + c2;
578
741
  }
579
742
  function doDecrypt(encryptData, privateKey, cipherMode = 1, {
580
743
  output = "string"
581
744
  } = {}) {
582
- const privateKeyInteger = utils3.hexToNumber(privateKey);
745
+ const privateKeyInteger = utils4.hexToNumber(privateKey);
583
746
  let c3 = encryptData.substring(128, 128 + 64);
584
747
  let c2 = encryptData.substring(128 + 64);
585
748
  if (cipherMode === C1C2C3) {
@@ -589,24 +752,10 @@ function doDecrypt(encryptData, privateKey, cipherMode = 1, {
589
752
  const msg = hexToArray(c2);
590
753
  const c1 = sm2Curve.ProjectivePoint.fromHex("04" + encryptData.substring(0, 128));
591
754
  const p = c1.multiply(privateKeyInteger);
592
- const x2 = hexToArray(leftPad2(utils3.numberToHexUnpadded(p.x), 64));
593
- const y2 = hexToArray(leftPad2(utils3.numberToHexUnpadded(p.y), 64));
594
- let ct = 1;
595
- let offset = 0;
596
- let t = new Uint8Array();
597
- const z = concatArray(x2, y2);
598
- const nextT = () => {
599
- t = sm3(Uint8Array.from([...z, ct >> 24 & 255, ct >> 16 & 255, ct >> 8 & 255, ct & 255]));
600
- ct++;
601
- offset = 0;
602
- };
603
- nextT();
604
- for (let i = 0, len = msg.length; i < len; i++) {
605
- if (offset === t.length)
606
- nextT();
607
- msg[i] ^= t[offset++] & 255;
608
- }
609
- 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))));
610
759
  if (checkC3 === c3.toLowerCase()) {
611
760
  return output === "array" ? msg : arrayToUtf8(msg);
612
761
  } else {
@@ -626,8 +775,8 @@ function doSignature(msg, privateKey, options = {}) {
626
775
  publicKey = publicKey || getPublicKeyFromPrivateKey(privateKey);
627
776
  hashHex = getHash(hashHex, publicKey, userId);
628
777
  }
629
- const dA = utils3.hexToNumber(privateKey);
630
- const e = utils3.hexToNumber(hashHex);
778
+ const dA = utils4.hexToNumber(privateKey);
779
+ const e = utils4.hexToNumber(hashHex);
631
780
  let k = null;
632
781
  let r = null;
633
782
  let s = null;
@@ -640,13 +789,13 @@ function doSignature(msg, privateKey, options = {}) {
640
789
  point = getPoint();
641
790
  }
642
791
  k = point.k;
643
- r = mod2.mod(e + point.x1, sm2Curve.CURVE.n);
792
+ r = field.add(e, point.x1);
644
793
  } while (r === ZERO || r + k === sm2Curve.CURVE.n);
645
- 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)));
646
795
  } while (s === ZERO);
647
796
  if (der)
648
797
  return encodeDer(r, s);
649
- return leftPad2(utils3.numberToHexUnpadded(r), 64) + leftPad2(utils3.numberToHexUnpadded(s), 64);
798
+ return leftPad(utils4.numberToHexUnpadded(r), 64) + leftPad(utils4.numberToHexUnpadded(s), 64);
650
799
  }
651
800
  function doVerifySignature(msg, signHex, publicKey, options = {}) {
652
801
  let hashHex;
@@ -667,24 +816,24 @@ function doVerifySignature(msg, signHex, publicKey, options = {}) {
667
816
  r = decodeDerObj.r;
668
817
  s = decodeDerObj.s;
669
818
  } else {
670
- r = utils3.hexToNumber(signHex.substring(0, 64));
671
- s = utils3.hexToNumber(signHex.substring(64));
819
+ r = utils4.hexToNumber(signHex.substring(0, 64));
820
+ s = utils4.hexToNumber(signHex.substring(64));
672
821
  }
673
822
  const PA = sm2Curve.ProjectivePoint.fromHex(publicKey);
674
- const e = utils3.hexToNumber(hashHex);
675
- const t = mod2.mod(r + s, sm2Curve.CURVE.n);
823
+ const e = utils4.hexToNumber(hashHex);
824
+ const t = field.add(r, s);
676
825
  if (t === ZERO)
677
826
  return false;
678
827
  const x1y1 = sm2Curve.ProjectivePoint.BASE.multiply(s).add(PA.multiply(t));
679
- const R = mod2.mod(e + x1y1.x, sm2Curve.CURVE.n);
828
+ const R = field.add(e, x1y1.x);
680
829
  return r === R;
681
830
  }
682
831
  function getHash(hashHex, publicKey, userId = "1234567812345678") {
683
832
  userId = utf8ToHex(userId);
684
- const a = leftPad2(utils3.numberToHexUnpadded(sm2Curve.CURVE.a), 64);
685
- const b = leftPad2(utils3.numberToHexUnpadded(sm2Curve.CURVE.b), 64);
686
- const gx = leftPad2(utils3.numberToHexUnpadded(sm2Curve.ProjectivePoint.BASE.x), 64);
687
- const gy = leftPad2(utils3.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);
688
837
  let px;
689
838
  let py;
690
839
  if (publicKey.length === 128) {
@@ -692,23 +841,23 @@ function getHash(hashHex, publicKey, userId = "1234567812345678") {
692
841
  py = publicKey.substring(64, 128);
693
842
  } else {
694
843
  const point = sm2Curve.ProjectivePoint.fromHex(publicKey);
695
- px = leftPad2(utils3.numberToHexUnpadded(point.x), 64);
696
- py = leftPad2(utils3.numberToHexUnpadded(point.y), 64);
844
+ px = leftPad(utils4.numberToHexUnpadded(point.x), 64);
845
+ py = leftPad(utils4.numberToHexUnpadded(point.y), 64);
697
846
  }
698
847
  const data = hexToArray(userId + a + b + gx + gy + px + py);
699
848
  const entl = userId.length * 4;
700
- const z = sm3(concatArray(new Uint8Array([entl >> 8 & 255, entl & 255]), data));
701
- 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)));
702
851
  }
703
852
  function getPublicKeyFromPrivateKey(privateKey) {
704
853
  const pubKey = sm2Curve.getPublicKey(privateKey, false);
705
- const pubPad = leftPad2(utils3.bytesToHex(pubKey), 64);
854
+ const pubPad = leftPad(utils4.bytesToHex(pubKey), 64);
706
855
  return pubPad;
707
856
  }
708
857
  function getPoint() {
709
858
  const keypair = generateKeyPairHex();
710
859
  const PA = sm2Curve.ProjectivePoint.fromHex(keypair.publicKey);
711
- const k = utils3.hexToNumber(keypair.privateKey);
860
+ const k = utils4.hexToNumber(keypair.privateKey);
712
861
  return {
713
862
  ...keypair,
714
863
  k,
@@ -716,6 +865,48 @@ function getPoint() {
716
865
  };
717
866
  }
718
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
+
719
910
  // src/sm4/index.ts
720
911
  var sm4_exports = {};
721
912
  __export(sm4_exports, {
@@ -1027,9 +1218,9 @@ function l1(b) {
1027
1218
  function l2(b) {
1028
1219
  return b ^ rotl(b, 13) ^ rotl(b, 23);
1029
1220
  }
1221
+ var x = new Uint32Array(4);
1222
+ var tmp = new Uint32Array(4);
1030
1223
  function sms4Crypt(input, output, roundKey) {
1031
- const x = new Uint32Array(4);
1032
- const tmp = new Uint32Array(4);
1033
1224
  for (let i = 0; i < 4; i++) {
1034
1225
  tmp[0] = input[4 * i] & 255;
1035
1226
  tmp[1] = input[4 * i + 1] & 255;
@@ -1055,8 +1246,6 @@ function sms4Crypt(input, output, roundKey) {
1055
1246
  }
1056
1247
  }
1057
1248
  function sms4KeyExt(key, roundKey, cryptFlag) {
1058
- const x = new Uint32Array(4);
1059
- const tmp = new Uint32Array(4);
1060
1249
  for (let i = 0; i < 4; i++) {
1061
1250
  tmp[0] = key[0 + 4 * i] & 255;
1062
1251
  tmp[1] = key[1 + 4 * i] & 255;
@@ -1086,6 +1275,7 @@ function sms4KeyExt(key, roundKey, cryptFlag) {
1086
1275
  }
1087
1276
  }
1088
1277
  }
1278
+ var blockOutput = new Uint8Array(16);
1089
1279
  function sm4(inArray, key, cryptFlag, options = {}) {
1090
1280
  let {
1091
1281
  padding = "pkcs#7",
@@ -1129,8 +1319,7 @@ function sm4(inArray, key, cryptFlag, options = {}) {
1129
1319
  let restLen = inArray.length;
1130
1320
  let point = 0;
1131
1321
  while (restLen >= BLOCK) {
1132
- const input = inArray.slice(point, point + 16);
1133
- const output2 = new Uint8Array(16);
1322
+ const input = inArray.subarray(point, point + 16);
1134
1323
  if (mode === "cbc") {
1135
1324
  for (let i = 0; i < BLOCK; i++) {
1136
1325
  if (cryptFlag !== DECRYPT) {
@@ -1138,18 +1327,18 @@ function sm4(inArray, key, cryptFlag, options = {}) {
1138
1327
  }
1139
1328
  }
1140
1329
  }
1141
- sms4Crypt(input, output2, roundKey);
1330
+ sms4Crypt(input, blockOutput, roundKey);
1142
1331
  for (let i = 0; i < BLOCK; i++) {
1143
1332
  if (mode === "cbc") {
1144
1333
  if (cryptFlag === DECRYPT) {
1145
- output2[i] ^= lastVector[i];
1334
+ blockOutput[i] ^= lastVector[i];
1146
1335
  }
1147
1336
  }
1148
- outArray[point + i] = output2[i];
1337
+ outArray[point + i] = blockOutput[i];
1149
1338
  }
1150
1339
  if (mode === "cbc") {
1151
1340
  if (cryptFlag !== DECRYPT) {
1152
- lastVector = output2;
1341
+ lastVector = blockOutput;
1153
1342
  } else {
1154
1343
  lastVector = input;
1155
1344
  }
@@ -1168,7 +1357,7 @@ function sm4(inArray, key, cryptFlag, options = {}) {
1168
1357
  }
1169
1358
  if (output !== "array") {
1170
1359
  if (cryptFlag !== DECRYPT) {
1171
- return arrayToHex(Array.from(outArray));
1360
+ return bytesToHex(outArray);
1172
1361
  } else {
1173
1362
  return arrayToUtf8(outArray);
1174
1363
  }
@@ -1188,3 +1377,4 @@ function decrypt(inArray, key, options = {}) {
1188
1377
  sm3,
1189
1378
  sm4
1190
1379
  });
1380
+ /*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */