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.mjs CHANGED
@@ -7,12 +7,12 @@ var __export = (target, all) => {
7
7
  // src/sm2/index.ts
8
8
  var sm2_exports = {};
9
9
  __export(sm2_exports, {
10
+ EmptyArray: () => EmptyArray,
10
11
  arrayToHex: () => arrayToHex,
11
12
  arrayToUtf8: () => arrayToUtf8,
12
13
  calculateSharedKey: () => calculateSharedKey,
13
14
  comparePublicKeyHex: () => comparePublicKeyHex,
14
15
  compressPublicKeyHex: () => compressPublicKeyHex,
15
- concatArray: () => concatArray,
16
16
  doDecrypt: () => doDecrypt,
17
17
  doEncrypt: () => doEncrypt,
18
18
  doSignature: () => doSignature,
@@ -23,7 +23,7 @@ __export(sm2_exports, {
23
23
  getPublicKeyFromPrivateKey: () => getPublicKeyFromPrivateKey,
24
24
  hexToArray: () => hexToArray,
25
25
  initRNGPool: () => initRNGPool,
26
- leftPad: () => leftPad2,
26
+ leftPad: () => leftPad,
27
27
  utf8ToHex: () => utf8ToHex,
28
28
  verifyPublicKey: () => verifyPublicKey
29
29
  });
@@ -158,181 +158,7 @@ import * as utils2 from "@noble/curves/abstract/utils";
158
158
  import { weierstrass } from "@noble/curves/abstract/weierstrass";
159
159
  import { Field } from "@noble/curves/abstract/modular";
160
160
 
161
- // src/sm2/sm3.ts
162
- var W = new Uint32Array(68);
163
- var M = new Uint32Array(64);
164
- function rotl(x, n) {
165
- const s = n & 31;
166
- return x << s | x >>> 32 - s;
167
- }
168
- function xor(x, y) {
169
- const result = new Uint8Array(x.length);
170
- for (let i = x.length - 1; i >= 0; i--)
171
- result[i] = (x[i] ^ y[i]) & 255;
172
- return result;
173
- }
174
- function P0(X) {
175
- return X ^ rotl(X, 9) ^ rotl(X, 17);
176
- }
177
- function P1(X) {
178
- return X ^ rotl(X, 15) ^ rotl(X, 23);
179
- }
180
- function sm3(array) {
181
- let len = array.length * 8;
182
- let k = len % 512;
183
- k = k >= 448 ? 512 - k % 448 - 1 : 448 - k - 1;
184
- const kArr = new Array((k - 7) / 8);
185
- const lenArr = new Array(8);
186
- for (let i = 0, len2 = kArr.length; i < len2; i++)
187
- kArr[i] = 0;
188
- for (let i = 0, len2 = lenArr.length; i < len2; i++)
189
- lenArr[i] = 0;
190
- let lenString = len.toString(2);
191
- for (let i = 7; i >= 0; i--) {
192
- if (lenString.length > 8) {
193
- const start = lenString.length - 8;
194
- lenArr[i] = parseInt(lenString.substring(start), 2);
195
- lenString = lenString.substring(0, start);
196
- } else if (lenString.length > 0) {
197
- lenArr[i] = parseInt(lenString, 2);
198
- lenString = "";
199
- }
200
- }
201
- const m = Uint8Array.from([...array, 128, ...kArr, ...lenArr]);
202
- const dataView = new DataView(m.buffer, 0);
203
- const n = m.length / 64;
204
- const V = new Uint32Array([1937774191, 1226093241, 388252375, 3666478592, 2842636476, 372324522, 3817729613, 2969243214]);
205
- for (let i = 0; i < n; i++) {
206
- W.fill(0);
207
- M.fill(0);
208
- const start = 16 * i;
209
- for (let j = 0; j < 16; j++) {
210
- W[j] = dataView.getUint32((start + j) * 4, false);
211
- }
212
- for (let j = 16; j < 68; j++) {
213
- W[j] = P1(W[j - 16] ^ W[j - 9] ^ rotl(W[j - 3], 15)) ^ rotl(W[j - 13], 7) ^ W[j - 6];
214
- }
215
- for (let j = 0; j < 64; j++) {
216
- M[j] = W[j] ^ W[j + 4];
217
- }
218
- const T1 = 2043430169;
219
- const T2 = 2055708042;
220
- let A = V[0];
221
- let B = V[1];
222
- let C = V[2];
223
- let D = V[3];
224
- let E = V[4];
225
- let F = V[5];
226
- let G = V[6];
227
- let H = V[7];
228
- let SS1;
229
- let SS2;
230
- let TT1;
231
- let TT2;
232
- let T;
233
- for (let j = 0; j < 64; j++) {
234
- T = j >= 0 && j <= 15 ? T1 : T2;
235
- SS1 = rotl(rotl(A, 12) + E + rotl(T, j), 7);
236
- SS2 = SS1 ^ rotl(A, 12);
237
- TT1 = (j >= 0 && j <= 15 ? A ^ B ^ C : A & B | A & C | B & C) + D + SS2 + M[j];
238
- TT2 = (j >= 0 && j <= 15 ? E ^ F ^ G : E & F | ~E & G) + H + SS1 + W[j];
239
- D = C;
240
- C = rotl(B, 9);
241
- B = A;
242
- A = TT1;
243
- H = G;
244
- G = rotl(F, 19);
245
- F = E;
246
- E = P0(TT2);
247
- }
248
- V[0] ^= A;
249
- V[1] ^= B;
250
- V[2] ^= C;
251
- V[3] ^= D;
252
- V[4] ^= E;
253
- V[5] ^= F;
254
- V[6] ^= G;
255
- V[7] ^= H;
256
- }
257
- const result = new Uint8Array(V.length * 4);
258
- for (let i = 0, len2 = V.length; i < len2; i++) {
259
- const word = V[i];
260
- result[i * 4] = (word & 4278190080) >>> 24;
261
- result[i * 4 + 1] = (word & 16711680) >>> 16;
262
- result[i * 4 + 2] = (word & 65280) >>> 8;
263
- result[i * 4 + 3] = word & 255;
264
- }
265
- return result;
266
- }
267
- var blockLen = 64;
268
- var iPad = new Uint8Array(blockLen);
269
- var oPad = new Uint8Array(blockLen);
270
- for (let i = 0; i < blockLen; i++) {
271
- iPad[i] = 54;
272
- oPad[i] = 92;
273
- }
274
- function hmac(input, key) {
275
- if (key.length > blockLen)
276
- key = sm3(key);
277
- while (key.length < blockLen) {
278
- const padKey = new Uint8Array(blockLen);
279
- padKey.set(key);
280
- key = padKey;
281
- }
282
- const iPadKey = xor(key, iPad);
283
- const oPadKey = xor(key, oPad);
284
- const hash = sm3(concatArray(iPadKey, input));
285
- return sm3(concatArray(oPadKey, hash));
286
- }
287
-
288
- // src/sm3/index.ts
289
- var sm3_exports = {};
290
- __export(sm3_exports, {
291
- sm3: () => sm32,
292
- utf8ToArray: () => utf8ToArray
293
- });
294
- function utf8ToArray(str) {
295
- const arr = [];
296
- for (let i = 0, len = str.length; i < len; i++) {
297
- const point = str.codePointAt(i);
298
- if (point <= 127) {
299
- arr.push(point);
300
- } else if (point <= 2047) {
301
- arr.push(192 | point >>> 6);
302
- arr.push(128 | point & 63);
303
- } else if (point <= 55295 || point >= 57344 && point <= 65535) {
304
- arr.push(224 | point >>> 12);
305
- arr.push(128 | point >>> 6 & 63);
306
- arr.push(128 | point & 63);
307
- } else if (point >= 65536 && point <= 1114111) {
308
- i++;
309
- arr.push(240 | point >>> 18 & 28);
310
- arr.push(128 | point >>> 12 & 63);
311
- arr.push(128 | point >>> 6 & 63);
312
- arr.push(128 | point & 63);
313
- } else {
314
- arr.push(point);
315
- throw new Error("input is not supported");
316
- }
317
- }
318
- return new Uint8Array(arr);
319
- }
320
- function sm32(input, options) {
321
- input = typeof input === "string" ? utf8ToArray(input) : input;
322
- if (options) {
323
- const mode = options.mode || "hmac";
324
- if (mode !== "hmac")
325
- throw new Error("invalid mode");
326
- let key = options.key;
327
- if (!key)
328
- throw new Error("invalid key");
329
- key = typeof key === "string" ? hexToArray(key) : key;
330
- return arrayToHex(Array.from(hmac(input, key)));
331
- }
332
- return arrayToHex(Array.from(sm3(input)));
333
- }
334
-
335
- // src/sm2/ec.ts
161
+ // src/sm2/rng.ts
336
162
  var DEFAULT_PRNG_POOL_SIZE = 16384;
337
163
  var prngPool = new Uint8Array(0);
338
164
  var _syncCrypto;
@@ -387,13 +213,304 @@ function randomBytes(length = 0) {
387
213
  return result;
388
214
  }
389
215
  }
390
- function createHash() {
391
- const hashC = (msg) => sm3(typeof msg === "string" ? utf8ToArray(msg) : msg);
392
- hashC.outputLen = 256;
393
- hashC.blockLen = 512;
394
- hashC.create = () => sm3(Uint8Array.from([]));
216
+
217
+ // src/sm3/utils.ts
218
+ var u8a = (a) => a instanceof Uint8Array;
219
+ var createView = (arr) => new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
220
+ var isLE = new Uint8Array(new Uint32Array([287454020]).buffer)[0] === 68;
221
+ if (!isLE)
222
+ throw new Error("Non little-endian hardware is not supported");
223
+ var hexes = Array.from({ length: 256 }, (v, i) => i.toString(16).padStart(2, "0"));
224
+ function bytesToHex(bytes) {
225
+ if (!u8a(bytes))
226
+ throw new Error("Uint8Array expected");
227
+ let hex = "";
228
+ for (let i = 0; i < bytes.length; i++) {
229
+ hex += hexes[bytes[i]];
230
+ }
231
+ return hex;
232
+ }
233
+ function utf8ToBytes(str) {
234
+ if (typeof str !== "string")
235
+ throw new Error(`utf8ToBytes expected string, got ${typeof str}`);
236
+ return new Uint8Array(new TextEncoder().encode(str));
237
+ }
238
+ function toBytes(data) {
239
+ if (typeof data === "string")
240
+ data = utf8ToBytes(data);
241
+ if (!u8a(data))
242
+ throw new Error(`expected Uint8Array, got ${typeof data}`);
243
+ return data;
244
+ }
245
+ var Hash = class {
246
+ clone() {
247
+ return this._cloneInto();
248
+ }
249
+ };
250
+ function wrapConstructor(hashCons) {
251
+ const hashC = (msg) => hashCons().update(toBytes(msg)).digest();
252
+ const tmp2 = hashCons();
253
+ hashC.outputLen = tmp2.outputLen;
254
+ hashC.blockLen = tmp2.blockLen;
255
+ hashC.create = () => hashCons();
395
256
  return hashC;
396
257
  }
258
+
259
+ // src/sm2/sm3.ts
260
+ var BoolA = (A, B, C) => A & B | A & C | B & C;
261
+ var BoolB = (A, B, C) => A ^ B ^ C;
262
+ var BoolC = (A, B, C) => A & B | ~A & C;
263
+ function setBigUint64(view, byteOffset, value, isLE2) {
264
+ if (typeof view.setBigUint64 === "function")
265
+ return view.setBigUint64(byteOffset, value, isLE2);
266
+ const _32n = BigInt(32);
267
+ const _u32_max = BigInt(4294967295);
268
+ const wh = Number(value >> _32n & _u32_max);
269
+ const wl = Number(value & _u32_max);
270
+ const h = isLE2 ? 4 : 0;
271
+ const l = isLE2 ? 0 : 4;
272
+ view.setUint32(byteOffset + h, wh, isLE2);
273
+ view.setUint32(byteOffset + l, wl, isLE2);
274
+ }
275
+ function rotl(x2, n) {
276
+ const s = n & 31;
277
+ return x2 << s | x2 >>> 32 - s;
278
+ }
279
+ function P0(X) {
280
+ return X ^ rotl(X, 9) ^ rotl(X, 17);
281
+ }
282
+ function P1(X) {
283
+ return X ^ rotl(X, 15) ^ rotl(X, 23);
284
+ }
285
+ var SHA2 = class extends Hash {
286
+ constructor(blockLen, outputLen, padOffset, isLE2) {
287
+ super();
288
+ this.blockLen = blockLen;
289
+ this.outputLen = outputLen;
290
+ this.padOffset = padOffset;
291
+ this.isLE = isLE2;
292
+ this.buffer = new Uint8Array(blockLen);
293
+ this.view = createView(this.buffer);
294
+ }
295
+ buffer;
296
+ view;
297
+ finished = false;
298
+ length = 0;
299
+ pos = 0;
300
+ destroyed = false;
301
+ update(data) {
302
+ const { view, buffer, blockLen } = this;
303
+ data = toBytes(data);
304
+ const len = data.length;
305
+ for (let pos = 0; pos < len; ) {
306
+ const take = Math.min(blockLen - this.pos, len - pos);
307
+ if (take === blockLen) {
308
+ const dataView = createView(data);
309
+ for (; blockLen <= len - pos; pos += blockLen)
310
+ this.process(dataView, pos);
311
+ continue;
312
+ }
313
+ buffer.set(data.subarray(pos, pos + take), this.pos);
314
+ this.pos += take;
315
+ pos += take;
316
+ if (this.pos === blockLen) {
317
+ this.process(view, 0);
318
+ this.pos = 0;
319
+ }
320
+ }
321
+ this.length += data.length;
322
+ this.roundClean();
323
+ return this;
324
+ }
325
+ digestInto(out) {
326
+ this.finished = true;
327
+ const { buffer, view, blockLen, isLE: isLE2 } = this;
328
+ let { pos } = this;
329
+ buffer[pos++] = 128;
330
+ this.buffer.subarray(pos).fill(0);
331
+ if (this.padOffset > blockLen - pos) {
332
+ this.process(view, 0);
333
+ pos = 0;
334
+ }
335
+ for (let i = pos; i < blockLen; i++)
336
+ buffer[i] = 0;
337
+ setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE2);
338
+ this.process(view, 0);
339
+ const oview = createView(out);
340
+ const len = this.outputLen;
341
+ if (len % 4)
342
+ throw new Error("_sha2: outputLen should be aligned to 32bit");
343
+ const outLen = len / 4;
344
+ const state = this.get();
345
+ if (outLen > state.length)
346
+ throw new Error("_sha2: outputLen bigger than state");
347
+ for (let i = 0; i < outLen; i++)
348
+ oview.setUint32(4 * i, state[i], isLE2);
349
+ }
350
+ digest() {
351
+ const { buffer, outputLen } = this;
352
+ this.digestInto(buffer);
353
+ const res = buffer.slice(0, outputLen);
354
+ this.destroy();
355
+ return res;
356
+ }
357
+ _cloneInto(to) {
358
+ to ||= new this.constructor();
359
+ to.set(...this.get());
360
+ const { blockLen, buffer, length, finished, destroyed, pos } = this;
361
+ to.length = length;
362
+ to.pos = pos;
363
+ to.finished = finished;
364
+ to.destroyed = destroyed;
365
+ if (length % blockLen)
366
+ to.buffer.set(buffer);
367
+ return to;
368
+ }
369
+ };
370
+ var IV = new Uint32Array([1937774191, 1226093241, 388252375, 3666478592, 2842636476, 372324522, 3817729613, 2969243214]);
371
+ var SM3_W = new Uint32Array(68);
372
+ var SM3_M = new Uint32Array(64);
373
+ var T1 = 2043430169;
374
+ var T2 = 2055708042;
375
+ var SM3 = class extends SHA2 {
376
+ A = IV[0] | 0;
377
+ B = IV[1] | 0;
378
+ C = IV[2] | 0;
379
+ D = IV[3] | 0;
380
+ E = IV[4] | 0;
381
+ F = IV[5] | 0;
382
+ G = IV[6] | 0;
383
+ H = IV[7] | 0;
384
+ constructor() {
385
+ super(64, 32, 8, false);
386
+ }
387
+ get() {
388
+ const { A, B, C, D, E, F, G, H } = this;
389
+ return [A, B, C, D, E, F, G, H];
390
+ }
391
+ set(A, B, C, D, E, F, G, H) {
392
+ this.A = A | 0;
393
+ this.B = B | 0;
394
+ this.C = C | 0;
395
+ this.D = D | 0;
396
+ this.E = E | 0;
397
+ this.F = F | 0;
398
+ this.G = G | 0;
399
+ this.H = H | 0;
400
+ }
401
+ process(view, offset) {
402
+ for (let i = 0; i < 16; i++, offset += 4)
403
+ SM3_W[i] = view.getUint32(offset, false);
404
+ for (let i = 16; i < 68; i++) {
405
+ 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];
406
+ }
407
+ for (let i = 0; i < 64; i++) {
408
+ SM3_M[i] = SM3_W[i] ^ SM3_W[i + 4];
409
+ }
410
+ let { A, B, C, D, E, F, G, H } = this;
411
+ for (let j = 0; j < 64; j++) {
412
+ let small = j >= 0 && j <= 15;
413
+ let T = small ? T1 : T2;
414
+ let SS1 = rotl(rotl(A, 12) + E + rotl(T, j), 7);
415
+ let SS2 = SS1 ^ rotl(A, 12);
416
+ let TT1 = (small ? BoolB(A, B, C) : BoolA(A, B, C)) + D + SS2 + SM3_M[j] | 0;
417
+ let TT2 = (small ? BoolB(E, F, G) : BoolC(E, F, G)) + H + SS1 + SM3_W[j] | 0;
418
+ D = C;
419
+ C = rotl(B, 9);
420
+ B = A;
421
+ A = TT1;
422
+ H = G;
423
+ G = rotl(F, 19);
424
+ F = E;
425
+ E = P0(TT2);
426
+ }
427
+ A = A ^ this.A | 0;
428
+ B = B ^ this.B | 0;
429
+ C = C ^ this.C | 0;
430
+ D = D ^ this.D | 0;
431
+ E = E ^ this.E | 0;
432
+ F = F ^ this.F | 0;
433
+ G = G ^ this.G | 0;
434
+ H = H ^ this.H | 0;
435
+ this.set(A, B, C, D, E, F, G, H);
436
+ }
437
+ roundClean() {
438
+ SM3_W.fill(0);
439
+ }
440
+ destroy() {
441
+ this.set(0, 0, 0, 0, 0, 0, 0, 0);
442
+ this.buffer.fill(0);
443
+ }
444
+ };
445
+ var sm3 = wrapConstructor(() => new SM3());
446
+
447
+ // src/sm2/hmac.ts
448
+ var HMAC = class extends Hash {
449
+ oHash;
450
+ iHash;
451
+ blockLen;
452
+ outputLen;
453
+ finished = false;
454
+ destroyed = false;
455
+ constructor(hash, _key) {
456
+ super();
457
+ const key = toBytes(_key);
458
+ this.iHash = hash.create();
459
+ if (typeof this.iHash.update !== "function")
460
+ throw new Error("Expected instance of class which extends utils.Hash");
461
+ this.blockLen = this.iHash.blockLen;
462
+ this.outputLen = this.iHash.outputLen;
463
+ const blockLen = this.blockLen;
464
+ const pad = new Uint8Array(blockLen);
465
+ pad.set(key.length > blockLen ? hash.create().update(key).digest() : key);
466
+ for (let i = 0; i < pad.length; i++)
467
+ pad[i] ^= 54;
468
+ this.iHash.update(pad);
469
+ this.oHash = hash.create();
470
+ for (let i = 0; i < pad.length; i++)
471
+ pad[i] ^= 54 ^ 92;
472
+ this.oHash.update(pad);
473
+ pad.fill(0);
474
+ }
475
+ update(buf) {
476
+ this.iHash.update(buf);
477
+ return this;
478
+ }
479
+ digestInto(out) {
480
+ this.finished = true;
481
+ this.iHash.digestInto(out);
482
+ this.oHash.update(out);
483
+ this.oHash.digestInto(out);
484
+ this.destroy();
485
+ }
486
+ digest() {
487
+ const out = new Uint8Array(this.oHash.outputLen);
488
+ this.digestInto(out);
489
+ return out;
490
+ }
491
+ _cloneInto(to) {
492
+ to ||= Object.create(Object.getPrototypeOf(this), {});
493
+ const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this;
494
+ to = to;
495
+ to.finished = finished;
496
+ to.destroyed = destroyed;
497
+ to.blockLen = blockLen;
498
+ to.outputLen = outputLen;
499
+ to.oHash = oHash._cloneInto(to.oHash);
500
+ to.iHash = iHash._cloneInto(to.iHash);
501
+ return to;
502
+ }
503
+ destroy() {
504
+ this.destroyed = true;
505
+ this.oHash.destroy();
506
+ this.iHash.destroy();
507
+ }
508
+ };
509
+ var hmac = (hash, key, message) => new HMAC(hash, key).update(message).digest();
510
+ hmac.create = (hash, key) => new HMAC(hash, key);
511
+
512
+ // src/sm2/ec.ts
513
+ import { concatBytes } from "@noble/curves/abstract/utils";
397
514
  var sm2Fp = Field(BigInt("115792089210356248756420345214020892766250353991924191454421193933289684991999"));
398
515
  var sm2Curve = weierstrass({
399
516
  a: BigInt("115792089210356248756420345214020892766250353991924191454421193933289684991996"),
@@ -403,18 +520,19 @@ var sm2Curve = weierstrass({
403
520
  n: BigInt("115792089210356248756420345214020892766061623724957744567843809356293439045923"),
404
521
  Gx: BigInt("22963146547237050559479531362550074578802567295341616970375194840604139615431"),
405
522
  Gy: BigInt("85132369209828568825618990617112496413088388631904505083283536607588877201568"),
406
- hash: createHash(),
407
- hmac: (key, ...msgs) => hmac(concatArray(...msgs), key),
523
+ hash: sm3,
524
+ hmac: (key, ...msgs) => hmac(sm3, key, concatBytes(...msgs)),
408
525
  randomBytes
409
526
  });
527
+ var field = Field(BigInt(sm2Curve.CURVE.n));
410
528
 
411
529
  // src/sm2/utils.ts
412
530
  import { mod } from "@noble/curves/abstract/modular";
413
531
  function generateKeyPairHex(str) {
414
532
  const privateKey = str ? utils2.numberToBytesBE(mod(BigInt(str), ONE) + ONE, 32) : sm2Curve.utils.randomPrivateKey();
415
533
  const publicKey = sm2Curve.getPublicKey(privateKey, false);
416
- const privPad = leftPad2(utils2.bytesToHex(privateKey), 64);
417
- const pubPad = leftPad2(utils2.bytesToHex(publicKey), 64);
534
+ const privPad = leftPad(utils2.bytesToHex(privateKey), 64);
535
+ const pubPad = leftPad(utils2.bytesToHex(publicKey), 64);
418
536
  return { privateKey: privPad, publicKey: pubPad };
419
537
  }
420
538
  function compressPublicKeyHex(s) {
@@ -443,7 +561,7 @@ function utf8ToHex(input) {
443
561
  }
444
562
  return hexChars.join("");
445
563
  }
446
- function leftPad2(input, num) {
564
+ function leftPad(input, num) {
447
565
  if (input.length >= num)
448
566
  return input;
449
567
  return new Array(num - input.length + 1).join("0") + input;
@@ -475,7 +593,7 @@ function arrayToUtf8(arr) {
475
593
  function hexToArray(hexStr) {
476
594
  let hexStrLength = hexStr.length;
477
595
  if (hexStrLength % 2 !== 0) {
478
- hexStr = leftPad2(hexStr, hexStrLength + 1);
596
+ hexStr = leftPad(hexStr, hexStrLength + 1);
479
597
  }
480
598
  hexStrLength = hexStr.length;
481
599
  const wordLength = hexStrLength / 2;
@@ -489,9 +607,9 @@ function verifyPublicKey(publicKey) {
489
607
  const point = sm2Curve.ProjectivePoint.fromHex(publicKey);
490
608
  if (!point)
491
609
  return false;
492
- const x = point.x;
610
+ const x2 = point.x;
493
611
  const y = point.y;
494
- return sm2Fp.sqr(y) === sm2Fp.add(sm2Fp.add(sm2Fp.mul(x, sm2Fp.sqr(x)), sm2Fp.mul(x, sm2Curve.CURVE.a)), sm2Curve.CURVE.b);
612
+ return sm2Fp.sqr(y) === sm2Fp.add(sm2Fp.addN(sm2Fp.mulN(x2, sm2Fp.sqrN(x2)), sm2Fp.mulN(x2, sm2Curve.CURVE.a)), sm2Curve.CURVE.b);
495
613
  }
496
614
  function comparePublicKeyHex(publicKey1, publicKey2) {
497
615
  const point1 = sm2Curve.ProjectivePoint.fromHex(publicKey1);
@@ -502,36 +620,26 @@ function comparePublicKeyHex(publicKey1, publicKey2) {
502
620
  return false;
503
621
  return point1.equals(point2);
504
622
  }
505
- function concatArray(...arrays) {
506
- let totalLength = arrays.reduce((acc, value) => acc + value.length, 0);
507
- if (!arrays.length)
508
- return new Uint8Array();
509
- let result = new Uint8Array(totalLength);
510
- let length = 0;
511
- for (let array of arrays) {
512
- result.set(array, length);
513
- length += array.length;
514
- }
515
- return result;
516
- }
517
623
 
518
624
  // src/sm2/index.ts
519
- import * as mod2 from "@noble/curves/abstract/modular";
520
625
  import * as utils4 from "@noble/curves/abstract/utils";
521
626
 
522
627
  // src/sm2/kx.ts
523
628
  import * as utils3 from "@noble/curves/abstract/utils";
524
- import { Field as Field2 } from "@noble/curves/abstract/modular";
525
- var field = Field2(BigInt(sm2Curve.CURVE.n));
526
629
  var wPow2 = utils3.hexToNumber("80000000000000000000000000000000");
527
630
  var wPow2Sub1 = utils3.hexToNumber("7fffffffffffffffffffffffffffffff");
528
631
  function hkdf(z, keylen) {
529
- let t = new Uint8Array();
530
632
  let msg = new Uint8Array(keylen);
531
633
  let ct = 1;
532
634
  let offset = 0;
635
+ let t = EmptyArray;
636
+ const ctShift = new Uint8Array(4);
533
637
  const nextT = () => {
534
- t = sm3(Uint8Array.from([...z, ct >> 24 & 255, ct >> 16 & 255, ct >> 8 & 255, ct & 255]));
638
+ ctShift[0] = ct >> 24 & 255;
639
+ ctShift[1] = ct >> 16 & 255;
640
+ ctShift[2] = ct >> 8 & 255;
641
+ ctShift[3] = ct & 255;
642
+ t = sm3(utils3.concatBytes(z, ctShift));
535
643
  ct++;
536
644
  offset = 0;
537
645
  };
@@ -553,18 +661,19 @@ function calculateSharedKey(keypairA, ephemeralKeypairA, publicKeyB, ephemeralPu
553
661
  const dA = utils3.hexToNumber(keypairA.privateKey);
554
662
  const x1 = RA.x;
555
663
  const x1_ = field.add(wPow2, x1 & wPow2Sub1);
556
- const tA = field.add(dA, field.mul(x1_, rA));
664
+ const tA = field.add(dA, field.mulN(x1_, rA));
557
665
  const x2 = RB.x;
558
666
  const x2_ = field.add(wPow2, x2 & wPow2Sub1);
559
667
  const U = RB.multiply(x2_).add(PB).multiply(tA);
560
- const xU = hexToArray(leftPad2(utils3.numberToHexUnpadded(U.x), 64));
561
- const yU = hexToArray(leftPad2(utils3.numberToHexUnpadded(U.y), 64));
562
- const KA = hkdf(concatArray(xU, yU, ZA, ZB), sharedKeyLength);
668
+ const xU = hexToArray(leftPad(utils3.numberToHexUnpadded(U.x), 64));
669
+ const yU = hexToArray(leftPad(utils3.numberToHexUnpadded(U.y), 64));
670
+ const KA = hkdf(utils3.concatBytes(xU, yU, ZA, ZB), sharedKeyLength);
563
671
  return KA;
564
672
  }
565
673
 
566
674
  // src/sm2/index.ts
567
675
  var C1C2C3 = 0;
676
+ var EmptyArray = new Uint8Array();
568
677
  function doEncrypt(msg, publicKey, cipherMode = 1) {
569
678
  const msgArr = typeof msg === "string" ? hexToArray(utf8ToHex(msg)) : Uint8Array.from(msg);
570
679
  const publicKeyPoint = sm2Curve.ProjectivePoint.fromHex(publicKey);
@@ -574,26 +683,33 @@ function doEncrypt(msg, publicKey, cipherMode = 1) {
574
683
  if (c1.length > 128)
575
684
  c1 = c1.substring(c1.length - 128);
576
685
  const p = publicKeyPoint.multiply(k);
577
- const x2 = hexToArray(leftPad2(utils4.numberToHexUnpadded(p.x), 64));
578
- const y2 = hexToArray(leftPad2(utils4.numberToHexUnpadded(p.y), 64));
579
- const c3 = arrayToHex(Array.from(sm3(concatArray(x2, msgArr, y2))));
686
+ const x2 = hexToArray(leftPad(utils4.numberToHexUnpadded(p.x), 64));
687
+ const y2 = hexToArray(leftPad(utils4.numberToHexUnpadded(p.y), 64));
688
+ const c3 = bytesToHex(sm3(utils4.concatBytes(x2, msgArr, y2)));
689
+ xorCipherStream(x2, y2, msgArr);
690
+ const c2 = bytesToHex(msgArr);
691
+ return cipherMode === C1C2C3 ? c1 + c2 + c3 : c1 + c3 + c2;
692
+ }
693
+ function xorCipherStream(x2, y2, msg) {
580
694
  let ct = 1;
581
695
  let offset = 0;
582
- let t = new Uint8Array();
583
- const z = concatArray(x2, y2);
696
+ let t = EmptyArray;
697
+ const ctShift = new Uint8Array(4);
584
698
  const nextT = () => {
585
- t = sm3(Uint8Array.from([...z, ct >> 24 & 255, ct >> 16 & 255, ct >> 8 & 255, ct & 255]));
699
+ ctShift[0] = ct >> 24 & 255;
700
+ ctShift[1] = ct >> 16 & 255;
701
+ ctShift[2] = ct >> 8 & 255;
702
+ ctShift[3] = ct & 255;
703
+ t = sm3(utils4.concatBytes(x2, y2, ctShift));
586
704
  ct++;
587
705
  offset = 0;
588
706
  };
589
707
  nextT();
590
- for (let i = 0, len = msgArr.length; i < len; i++) {
708
+ for (let i = 0, len = msg.length; i < len; i++) {
591
709
  if (offset === t.length)
592
710
  nextT();
593
- msgArr[i] ^= t[offset++] & 255;
711
+ msg[i] ^= t[offset++] & 255;
594
712
  }
595
- const c2 = arrayToHex(Array.from(msgArr));
596
- return cipherMode === C1C2C3 ? c1 + c2 + c3 : c1 + c3 + c2;
597
713
  }
598
714
  function doDecrypt(encryptData, privateKey, cipherMode = 1, {
599
715
  output = "string"
@@ -608,24 +724,10 @@ function doDecrypt(encryptData, privateKey, cipherMode = 1, {
608
724
  const msg = hexToArray(c2);
609
725
  const c1 = sm2Curve.ProjectivePoint.fromHex("04" + encryptData.substring(0, 128));
610
726
  const p = c1.multiply(privateKeyInteger);
611
- const x2 = hexToArray(leftPad2(utils4.numberToHexUnpadded(p.x), 64));
612
- const y2 = hexToArray(leftPad2(utils4.numberToHexUnpadded(p.y), 64));
613
- let ct = 1;
614
- let offset = 0;
615
- let t = new Uint8Array();
616
- const z = concatArray(x2, y2);
617
- const nextT = () => {
618
- t = sm3(Uint8Array.from([...z, ct >> 24 & 255, ct >> 16 & 255, ct >> 8 & 255, ct & 255]));
619
- ct++;
620
- offset = 0;
621
- };
622
- nextT();
623
- for (let i = 0, len = msg.length; i < len; i++) {
624
- if (offset === t.length)
625
- nextT();
626
- msg[i] ^= t[offset++] & 255;
627
- }
628
- const checkC3 = arrayToHex(Array.from(sm3(concatArray(x2, msg, y2))));
727
+ const x2 = hexToArray(leftPad(utils4.numberToHexUnpadded(p.x), 64));
728
+ const y2 = hexToArray(leftPad(utils4.numberToHexUnpadded(p.y), 64));
729
+ xorCipherStream(x2, y2, msg);
730
+ const checkC3 = arrayToHex(Array.from(sm3(utils4.concatBytes(x2, msg, y2))));
629
731
  if (checkC3 === c3.toLowerCase()) {
630
732
  return output === "array" ? msg : arrayToUtf8(msg);
631
733
  } else {
@@ -659,13 +761,13 @@ function doSignature(msg, privateKey, options = {}) {
659
761
  point = getPoint();
660
762
  }
661
763
  k = point.k;
662
- r = mod2.mod(e + point.x1, sm2Curve.CURVE.n);
764
+ r = field.add(e, point.x1);
663
765
  } while (r === ZERO || r + k === sm2Curve.CURVE.n);
664
- s = mod2.mod(mod2.invert(dA + ONE, sm2Curve.CURVE.n) * (k - r * dA), sm2Curve.CURVE.n);
766
+ s = field.mul(field.inv(field.addN(dA, ONE)), field.subN(k, field.mulN(r, dA)));
665
767
  } while (s === ZERO);
666
768
  if (der)
667
769
  return encodeDer(r, s);
668
- return leftPad2(utils4.numberToHexUnpadded(r), 64) + leftPad2(utils4.numberToHexUnpadded(s), 64);
770
+ return leftPad(utils4.numberToHexUnpadded(r), 64) + leftPad(utils4.numberToHexUnpadded(s), 64);
669
771
  }
670
772
  function doVerifySignature(msg, signHex, publicKey, options = {}) {
671
773
  let hashHex;
@@ -691,19 +793,19 @@ function doVerifySignature(msg, signHex, publicKey, options = {}) {
691
793
  }
692
794
  const PA = sm2Curve.ProjectivePoint.fromHex(publicKey);
693
795
  const e = utils4.hexToNumber(hashHex);
694
- const t = mod2.mod(r + s, sm2Curve.CURVE.n);
796
+ const t = field.add(r, s);
695
797
  if (t === ZERO)
696
798
  return false;
697
799
  const x1y1 = sm2Curve.ProjectivePoint.BASE.multiply(s).add(PA.multiply(t));
698
- const R = mod2.mod(e + x1y1.x, sm2Curve.CURVE.n);
800
+ const R = field.add(e, x1y1.x);
699
801
  return r === R;
700
802
  }
701
803
  function getHash(hashHex, publicKey, userId = "1234567812345678") {
702
804
  userId = utf8ToHex(userId);
703
- const a = leftPad2(utils4.numberToHexUnpadded(sm2Curve.CURVE.a), 64);
704
- const b = leftPad2(utils4.numberToHexUnpadded(sm2Curve.CURVE.b), 64);
705
- const gx = leftPad2(utils4.numberToHexUnpadded(sm2Curve.ProjectivePoint.BASE.x), 64);
706
- const gy = leftPad2(utils4.numberToHexUnpadded(sm2Curve.ProjectivePoint.BASE.y), 64);
805
+ const a = leftPad(utils4.numberToHexUnpadded(sm2Curve.CURVE.a), 64);
806
+ const b = leftPad(utils4.numberToHexUnpadded(sm2Curve.CURVE.b), 64);
807
+ const gx = leftPad(utils4.numberToHexUnpadded(sm2Curve.ProjectivePoint.BASE.x), 64);
808
+ const gy = leftPad(utils4.numberToHexUnpadded(sm2Curve.ProjectivePoint.BASE.y), 64);
707
809
  let px;
708
810
  let py;
709
811
  if (publicKey.length === 128) {
@@ -711,17 +813,17 @@ function getHash(hashHex, publicKey, userId = "1234567812345678") {
711
813
  py = publicKey.substring(64, 128);
712
814
  } else {
713
815
  const point = sm2Curve.ProjectivePoint.fromHex(publicKey);
714
- px = leftPad2(utils4.numberToHexUnpadded(point.x), 64);
715
- py = leftPad2(utils4.numberToHexUnpadded(point.y), 64);
816
+ px = leftPad(utils4.numberToHexUnpadded(point.x), 64);
817
+ py = leftPad(utils4.numberToHexUnpadded(point.y), 64);
716
818
  }
717
819
  const data = hexToArray(userId + a + b + gx + gy + px + py);
718
820
  const entl = userId.length * 4;
719
- const z = sm3(concatArray(new Uint8Array([entl >> 8 & 255, entl & 255]), data));
720
- return arrayToHex(Array.from(sm3(concatArray(z, typeof hashHex === "string" ? hexToArray(hashHex) : hashHex))));
821
+ const z = sm3(utils4.concatBytes(new Uint8Array([entl >> 8 & 255, entl & 255]), data));
822
+ return bytesToHex(sm3(utils4.concatBytes(z, typeof hashHex === "string" ? hexToArray(hashHex) : hashHex)));
721
823
  }
722
824
  function getPublicKeyFromPrivateKey(privateKey) {
723
825
  const pubKey = sm2Curve.getPublicKey(privateKey, false);
724
- const pubPad = leftPad2(utils4.bytesToHex(pubKey), 64);
826
+ const pubPad = leftPad(utils4.bytesToHex(pubKey), 64);
725
827
  return pubPad;
726
828
  }
727
829
  function getPoint() {
@@ -735,6 +837,48 @@ function getPoint() {
735
837
  };
736
838
  }
737
839
 
840
+ // src/sm3/index.ts
841
+ function utf8ToArray(str) {
842
+ const arr = [];
843
+ for (let i = 0, len = str.length; i < len; i++) {
844
+ const point = str.codePointAt(i);
845
+ if (point <= 127) {
846
+ arr.push(point);
847
+ } else if (point <= 2047) {
848
+ arr.push(192 | point >>> 6);
849
+ arr.push(128 | point & 63);
850
+ } else if (point <= 55295 || point >= 57344 && point <= 65535) {
851
+ arr.push(224 | point >>> 12);
852
+ arr.push(128 | point >>> 6 & 63);
853
+ arr.push(128 | point & 63);
854
+ } else if (point >= 65536 && point <= 1114111) {
855
+ i++;
856
+ arr.push(240 | point >>> 18 & 28);
857
+ arr.push(128 | point >>> 12 & 63);
858
+ arr.push(128 | point >>> 6 & 63);
859
+ arr.push(128 | point & 63);
860
+ } else {
861
+ arr.push(point);
862
+ throw new Error("input is not supported");
863
+ }
864
+ }
865
+ return new Uint8Array(arr);
866
+ }
867
+ function sm32(input, options) {
868
+ input = typeof input === "string" ? utf8ToArray(input) : input;
869
+ if (options) {
870
+ const mode = options.mode || "hmac";
871
+ if (mode !== "hmac")
872
+ throw new Error("invalid mode");
873
+ let key = options.key;
874
+ if (!key)
875
+ throw new Error("invalid key");
876
+ key = typeof key === "string" ? hexToArray(key) : key;
877
+ return bytesToHex(hmac(sm3, key, input));
878
+ }
879
+ return bytesToHex(sm3(input));
880
+ }
881
+
738
882
  // src/sm4/index.ts
739
883
  var sm4_exports = {};
740
884
  __export(sm4_exports, {
@@ -1046,9 +1190,9 @@ function l1(b) {
1046
1190
  function l2(b) {
1047
1191
  return b ^ rotl(b, 13) ^ rotl(b, 23);
1048
1192
  }
1193
+ var x = new Uint32Array(4);
1194
+ var tmp = new Uint32Array(4);
1049
1195
  function sms4Crypt(input, output, roundKey) {
1050
- const x = new Uint32Array(4);
1051
- const tmp = new Uint32Array(4);
1052
1196
  for (let i = 0; i < 4; i++) {
1053
1197
  tmp[0] = input[4 * i] & 255;
1054
1198
  tmp[1] = input[4 * i + 1] & 255;
@@ -1074,8 +1218,6 @@ function sms4Crypt(input, output, roundKey) {
1074
1218
  }
1075
1219
  }
1076
1220
  function sms4KeyExt(key, roundKey, cryptFlag) {
1077
- const x = new Uint32Array(4);
1078
- const tmp = new Uint32Array(4);
1079
1221
  for (let i = 0; i < 4; i++) {
1080
1222
  tmp[0] = key[0 + 4 * i] & 255;
1081
1223
  tmp[1] = key[1 + 4 * i] & 255;
@@ -1105,6 +1247,7 @@ function sms4KeyExt(key, roundKey, cryptFlag) {
1105
1247
  }
1106
1248
  }
1107
1249
  }
1250
+ var blockOutput = new Uint8Array(16);
1108
1251
  function sm4(inArray, key, cryptFlag, options = {}) {
1109
1252
  let {
1110
1253
  padding = "pkcs#7",
@@ -1148,8 +1291,7 @@ function sm4(inArray, key, cryptFlag, options = {}) {
1148
1291
  let restLen = inArray.length;
1149
1292
  let point = 0;
1150
1293
  while (restLen >= BLOCK) {
1151
- const input = inArray.slice(point, point + 16);
1152
- const output2 = new Uint8Array(16);
1294
+ const input = inArray.subarray(point, point + 16);
1153
1295
  if (mode === "cbc") {
1154
1296
  for (let i = 0; i < BLOCK; i++) {
1155
1297
  if (cryptFlag !== DECRYPT) {
@@ -1157,18 +1299,18 @@ function sm4(inArray, key, cryptFlag, options = {}) {
1157
1299
  }
1158
1300
  }
1159
1301
  }
1160
- sms4Crypt(input, output2, roundKey);
1302
+ sms4Crypt(input, blockOutput, roundKey);
1161
1303
  for (let i = 0; i < BLOCK; i++) {
1162
1304
  if (mode === "cbc") {
1163
1305
  if (cryptFlag === DECRYPT) {
1164
- output2[i] ^= lastVector[i];
1306
+ blockOutput[i] ^= lastVector[i];
1165
1307
  }
1166
1308
  }
1167
- outArray[point + i] = output2[i];
1309
+ outArray[point + i] = blockOutput[i];
1168
1310
  }
1169
1311
  if (mode === "cbc") {
1170
1312
  if (cryptFlag !== DECRYPT) {
1171
- lastVector = output2;
1313
+ lastVector = blockOutput;
1172
1314
  } else {
1173
1315
  lastVector = input;
1174
1316
  }
@@ -1187,7 +1329,7 @@ function sm4(inArray, key, cryptFlag, options = {}) {
1187
1329
  }
1188
1330
  if (output !== "array") {
1189
1331
  if (cryptFlag !== DECRYPT) {
1190
- return arrayToHex(Array.from(outArray));
1332
+ return bytesToHex(outArray);
1191
1333
  } else {
1192
1334
  return arrayToUtf8(outArray);
1193
1335
  }
@@ -1203,6 +1345,7 @@ function decrypt(inArray, key, options = {}) {
1203
1345
  }
1204
1346
  export {
1205
1347
  sm2_exports as sm2,
1206
- sm3_exports as sm3,
1348
+ sm32 as sm3,
1207
1349
  sm4_exports as sm4
1208
1350
  };
1351
+ /*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */