sm-crypto-v2 1.7.0 → 1.9.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/CHANGELOG.md CHANGED
@@ -2,6 +2,21 @@
2
2
 
3
3
  All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines.
4
4
 
5
+ ## [1.9.0](https://github.com/Cubelrti/sm-crypto-v2/compare/v1.7.0...v1.9.0) (2023-12-27)
6
+
7
+
8
+ ### Features
9
+
10
+ * **sm2:** support asn1 der encoded encryption/decryption ([f08b9fd](https://github.com/Cubelrti/sm-crypto-v2/commit/f08b9fd5b64a2a257d41694c1858d7a6b07326ae))
11
+ * support miniprogram build ([bb4dddc](https://github.com/Cubelrti/sm-crypto-v2/commit/bb4dddcb4935299fe6db82912f393aa427961e40))
12
+
13
+ ## [1.8.0](https://github.com/Cubelrti/sm-crypto-v2/compare/v1.7.0...v1.8.0) (2023-12-15)
14
+
15
+
16
+ ### Features
17
+
18
+ * **sm2:** support asn1 der encoded encryption/decryption ([f08b9fd](https://github.com/Cubelrti/sm-crypto-v2/commit/f08b9fd5b64a2a257d41694c1858d7a6b07326ae))
19
+
5
20
  ## [1.7.0](https://github.com/Cubelrti/sm-crypto-v2/compare/v1.6.0...v1.7.0) (2023-07-17)
6
21
 
7
22
 
package/README.md CHANGED
@@ -57,9 +57,11 @@ verifyResult = sm2.verifyPublicKey(compressedPublicKey) // 验证公钥
57
57
  ```js
58
58
  import { sm2 } from 'sm-crypto-v2'
59
59
  const cipherMode = 1 // 1 - C1C3C2,0 - C1C2C3,默认为1
60
+ // 支持使用 asn1 对加密结果进行编码,在 options 参数中传入 { asn1: true } 即可,默认不开启
61
+ let encryptData = sm2.doEncrypt(msgString, publicKey, cipherMode, { asn1: false }) // 加密结果
60
62
 
61
- let encryptData = sm2.doEncrypt(msgString, publicKey, cipherMode) // 加密结果
62
- let decryptData = sm2.doDecrypt(encryptData, privateKey, cipherMode) // 解密结果
63
+ // 支持使用 asn1 对密文进行解码再解密,在 options 参数中传入 { asn1: true } 即可,默认不开启
64
+ let decryptData = sm2.doDecrypt(encryptData, privateKey, cipherMode, { asn1: false }) // 解密结果
63
65
 
64
66
  encryptData = sm2.doEncrypt(msgArray, publicKey, cipherMode) // 加密结果,输入数组
65
67
  decryptData = sm2.doDecrypt(encryptData, privateKey, cipherMode, {output: 'array'}) // 解密结果,输出数组
@@ -0,0 +1,175 @@
1
+ import { ProjPointType } from '@noble/curves/abstract/weierstrass';
2
+
3
+ interface KeyPair {
4
+ privateKey: string;
5
+ publicKey: string;
6
+ }
7
+ /**
8
+ * 生成密钥对:publicKey = privateKey * G
9
+ */
10
+ declare function generateKeyPairHex(str?: string): KeyPair;
11
+ /**
12
+ * 生成压缩公钥
13
+ */
14
+ declare function compressPublicKeyHex(s: string): string;
15
+ /**
16
+ * utf8串转16进制串
17
+ */
18
+ declare function utf8ToHex(input: string): string;
19
+ /**
20
+ * 补全16进制字符串
21
+ */
22
+ declare function leftPad(input: string, num: number): string;
23
+ /**
24
+ * 转成16进制串
25
+ */
26
+ declare function arrayToHex(arr: number[]): string;
27
+ /**
28
+ * 转成utf8串
29
+ */
30
+ declare function arrayToUtf8(arr: Uint8Array): string;
31
+ /**
32
+ * 转成字节数组
33
+ */
34
+ declare function hexToArray(hexStr: string): Uint8Array;
35
+ /**
36
+ * 验证公钥是否为椭圆曲线上的点
37
+ */
38
+ declare function verifyPublicKey(publicKey: string): boolean;
39
+ /**
40
+ * 验证公钥是否等价,等价返回true
41
+ */
42
+ declare function comparePublicKeyHex(publicKey1: string, publicKey2: string): boolean;
43
+
44
+ declare function initRNGPool(): Promise<void>;
45
+
46
+ declare function calculateSharedKey(keypairA: KeyPair, ephemeralKeypairA: KeyPair, publicKeyB: string, ephemeralPublicKeyB: string, sharedKeyLength: number, isRecipient?: boolean, idA?: string, idB?: string): Uint8Array;
47
+
48
+ declare const EmptyArray: Uint8Array;
49
+ /**
50
+ * 加密
51
+ */
52
+ declare function doEncrypt(msg: string | Uint8Array, publicKey: string | ProjPointType<bigint>, cipherMode?: number, options?: {
53
+ asn1?: boolean;
54
+ }): string;
55
+ /**
56
+ * 解密
57
+ */
58
+ declare function doDecrypt(encryptData: string, privateKey: string, cipherMode?: number, options?: {
59
+ output: 'array';
60
+ asn1?: boolean;
61
+ }): Uint8Array;
62
+ declare function doDecrypt(encryptData: string, privateKey: string, cipherMode?: number, options?: {
63
+ output: 'string';
64
+ asn1?: boolean;
65
+ }): string;
66
+ interface SignaturePoint {
67
+ k: bigint;
68
+ x1: bigint;
69
+ }
70
+ /**
71
+ * 签名
72
+ */
73
+ declare function doSignature(msg: Uint8Array | string, privateKey: string, options?: {
74
+ pointPool?: SignaturePoint[];
75
+ der?: boolean;
76
+ hash?: boolean;
77
+ publicKey?: string;
78
+ userId?: string;
79
+ }): string;
80
+ /**
81
+ * 验签
82
+ */
83
+ declare function doVerifySignature(msg: string | Uint8Array, signHex: string, publicKey: string | ProjPointType<bigint>, options?: {
84
+ der?: boolean;
85
+ hash?: boolean;
86
+ userId?: string;
87
+ }): boolean;
88
+ declare function getZ(publicKey: string, userId?: string): Uint8Array;
89
+ /**
90
+ * sm3杂凑算法
91
+ */
92
+ declare function getHash(hashHex: string | Uint8Array, publicKey: string, userId?: string): string;
93
+ /**
94
+ * 预计算公钥点,可用于提升加密性能
95
+ * @export
96
+ * @param {string} publicKey 公钥
97
+ * @param windowSize 计算窗口大小,默认为 8
98
+ * @returns {ProjPointType<bigint>} 预计算的点
99
+ */
100
+ declare function precomputePublicKey(publicKey: string, windowSize?: number): ProjPointType<bigint>;
101
+ /**
102
+ * 计算公钥
103
+ */
104
+ declare function getPublicKeyFromPrivateKey(privateKey: string): string;
105
+ /**
106
+ * 获取椭圆曲线点
107
+ */
108
+ declare function getPoint(): {
109
+ k: bigint;
110
+ x1: bigint;
111
+ privateKey: string;
112
+ publicKey: string;
113
+ };
114
+
115
+ declare const index$1_EmptyArray: typeof EmptyArray;
116
+ type index$1_KeyPair = KeyPair;
117
+ type index$1_SignaturePoint = SignaturePoint;
118
+ declare const index$1_arrayToHex: typeof arrayToHex;
119
+ declare const index$1_arrayToUtf8: typeof arrayToUtf8;
120
+ declare const index$1_calculateSharedKey: typeof calculateSharedKey;
121
+ declare const index$1_comparePublicKeyHex: typeof comparePublicKeyHex;
122
+ declare const index$1_compressPublicKeyHex: typeof compressPublicKeyHex;
123
+ declare const index$1_doDecrypt: typeof doDecrypt;
124
+ declare const index$1_doEncrypt: typeof doEncrypt;
125
+ declare const index$1_doSignature: typeof doSignature;
126
+ declare const index$1_doVerifySignature: typeof doVerifySignature;
127
+ declare const index$1_generateKeyPairHex: typeof generateKeyPairHex;
128
+ declare const index$1_getHash: typeof getHash;
129
+ declare const index$1_getPoint: typeof getPoint;
130
+ declare const index$1_getPublicKeyFromPrivateKey: typeof getPublicKeyFromPrivateKey;
131
+ declare const index$1_getZ: typeof getZ;
132
+ declare const index$1_hexToArray: typeof hexToArray;
133
+ declare const index$1_initRNGPool: typeof initRNGPool;
134
+ declare const index$1_leftPad: typeof leftPad;
135
+ declare const index$1_precomputePublicKey: typeof precomputePublicKey;
136
+ declare const index$1_utf8ToHex: typeof utf8ToHex;
137
+ declare const index$1_verifyPublicKey: typeof verifyPublicKey;
138
+ declare namespace index$1 {
139
+ export { index$1_EmptyArray as EmptyArray, type index$1_KeyPair as KeyPair, type index$1_SignaturePoint as SignaturePoint, index$1_arrayToHex as arrayToHex, index$1_arrayToUtf8 as arrayToUtf8, index$1_calculateSharedKey as calculateSharedKey, index$1_comparePublicKeyHex as comparePublicKeyHex, index$1_compressPublicKeyHex as compressPublicKeyHex, index$1_doDecrypt as doDecrypt, index$1_doEncrypt as doEncrypt, index$1_doSignature as doSignature, index$1_doVerifySignature as doVerifySignature, index$1_generateKeyPairHex as generateKeyPairHex, index$1_getHash as getHash, index$1_getPoint as getPoint, index$1_getPublicKeyFromPrivateKey as getPublicKeyFromPrivateKey, index$1_getZ as getZ, index$1_hexToArray as hexToArray, index$1_initRNGPool as initRNGPool, index$1_leftPad as leftPad, index$1_precomputePublicKey as precomputePublicKey, index$1_utf8ToHex as utf8ToHex, index$1_verifyPublicKey as verifyPublicKey };
140
+ }
141
+
142
+ declare function sm3(input: string | Uint8Array, options?: {
143
+ key: Uint8Array | string;
144
+ mode?: 'hmac' | 'mac';
145
+ }): string;
146
+
147
+ interface SM4Options {
148
+ padding?: 'pkcs#7' | 'pkcs#5' | 'none' | null;
149
+ mode?: 'cbc' | 'ecb';
150
+ iv?: Uint8Array | string;
151
+ output?: 'string' | 'array';
152
+ }
153
+ declare function sm4(inArray: Uint8Array | string, key: Uint8Array | string, cryptFlag: 0 | 1, options?: SM4Options): string | Uint8Array;
154
+ declare function encrypt(inArray: Uint8Array | string, key: Uint8Array | string, options?: {
155
+ output: 'array';
156
+ } | SM4Options): Uint8Array;
157
+ declare function encrypt(inArray: Uint8Array | string, key: Uint8Array | string, options?: {
158
+ output: 'string';
159
+ } | SM4Options): string;
160
+ declare function decrypt(inArray: Uint8Array | string, key: Uint8Array | string, options?: {
161
+ output: 'array';
162
+ } | SM4Options): Uint8Array;
163
+ declare function decrypt(inArray: Uint8Array | string, key: Uint8Array | string, options?: {
164
+ output: 'string';
165
+ } | SM4Options): string;
166
+
167
+ type index_SM4Options = SM4Options;
168
+ declare const index_decrypt: typeof decrypt;
169
+ declare const index_encrypt: typeof encrypt;
170
+ declare const index_sm4: typeof sm4;
171
+ declare namespace index {
172
+ export { type index_SM4Options as SM4Options, index_decrypt as decrypt, index_encrypt as encrypt, index_sm4 as sm4 };
173
+ }
174
+
175
+ export { index$1 as sm2, sm3, index as sm4 };
package/dist/index.d.ts CHANGED
@@ -49,15 +49,19 @@ declare const EmptyArray: Uint8Array;
49
49
  /**
50
50
  * 加密
51
51
  */
52
- declare function doEncrypt(msg: string | Uint8Array, publicKey: string | ProjPointType<bigint>, cipherMode?: number): string;
52
+ declare function doEncrypt(msg: string | Uint8Array, publicKey: string | ProjPointType<bigint>, cipherMode?: number, options?: {
53
+ asn1?: boolean;
54
+ }): string;
53
55
  /**
54
56
  * 解密
55
57
  */
56
58
  declare function doDecrypt(encryptData: string, privateKey: string, cipherMode?: number, options?: {
57
59
  output: 'array';
60
+ asn1?: boolean;
58
61
  }): Uint8Array;
59
62
  declare function doDecrypt(encryptData: string, privateKey: string, cipherMode?: number, options?: {
60
63
  output: 'string';
64
+ asn1?: boolean;
61
65
  }): string;
62
66
  interface SignaturePoint {
63
67
  k: bigint;
@@ -109,54 +113,30 @@ declare function getPoint(): {
109
113
  };
110
114
 
111
115
  declare const index$1_EmptyArray: typeof EmptyArray;
112
- declare const index$1_doEncrypt: typeof doEncrypt;
113
- declare const index$1_doDecrypt: typeof doDecrypt;
116
+ type index$1_KeyPair = KeyPair;
114
117
  type index$1_SignaturePoint = SignaturePoint;
118
+ declare const index$1_arrayToHex: typeof arrayToHex;
119
+ declare const index$1_arrayToUtf8: typeof arrayToUtf8;
120
+ declare const index$1_calculateSharedKey: typeof calculateSharedKey;
121
+ declare const index$1_comparePublicKeyHex: typeof comparePublicKeyHex;
122
+ declare const index$1_compressPublicKeyHex: typeof compressPublicKeyHex;
123
+ declare const index$1_doDecrypt: typeof doDecrypt;
124
+ declare const index$1_doEncrypt: typeof doEncrypt;
115
125
  declare const index$1_doSignature: typeof doSignature;
116
126
  declare const index$1_doVerifySignature: typeof doVerifySignature;
117
- declare const index$1_getZ: typeof getZ;
127
+ declare const index$1_generateKeyPairHex: typeof generateKeyPairHex;
118
128
  declare const index$1_getHash: typeof getHash;
119
- declare const index$1_precomputePublicKey: typeof precomputePublicKey;
120
- declare const index$1_getPublicKeyFromPrivateKey: typeof getPublicKeyFromPrivateKey;
121
129
  declare const index$1_getPoint: typeof getPoint;
130
+ declare const index$1_getPublicKeyFromPrivateKey: typeof getPublicKeyFromPrivateKey;
131
+ declare const index$1_getZ: typeof getZ;
132
+ declare const index$1_hexToArray: typeof hexToArray;
122
133
  declare const index$1_initRNGPool: typeof initRNGPool;
123
- declare const index$1_calculateSharedKey: typeof calculateSharedKey;
124
- type index$1_KeyPair = KeyPair;
125
- declare const index$1_generateKeyPairHex: typeof generateKeyPairHex;
126
- declare const index$1_compressPublicKeyHex: typeof compressPublicKeyHex;
127
- declare const index$1_utf8ToHex: typeof utf8ToHex;
128
134
  declare const index$1_leftPad: typeof leftPad;
129
- declare const index$1_arrayToHex: typeof arrayToHex;
130
- declare const index$1_arrayToUtf8: typeof arrayToUtf8;
131
- declare const index$1_hexToArray: typeof hexToArray;
135
+ declare const index$1_precomputePublicKey: typeof precomputePublicKey;
136
+ declare const index$1_utf8ToHex: typeof utf8ToHex;
132
137
  declare const index$1_verifyPublicKey: typeof verifyPublicKey;
133
- declare const index$1_comparePublicKeyHex: typeof comparePublicKeyHex;
134
138
  declare namespace index$1 {
135
- export {
136
- index$1_EmptyArray as EmptyArray,
137
- index$1_doEncrypt as doEncrypt,
138
- index$1_doDecrypt as doDecrypt,
139
- index$1_SignaturePoint as SignaturePoint,
140
- index$1_doSignature as doSignature,
141
- index$1_doVerifySignature as doVerifySignature,
142
- index$1_getZ as getZ,
143
- index$1_getHash as getHash,
144
- index$1_precomputePublicKey as precomputePublicKey,
145
- index$1_getPublicKeyFromPrivateKey as getPublicKeyFromPrivateKey,
146
- index$1_getPoint as getPoint,
147
- index$1_initRNGPool as initRNGPool,
148
- index$1_calculateSharedKey as calculateSharedKey,
149
- index$1_KeyPair as KeyPair,
150
- index$1_generateKeyPairHex as generateKeyPairHex,
151
- index$1_compressPublicKeyHex as compressPublicKeyHex,
152
- index$1_utf8ToHex as utf8ToHex,
153
- index$1_leftPad as leftPad,
154
- index$1_arrayToHex as arrayToHex,
155
- index$1_arrayToUtf8 as arrayToUtf8,
156
- index$1_hexToArray as hexToArray,
157
- index$1_verifyPublicKey as verifyPublicKey,
158
- index$1_comparePublicKeyHex as comparePublicKeyHex,
159
- };
139
+ export { index$1_EmptyArray as EmptyArray, type index$1_KeyPair as KeyPair, type index$1_SignaturePoint as SignaturePoint, index$1_arrayToHex as arrayToHex, index$1_arrayToUtf8 as arrayToUtf8, index$1_calculateSharedKey as calculateSharedKey, index$1_comparePublicKeyHex as comparePublicKeyHex, index$1_compressPublicKeyHex as compressPublicKeyHex, index$1_doDecrypt as doDecrypt, index$1_doEncrypt as doEncrypt, index$1_doSignature as doSignature, index$1_doVerifySignature as doVerifySignature, index$1_generateKeyPairHex as generateKeyPairHex, index$1_getHash as getHash, index$1_getPoint as getPoint, index$1_getPublicKeyFromPrivateKey as getPublicKeyFromPrivateKey, index$1_getZ as getZ, index$1_hexToArray as hexToArray, index$1_initRNGPool as initRNGPool, index$1_leftPad as leftPad, index$1_precomputePublicKey as precomputePublicKey, index$1_utf8ToHex as utf8ToHex, index$1_verifyPublicKey as verifyPublicKey };
160
140
  }
161
141
 
162
142
  declare function sm3(input: string | Uint8Array, options?: {
@@ -185,16 +165,11 @@ declare function decrypt(inArray: Uint8Array | string, key: Uint8Array | string,
185
165
  } | SM4Options): string;
186
166
 
187
167
  type index_SM4Options = SM4Options;
188
- declare const index_sm4: typeof sm4;
189
- declare const index_encrypt: typeof encrypt;
190
168
  declare const index_decrypt: typeof decrypt;
169
+ declare const index_encrypt: typeof encrypt;
170
+ declare const index_sm4: typeof sm4;
191
171
  declare namespace index {
192
- export {
193
- index_SM4Options as SM4Options,
194
- index_sm4 as sm4,
195
- index_encrypt as encrypt,
196
- index_decrypt as decrypt,
197
- };
172
+ export { type index_SM4Options as SM4Options, index_decrypt as decrypt, index_encrypt as encrypt, index_sm4 as sm4 };
198
173
  }
199
174
 
200
175
  export { index$1 as sm2, sm3, index as sm4 };
package/dist/index.js CHANGED
@@ -18,6 +18,10 @@ var __copyProps = (to, from, except, desc) => {
18
18
  return to;
19
19
  };
20
20
  var __toESM = (mod2, isNodeMode, target) => (target = mod2 != null ? __create(__getProtoOf(mod2)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
21
25
  isNodeMode || !mod2 || !mod2.__esModule ? __defProp(target, "default", { value: mod2, enumerable: true }) : target,
22
26
  mod2
23
27
  ));
@@ -98,6 +102,9 @@ var ASN1Object = class {
98
102
  this.l = l;
99
103
  this.v = v;
100
104
  }
105
+ /**
106
+ * 获取 der 编码比特流16进制串
107
+ */
101
108
  getEncodedHex() {
102
109
  if (!this.tlv) {
103
110
  this.v = this.getValue();
@@ -133,6 +140,19 @@ var DERInteger = class extends ASN1Object {
133
140
  return this.v;
134
141
  }
135
142
  };
143
+ var DEROctetString = class extends ASN1Object {
144
+ constructor(s) {
145
+ super();
146
+ this.s = s;
147
+ this.t = "04";
148
+ if (s)
149
+ this.v = s.toLowerCase();
150
+ }
151
+ hV = "";
152
+ getValue() {
153
+ return this.v;
154
+ }
155
+ };
136
156
  var DERSequence = class extends ASN1Object {
137
157
  constructor(asn1Array) {
138
158
  super();
@@ -167,11 +187,19 @@ function encodeDer(r, s) {
167
187
  const derSeq = new DERSequence([derR, derS]);
168
188
  return derSeq.getEncodedHex();
169
189
  }
190
+ function encodeEnc(x2, y, hash, cipher) {
191
+ const derX = new DERInteger(x2);
192
+ const derY = new DERInteger(y);
193
+ const derHash = new DEROctetString(hash);
194
+ const derCipher = new DEROctetString(cipher);
195
+ const derSeq = new DERSequence([derX, derY, derHash, derCipher]);
196
+ return derSeq.getEncodedHex();
197
+ }
170
198
  function decodeDer(input) {
171
199
  const start = getStartOfV(input, 0);
172
200
  const vIndexR = getStartOfV(input, start);
173
201
  const lR = getL(input, start);
174
- const vR = input.substr(vIndexR, lR * 2);
202
+ const vR = input.substring(vIndexR, vIndexR + lR * 2);
175
203
  const nextStart = vIndexR + vR.length;
176
204
  const vIndexS = getStartOfV(input, nextStart);
177
205
  const lS = getL(input, nextStart);
@@ -180,6 +208,23 @@ function decodeDer(input) {
180
208
  const s = utils.hexToNumber(vS);
181
209
  return { r, s };
182
210
  }
211
+ function decodeEnc(input) {
212
+ function extractSequence(input2, start2) {
213
+ const vIndex = getStartOfV(input2, start2);
214
+ const length = getL(input2, start2);
215
+ const value = input2.substring(vIndex, vIndex + length * 2);
216
+ const nextStart = vIndex + value.length;
217
+ return { value, nextStart };
218
+ }
219
+ const start = getStartOfV(input, 0);
220
+ const { value: vR, nextStart: startS } = extractSequence(input, start);
221
+ const { value: vS, nextStart: startHash } = extractSequence(input, startS);
222
+ const { value: hash, nextStart: startCipher } = extractSequence(input, startHash);
223
+ const { value: cipher } = extractSequence(input, startCipher);
224
+ const x2 = utils.hexToNumber(vR);
225
+ const y = utils.hexToNumber(vS);
226
+ return { x: x2, y, hash, cipher };
227
+ }
183
228
 
184
229
  // src/sm2/utils.ts
185
230
  var utils2 = __toESM(require("@noble/curves/abstract/utils"));
@@ -277,6 +322,7 @@ function toBytes(data) {
277
322
  return data;
278
323
  }
279
324
  var Hash = class {
325
+ // Safe version that clones internal state
280
326
  clone() {
281
327
  return this._cloneInto();
282
328
  }
@@ -326,6 +372,7 @@ var SHA2 = class extends Hash {
326
372
  this.buffer = new Uint8Array(blockLen);
327
373
  this.view = createView(this.buffer);
328
374
  }
375
+ // For partial updates less than block size
329
376
  buffer;
330
377
  view;
331
378
  finished = false;
@@ -407,6 +454,8 @@ var SM3_M = new Uint32Array(64);
407
454
  var T1 = 2043430169;
408
455
  var T2 = 2055708042;
409
456
  var SM3 = class extends SHA2 {
457
+ // We cannot use array here since array allows indexing by variable
458
+ // which means optimizer/compiler cannot use registers.
410
459
  A = IV[0] | 0;
411
460
  B = IV[1] | 0;
412
461
  C = IV[2] | 0;
@@ -422,6 +471,7 @@ var SM3 = class extends SHA2 {
422
471
  const { A, B, C, D, E, F, G, H } = this;
423
472
  return [A, B, C, D, E, F, G, H];
424
473
  }
474
+ // prettier-ignore
425
475
  set(A, B, C, D, E, F, G, H) {
426
476
  this.A = A | 0;
427
477
  this.B = B | 0;
@@ -547,6 +597,7 @@ hmac.create = (hash, key) => new HMAC(hash, key);
547
597
  var import_utils3 = require("@noble/curves/abstract/utils");
548
598
  var sm2Fp = (0, import_modular.Field)(BigInt("115792089210356248756420345214020892766250353991924191454421193933289684991999"));
549
599
  var sm2Curve = (0, import_weierstrass.weierstrass)({
600
+ // sm2: short weierstrass.
550
601
  a: BigInt("115792089210356248756420345214020892766250353991924191454421193933289684991996"),
551
602
  b: BigInt("18505919022281880113072981827955639221458448578012075254857346196103069175443"),
552
603
  Fp: sm2Fp,
@@ -714,7 +765,7 @@ function calculateSharedKey(keypairA, ephemeralKeypairA, publicKeyB, ephemeralPu
714
765
  // src/sm2/index.ts
715
766
  var C1C2C3 = 0;
716
767
  var EmptyArray = new Uint8Array();
717
- function doEncrypt(msg, publicKey, cipherMode = 1) {
768
+ function doEncrypt(msg, publicKey, cipherMode = 1, options) {
718
769
  const msgArr = typeof msg === "string" ? hexToArray(utf8ToHex(msg)) : Uint8Array.from(msg);
719
770
  const publicKeyPoint = typeof publicKey === "string" ? sm2Curve.ProjectivePoint.fromHex(publicKey) : publicKey;
720
771
  const keypair = generateKeyPairHex();
@@ -728,6 +779,11 @@ function doEncrypt(msg, publicKey, cipherMode = 1) {
728
779
  const c3 = bytesToHex(sm3(utils4.concatBytes(x2, msgArr, y2)));
729
780
  xorCipherStream(x2, y2, msgArr);
730
781
  const c2 = bytesToHex(msgArr);
782
+ if (options?.asn1) {
783
+ const point = sm2Curve.ProjectivePoint.fromHex(keypair.publicKey);
784
+ const encode = cipherMode === C1C2C3 ? encodeEnc(point.x, point.y, c2, c3) : encodeEnc(point.x, point.y, c3, c2);
785
+ return encode;
786
+ }
731
787
  return cipherMode === C1C2C3 ? c1 + c2 + c3 : c1 + c3 + c2;
732
788
  }
733
789
  function xorCipherStream(x2, y2, msg) {
@@ -752,17 +808,31 @@ function xorCipherStream(x2, y2, msg) {
752
808
  }
753
809
  }
754
810
  function doDecrypt(encryptData, privateKey, cipherMode = 1, {
755
- output = "string"
811
+ output = "string",
812
+ asn1 = false
756
813
  } = {}) {
757
814
  const privateKeyInteger = utils4.hexToNumber(privateKey);
758
- let c3 = encryptData.substring(128, 128 + 64);
759
- let c2 = encryptData.substring(128 + 64);
760
- if (cipherMode === C1C2C3) {
761
- c3 = encryptData.substring(encryptData.length - 64);
762
- c2 = encryptData.substring(128, encryptData.length - 64);
815
+ let c1;
816
+ let c2;
817
+ let c3;
818
+ if (asn1) {
819
+ const { x: x3, y, cipher, hash } = decodeEnc(encryptData);
820
+ c1 = sm2Curve.ProjectivePoint.fromAffine({ x: x3, y });
821
+ c3 = hash;
822
+ c2 = cipher;
823
+ if (cipherMode === C1C2C3) {
824
+ [c2, c3] = [c3, c2];
825
+ }
826
+ } else {
827
+ c1 = sm2Curve.ProjectivePoint.fromHex("04" + encryptData.substring(0, 128));
828
+ c3 = encryptData.substring(128, 128 + 64);
829
+ c2 = encryptData.substring(128 + 64);
830
+ if (cipherMode === C1C2C3) {
831
+ c3 = encryptData.substring(encryptData.length - 64);
832
+ c2 = encryptData.substring(128, encryptData.length - 64);
833
+ }
763
834
  }
764
835
  const msg = hexToArray(c2);
765
- const c1 = sm2Curve.ProjectivePoint.fromHex("04" + encryptData.substring(0, 128));
766
836
  const p = c1.multiply(privateKeyInteger);
767
837
  const x2 = hexToArray(leftPad(utils4.numberToHexUnpadded(p.x), 64));
768
838
  const y2 = hexToArray(leftPad(utils4.numberToHexUnpadded(p.y), 64));
package/dist/index.mjs CHANGED
@@ -70,6 +70,9 @@ var ASN1Object = class {
70
70
  this.l = l;
71
71
  this.v = v;
72
72
  }
73
+ /**
74
+ * 获取 der 编码比特流16进制串
75
+ */
73
76
  getEncodedHex() {
74
77
  if (!this.tlv) {
75
78
  this.v = this.getValue();
@@ -105,6 +108,19 @@ var DERInteger = class extends ASN1Object {
105
108
  return this.v;
106
109
  }
107
110
  };
111
+ var DEROctetString = class extends ASN1Object {
112
+ constructor(s) {
113
+ super();
114
+ this.s = s;
115
+ this.t = "04";
116
+ if (s)
117
+ this.v = s.toLowerCase();
118
+ }
119
+ hV = "";
120
+ getValue() {
121
+ return this.v;
122
+ }
123
+ };
108
124
  var DERSequence = class extends ASN1Object {
109
125
  constructor(asn1Array) {
110
126
  super();
@@ -139,11 +155,19 @@ function encodeDer(r, s) {
139
155
  const derSeq = new DERSequence([derR, derS]);
140
156
  return derSeq.getEncodedHex();
141
157
  }
158
+ function encodeEnc(x2, y, hash, cipher) {
159
+ const derX = new DERInteger(x2);
160
+ const derY = new DERInteger(y);
161
+ const derHash = new DEROctetString(hash);
162
+ const derCipher = new DEROctetString(cipher);
163
+ const derSeq = new DERSequence([derX, derY, derHash, derCipher]);
164
+ return derSeq.getEncodedHex();
165
+ }
142
166
  function decodeDer(input) {
143
167
  const start = getStartOfV(input, 0);
144
168
  const vIndexR = getStartOfV(input, start);
145
169
  const lR = getL(input, start);
146
- const vR = input.substr(vIndexR, lR * 2);
170
+ const vR = input.substring(vIndexR, vIndexR + lR * 2);
147
171
  const nextStart = vIndexR + vR.length;
148
172
  const vIndexS = getStartOfV(input, nextStart);
149
173
  const lS = getL(input, nextStart);
@@ -152,6 +176,23 @@ function decodeDer(input) {
152
176
  const s = utils.hexToNumber(vS);
153
177
  return { r, s };
154
178
  }
179
+ function decodeEnc(input) {
180
+ function extractSequence(input2, start2) {
181
+ const vIndex = getStartOfV(input2, start2);
182
+ const length = getL(input2, start2);
183
+ const value = input2.substring(vIndex, vIndex + length * 2);
184
+ const nextStart = vIndex + value.length;
185
+ return { value, nextStart };
186
+ }
187
+ const start = getStartOfV(input, 0);
188
+ const { value: vR, nextStart: startS } = extractSequence(input, start);
189
+ const { value: vS, nextStart: startHash } = extractSequence(input, startS);
190
+ const { value: hash, nextStart: startCipher } = extractSequence(input, startHash);
191
+ const { value: cipher } = extractSequence(input, startCipher);
192
+ const x2 = utils.hexToNumber(vR);
193
+ const y = utils.hexToNumber(vS);
194
+ return { x: x2, y, hash, cipher };
195
+ }
155
196
 
156
197
  // src/sm2/utils.ts
157
198
  import * as utils2 from "@noble/curves/abstract/utils";
@@ -249,6 +290,7 @@ function toBytes(data) {
249
290
  return data;
250
291
  }
251
292
  var Hash = class {
293
+ // Safe version that clones internal state
252
294
  clone() {
253
295
  return this._cloneInto();
254
296
  }
@@ -298,6 +340,7 @@ var SHA2 = class extends Hash {
298
340
  this.buffer = new Uint8Array(blockLen);
299
341
  this.view = createView(this.buffer);
300
342
  }
343
+ // For partial updates less than block size
301
344
  buffer;
302
345
  view;
303
346
  finished = false;
@@ -379,6 +422,8 @@ var SM3_M = new Uint32Array(64);
379
422
  var T1 = 2043430169;
380
423
  var T2 = 2055708042;
381
424
  var SM3 = class extends SHA2 {
425
+ // We cannot use array here since array allows indexing by variable
426
+ // which means optimizer/compiler cannot use registers.
382
427
  A = IV[0] | 0;
383
428
  B = IV[1] | 0;
384
429
  C = IV[2] | 0;
@@ -394,6 +439,7 @@ var SM3 = class extends SHA2 {
394
439
  const { A, B, C, D, E, F, G, H } = this;
395
440
  return [A, B, C, D, E, F, G, H];
396
441
  }
442
+ // prettier-ignore
397
443
  set(A, B, C, D, E, F, G, H) {
398
444
  this.A = A | 0;
399
445
  this.B = B | 0;
@@ -519,6 +565,7 @@ hmac.create = (hash, key) => new HMAC(hash, key);
519
565
  import { concatBytes } from "@noble/curves/abstract/utils";
520
566
  var sm2Fp = Field(BigInt("115792089210356248756420345214020892766250353991924191454421193933289684991999"));
521
567
  var sm2Curve = weierstrass({
568
+ // sm2: short weierstrass.
522
569
  a: BigInt("115792089210356248756420345214020892766250353991924191454421193933289684991996"),
523
570
  b: BigInt("18505919022281880113072981827955639221458448578012075254857346196103069175443"),
524
571
  Fp: sm2Fp,
@@ -686,7 +733,7 @@ function calculateSharedKey(keypairA, ephemeralKeypairA, publicKeyB, ephemeralPu
686
733
  // src/sm2/index.ts
687
734
  var C1C2C3 = 0;
688
735
  var EmptyArray = new Uint8Array();
689
- function doEncrypt(msg, publicKey, cipherMode = 1) {
736
+ function doEncrypt(msg, publicKey, cipherMode = 1, options) {
690
737
  const msgArr = typeof msg === "string" ? hexToArray(utf8ToHex(msg)) : Uint8Array.from(msg);
691
738
  const publicKeyPoint = typeof publicKey === "string" ? sm2Curve.ProjectivePoint.fromHex(publicKey) : publicKey;
692
739
  const keypair = generateKeyPairHex();
@@ -700,6 +747,11 @@ function doEncrypt(msg, publicKey, cipherMode = 1) {
700
747
  const c3 = bytesToHex(sm3(utils4.concatBytes(x2, msgArr, y2)));
701
748
  xorCipherStream(x2, y2, msgArr);
702
749
  const c2 = bytesToHex(msgArr);
750
+ if (options?.asn1) {
751
+ const point = sm2Curve.ProjectivePoint.fromHex(keypair.publicKey);
752
+ const encode = cipherMode === C1C2C3 ? encodeEnc(point.x, point.y, c2, c3) : encodeEnc(point.x, point.y, c3, c2);
753
+ return encode;
754
+ }
703
755
  return cipherMode === C1C2C3 ? c1 + c2 + c3 : c1 + c3 + c2;
704
756
  }
705
757
  function xorCipherStream(x2, y2, msg) {
@@ -724,17 +776,31 @@ function xorCipherStream(x2, y2, msg) {
724
776
  }
725
777
  }
726
778
  function doDecrypt(encryptData, privateKey, cipherMode = 1, {
727
- output = "string"
779
+ output = "string",
780
+ asn1 = false
728
781
  } = {}) {
729
782
  const privateKeyInteger = utils4.hexToNumber(privateKey);
730
- let c3 = encryptData.substring(128, 128 + 64);
731
- let c2 = encryptData.substring(128 + 64);
732
- if (cipherMode === C1C2C3) {
733
- c3 = encryptData.substring(encryptData.length - 64);
734
- c2 = encryptData.substring(128, encryptData.length - 64);
783
+ let c1;
784
+ let c2;
785
+ let c3;
786
+ if (asn1) {
787
+ const { x: x3, y, cipher, hash } = decodeEnc(encryptData);
788
+ c1 = sm2Curve.ProjectivePoint.fromAffine({ x: x3, y });
789
+ c3 = hash;
790
+ c2 = cipher;
791
+ if (cipherMode === C1C2C3) {
792
+ [c2, c3] = [c3, c2];
793
+ }
794
+ } else {
795
+ c1 = sm2Curve.ProjectivePoint.fromHex("04" + encryptData.substring(0, 128));
796
+ c3 = encryptData.substring(128, 128 + 64);
797
+ c2 = encryptData.substring(128 + 64);
798
+ if (cipherMode === C1C2C3) {
799
+ c3 = encryptData.substring(encryptData.length - 64);
800
+ c2 = encryptData.substring(128, encryptData.length - 64);
801
+ }
735
802
  }
736
803
  const msg = hexToArray(c2);
737
- const c1 = sm2Curve.ProjectivePoint.fromHex("04" + encryptData.substring(0, 128));
738
804
  const p = c1.multiply(privateKeyInteger);
739
805
  const x2 = hexToArray(leftPad(utils4.numberToHexUnpadded(p.x), 64));
740
806
  const y2 = hexToArray(leftPad(utils4.numberToHexUnpadded(p.y), 64));