sm-crypto-wasm 0.2.1 → 0.3.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.
@@ -0,0 +1,43 @@
1
+ /**
2
+ * SM9 输入归一化与密钥参数校验。
3
+ *
4
+ * 从 `index.ts` 拆出,供 `kem.ts` / `hybrid.ts` 复用,避免循环依赖。
5
+ */
6
+ /**
7
+ * 通用输入归一化:Uint8Array 拷贝、hex 解码、其它按 UTF-8。
8
+ *
9
+ * **刻意不做 PEM 嗅探** —— PEM 只可能出现在密钥参数上,由 `masterPrivateBytes`
10
+ * 显式处理;这样 id / msg 里出现 `-----BEGIN` 也不会被误吞。
11
+ */
12
+ export declare function toBytes(input: string | Uint8Array, label: string): Uint8Array;
13
+ /**
14
+ * 主私钥参数归一化:接受 32 字节(hex / Uint8Array)或 PKCS#8 私钥 PEM
15
+ * (spec §12.1 Q3,算法 OID `1.2.156.10197.1.100`)。
16
+ */
17
+ export declare function masterPrivateBytes(input: string | Uint8Array, label: string): Uint8Array;
18
+ /** 主公钥参数归一化:64(加密 G1)或 128(签名 G2)字节点,或 SPKI 主公钥 PEM。 */
19
+ export declare function masterPublicBytes(input: string | Uint8Array, label: string): Uint8Array;
20
+ /** `verify` / `encrypt` 第一参数的解析结果。 */
21
+ export type KeyArg = {
22
+ kind: 'secret';
23
+ bytes: Uint8Array;
24
+ } | {
25
+ kind: 'public';
26
+ bytes: Uint8Array;
27
+ };
28
+ /**
29
+ * 解析 `verify` / `encrypt` 的密钥参数:主私钥(32 字节 / PKCS#8 私钥 PEM)
30
+ * 或主公钥(`publicLen` 字节点 / SPKI 公钥 PEM)。
31
+ *
32
+ * 两者的长度区间不重叠(主私钥恒为 32 字节),因此按长度即可判别。
33
+ */
34
+ export declare function keyArg(input: string | Uint8Array, publicLen: 64 | 128, label: string): KeyArg;
35
+ /**
36
+ * 校验字节长度。默认按**密钥支**(`InvalidKeyError`)抛错 —— SM9 各入口的参数绝大多数
37
+ * 是主私钥 / 标量;密文、签名、协议消息的调用点显式传 `'cipher'`。
38
+ */
39
+ export declare function requireLen(b: Uint8Array, n: number, label: string, kind?: 'key' | 'cipher'): void;
40
+ export declare function putHex(hex: string, ptr: number): void;
41
+ export declare function putBytes(b: Uint8Array, ptr: number): void;
42
+ export declare function readHex(ptr: number, len: number): string;
43
+ export declare function randomRHex(): string;
@@ -0,0 +1,121 @@
1
+ /**
2
+ * SM9 输入归一化与密钥参数校验。
3
+ *
4
+ * 从 `index.ts` 拆出,供 `kem.ts` / `hybrid.ts` 复用,避免循环依赖。
5
+ */
6
+ import { parseSm9PrivateKeyPem, parseSm9PublicKeyPem } from '../pem/sm9.js';
7
+ import { bytesToHex, hexToBytes } from '../runtime/convert.js';
8
+ import { InvalidCiphertextError, InvalidKeyError } from '../runtime/errors.js';
9
+ import { randomScalarBelow } from '../runtime/random.js';
10
+ import { mem, N } from './core.js';
11
+ /**
12
+ * 通用输入归一化:Uint8Array 拷贝、hex 解码、其它按 UTF-8。
13
+ *
14
+ * **刻意不做 PEM 嗅探** —— PEM 只可能出现在密钥参数上,由 `masterPrivateBytes`
15
+ * 显式处理;这样 id / msg 里出现 `-----BEGIN` 也不会被误吞。
16
+ */
17
+ export function toBytes(input, label) {
18
+ if (input instanceof Uint8Array)
19
+ return new Uint8Array(input);
20
+ if (typeof input !== 'string')
21
+ throw new TypeError(`sm9: ${label} 必须是字符串或 Uint8Array`);
22
+ if (input.startsWith('0x') || /^[0-9a-fA-F]+$/.test(input)) {
23
+ const s = input.startsWith('0x') ? input.slice(2) : input;
24
+ if (s.length % 2 !== 0)
25
+ throw new TypeError(`sm9: ${label} hex 长度必须为偶数`);
26
+ return hexToBytes(s, label);
27
+ }
28
+ return new TextEncoder().encode(input);
29
+ }
30
+ /**
31
+ * 主私钥参数归一化:接受 32 字节(hex / Uint8Array)或 PKCS#8 私钥 PEM
32
+ * (spec §12.1 Q3,算法 OID `1.2.156.10197.1.100`)。
33
+ */
34
+ export function masterPrivateBytes(input, label) {
35
+ let bytes;
36
+ if (typeof input === 'string' && input.includes('-----BEGIN')) {
37
+ const parsed = parseSm9PrivateKeyPem(input);
38
+ if (parsed.length !== 32) {
39
+ throw new InvalidKeyError(`sm9: ${label} 作为 PEM 主私钥应为 32 字节,实际 ${parsed.length}`);
40
+ }
41
+ bytes = parsed;
42
+ }
43
+ else {
44
+ const b = toBytes(input, label);
45
+ if (b.length !== 32) {
46
+ throw new InvalidKeyError(`sm9: ${label} 必须是 32 字节主私钥,实际 ${b.length}`);
47
+ }
48
+ bytes = b;
49
+ }
50
+ // 标量范围:SM9(GM/T 0044)要求 1 ≤ k ≤ n−1。
51
+ // 越界值不会崩,但 wasm 侧的 addModN → modAdd 只做一次条件减、要求输入已
52
+ // 约化(h1 + k < 2n),k ≥ n 时 k + h1 可能 ≥ 2n 而静默产出错值,故在此显式拒绝。
53
+ const k = BigInt(`0x${bytesToHex(bytes)}`);
54
+ if (k < 1n || k >= N) {
55
+ throw new InvalidKeyError(`sm9: ${label} 必须在 [1, n−1] 范围内(SM9 主私钥标量)`);
56
+ }
57
+ return bytes;
58
+ }
59
+ /** 主公钥参数归一化:64(加密 G1)或 128(签名 G2)字节点,或 SPKI 主公钥 PEM。 */
60
+ export function masterPublicBytes(input, label) {
61
+ if (typeof input === 'string' && input.includes('-----BEGIN')) {
62
+ const pub = parseSm9PublicKeyPem(input);
63
+ if (pub.length !== 64 && pub.length !== 128) {
64
+ throw new InvalidKeyError(`sm9: ${label} 作为 PEM 主公钥必须是 64 或 128 字节,实际 ${pub.length}`);
65
+ }
66
+ return pub;
67
+ }
68
+ const b = toBytes(input, label);
69
+ if (b.length !== 64 && b.length !== 128) {
70
+ throw new InvalidKeyError(`sm9: ${label} 必须是 64(加密)或 128(签名)字节主公钥,实际 ${b.length}`);
71
+ }
72
+ return b;
73
+ }
74
+ /**
75
+ * 解析 `verify` / `encrypt` 的密钥参数:主私钥(32 字节 / PKCS#8 私钥 PEM)
76
+ * 或主公钥(`publicLen` 字节点 / SPKI 公钥 PEM)。
77
+ *
78
+ * 两者的长度区间不重叠(主私钥恒为 32 字节),因此按长度即可判别。
79
+ */
80
+ export function keyArg(input, publicLen, label) {
81
+ if (typeof input === 'string' && input.includes('-----BEGIN')) {
82
+ if (input.includes('BEGIN PUBLIC KEY')) {
83
+ const pub = parseSm9PublicKeyPem(input);
84
+ if (pub.length !== publicLen) {
85
+ throw new InvalidKeyError(`sm9: ${label} 作为 PEM 主公钥应为 ${publicLen} 字节,实际 ${pub.length}`);
86
+ }
87
+ return { kind: 'public', bytes: pub };
88
+ }
89
+ return { kind: 'secret', bytes: masterPrivateBytes(input, label) };
90
+ }
91
+ const b = toBytes(input, label);
92
+ if (b.length === 32)
93
+ return { kind: 'secret', bytes: b };
94
+ if (b.length === publicLen)
95
+ return { kind: 'public', bytes: b };
96
+ throw new InvalidKeyError(`sm9: ${label} 必须是 32 字节主私钥或 ${publicLen} 字节主公钥,实际 ${b.length}`);
97
+ }
98
+ /**
99
+ * 校验字节长度。默认按**密钥支**(`InvalidKeyError`)抛错 —— SM9 各入口的参数绝大多数
100
+ * 是主私钥 / 标量;密文、签名、协议消息的调用点显式传 `'cipher'`。
101
+ */
102
+ export function requireLen(b, n, label, kind = 'key') {
103
+ if (b.length === n)
104
+ return;
105
+ const msg = `sm9: ${label} 必须是 ${n} 字节,实际 ${b.length}`;
106
+ if (kind === 'cipher')
107
+ throw new InvalidCiphertextError(msg);
108
+ throw new InvalidKeyError(msg);
109
+ }
110
+ export function putHex(hex, ptr) {
111
+ mem().set(hexToBytes(hex), ptr);
112
+ }
113
+ export function putBytes(b, ptr) {
114
+ mem().set(b, ptr);
115
+ }
116
+ export function readHex(ptr, len) {
117
+ return bytesToHex(mem().subarray(ptr, ptr + len));
118
+ }
119
+ export function randomRHex() {
120
+ return randomScalarBelow(N).toString(16).padStart(64, '0');
121
+ }
@@ -0,0 +1,48 @@
1
+ /**
2
+ * SM9 密钥封装(KEM,GM/T 0044.4)。
3
+ *
4
+ * 两种封装入口:
5
+ * - `kemEncrypt(ke, id, klen, r?)`:用加密主私钥派生 Ppub-e(既有已发布接口)。
6
+ * - `kemEncapsulateWithMasterPublic(pub, id, klen, r?)`:直接用加密主公钥
7
+ * `[ke]P1`(发送方的典型形态;供 `hybrid.ts` 使用,不改变既有 `kemEncrypt`)。
8
+ *
9
+ * 解封装只有 `kemDecrypt(ke, id, encapsulation, klen)`:必须持有加密主私钥。
10
+ *
11
+ * spec/plan 对应:`docs/superpowers/plans/2026-10-16-sm2-sm9-hybrid-encryption.md`
12
+ * Task 4。
13
+ */
14
+ /** KEM 封装结果。 */
15
+ export interface KemResult {
16
+ /** 会话密钥 K(hex,长度为 `2*klen`)。 */
17
+ key: string;
18
+ /** 封装点 C1(65 字节未压缩 G1 点 hex:`04 || x || y`)。 */
19
+ encapsulation: string;
20
+ }
21
+ /**
22
+ * SM9 密钥封装(GM/T 0044.4):用接收方 id 与其加密主公钥 [ke]P1 封装一个会话密钥。
23
+ *
24
+ * @param ke 32 字节加密主私钥 hex(用于派生主公钥 [ke]P1)
25
+ * @param id 接收方标识
26
+ * @param klen 会话密钥字节长度(默认 32)
27
+ * @param r 32 字节随机数 hex(可选;不传则由宿主 CSPRNG 提供)
28
+ * @returns `{ key, encapsulation }`
29
+ */
30
+ export declare function kemEncrypt(ke: string | Uint8Array, id: string | Uint8Array, klen?: number, r?: string | Uint8Array): KemResult;
31
+ /**
32
+ * 用加密主公钥封装的内部入口(`hybridEncrypt` 使用)。
33
+ *
34
+ * 与 `kemEncrypt` 的区别只在密钥参数:这里不需要 KGC 的加密主私钥。
35
+ *
36
+ * @param masterPublicKey 64 字节加密主公钥 `[ke]P1`(点字节 / SPKI 主公钥 PEM)。
37
+ * @param id 接收方标识。
38
+ * @param klen 会话密钥字节长度(默认 32)。
39
+ * @param r 32 字节随机数 hex(可选)。
40
+ */
41
+ export declare function kemEncapsulateWithMasterPublic(masterPublicKey: string | Uint8Array, id: string | Uint8Array, klen?: number, r?: string | Uint8Array): KemResult;
42
+ /**
43
+ * SM9 密钥解封装:用本端加密主私钥 ke 与 id 从封装点 C1 恢复会话密钥。
44
+ *
45
+ * @param encapsulation 65 字节封装点 C1 hex
46
+ * @returns 会话密钥 hex
47
+ */
48
+ export declare function kemDecrypt(ke: string | Uint8Array, id: string | Uint8Array, encapsulation: string | Uint8Array, klen?: number): string;
@@ -0,0 +1,123 @@
1
+ /**
2
+ * SM9 密钥封装(KEM,GM/T 0044.4)。
3
+ *
4
+ * 两种封装入口:
5
+ * - `kemEncrypt(ke, id, klen, r?)`:用加密主私钥派生 Ppub-e(既有已发布接口)。
6
+ * - `kemEncapsulateWithMasterPublic(pub, id, klen, r?)`:直接用加密主公钥
7
+ * `[ke]P1`(发送方的典型形态;供 `hybrid.ts` 使用,不改变既有 `kemEncrypt`)。
8
+ *
9
+ * 解封装只有 `kemDecrypt(ke, id, encapsulation, klen)`:必须持有加密主私钥。
10
+ *
11
+ * spec/plan 对应:`docs/superpowers/plans/2026-10-16-sm2-sm9-hybrid-encryption.md`
12
+ * Task 4。
13
+ */
14
+ import { DecryptionError, InvalidKeyError } from '../runtime/errors.js';
15
+ import { getModule } from './core.js';
16
+ import { masterPrivateBytes, masterPublicBytes, putBytes, randomRHex, readHex, requireLen, toBytes, } from './input.js';
17
+ function requireKlen(klen) {
18
+ if (!Number.isInteger(klen) || klen <= 0)
19
+ throw new RangeError('sm9: klen 必须为正整数');
20
+ }
21
+ /**
22
+ * SM9 密钥封装(GM/T 0044.4):用接收方 id 与其加密主公钥 [ke]P1 封装一个会话密钥。
23
+ *
24
+ * @param ke 32 字节加密主私钥 hex(用于派生主公钥 [ke]P1)
25
+ * @param id 接收方标识
26
+ * @param klen 会话密钥字节长度(默认 32)
27
+ * @param r 32 字节随机数 hex(可选;不传则由宿主 CSPRNG 提供)
28
+ * @returns `{ key, encapsulation }`
29
+ */
30
+ export function kemEncrypt(ke, id, klen = 32, r) {
31
+ const keB = masterPrivateBytes(ke, 'ke');
32
+ const idB = toBytes(id, 'id');
33
+ const rB = r !== undefined ? toBytes(r, 'r') : toBytes(randomRHex(), 'r');
34
+ requireLen(rB, 32, 'r');
35
+ requireKlen(klen);
36
+ const { exports } = getModule();
37
+ const keP = exports.alloc(32);
38
+ const idP = exports.alloc(idB.length);
39
+ const rP = exports.alloc(32);
40
+ const c1P = exports.alloc(65);
41
+ const kP = exports.alloc(klen);
42
+ try {
43
+ putBytes(keB, keP);
44
+ putBytes(idB, idP);
45
+ putBytes(rB, rP);
46
+ const rc = exports.sm9KemEncryptOut(keP, idP, idB.length, rP, klen, c1P, kP);
47
+ if (rc !== 1)
48
+ throw new Error('sm9: kemEncrypt 失败(K 全 0,需换随机数重试)');
49
+ return { key: readHex(kP, klen), encapsulation: readHex(c1P, 65) };
50
+ }
51
+ finally {
52
+ exports.freeAll();
53
+ }
54
+ }
55
+ /**
56
+ * 用加密主公钥封装的内部入口(`hybridEncrypt` 使用)。
57
+ *
58
+ * 与 `kemEncrypt` 的区别只在密钥参数:这里不需要 KGC 的加密主私钥。
59
+ *
60
+ * @param masterPublicKey 64 字节加密主公钥 `[ke]P1`(点字节 / SPKI 主公钥 PEM)。
61
+ * @param id 接收方标识。
62
+ * @param klen 会话密钥字节长度(默认 32)。
63
+ * @param r 32 字节随机数 hex(可选)。
64
+ */
65
+ export function kemEncapsulateWithMasterPublic(masterPublicKey, id, klen = 32, r) {
66
+ const pub = masterPublicBytes(masterPublicKey, 'masterPublicKey');
67
+ if (pub.length !== 64) {
68
+ throw new InvalidKeyError(`sm9: masterPublicKey 必须是 64 字节加密主公钥,实际 ${pub.length}`);
69
+ }
70
+ const idB = toBytes(id, 'id');
71
+ const rB = r !== undefined ? toBytes(r, 'r') : toBytes(randomRHex(), 'r');
72
+ requireLen(rB, 32, 'r');
73
+ requireKlen(klen);
74
+ const { exports } = getModule();
75
+ const pubP = exports.alloc(64);
76
+ const idP = exports.alloc(idB.length);
77
+ const rP = exports.alloc(32);
78
+ const c1P = exports.alloc(65);
79
+ const kP = exports.alloc(klen);
80
+ try {
81
+ putBytes(pub, pubP);
82
+ putBytes(idB, idP);
83
+ putBytes(rB, rP);
84
+ const rc = exports.sm9KemEncryptPubOut(pubP, idP, idB.length, rP, klen, c1P, kP);
85
+ if (rc !== 1)
86
+ throw new Error('sm9: kemEncapsulate 失败(K 全 0,需换随机数重试)');
87
+ return { key: readHex(kP, klen), encapsulation: readHex(c1P, 65) };
88
+ }
89
+ finally {
90
+ exports.freeAll();
91
+ }
92
+ }
93
+ /**
94
+ * SM9 密钥解封装:用本端加密主私钥 ke 与 id 从封装点 C1 恢复会话密钥。
95
+ *
96
+ * @param encapsulation 65 字节封装点 C1 hex
97
+ * @returns 会话密钥 hex
98
+ */
99
+ export function kemDecrypt(ke, id, encapsulation, klen = 32) {
100
+ const keB = masterPrivateBytes(ke, 'ke');
101
+ const idB = toBytes(id, 'id');
102
+ const c1B = toBytes(encapsulation, 'encapsulation');
103
+ if (c1B.length !== 65)
104
+ throw new RangeError(`sm9: encapsulation 必须是 65 字节,实际 ${c1B.length}`);
105
+ requireKlen(klen);
106
+ const { exports } = getModule();
107
+ const keP = exports.alloc(32);
108
+ const idP = exports.alloc(idB.length);
109
+ const c1P = exports.alloc(65);
110
+ const kP = exports.alloc(klen);
111
+ try {
112
+ putBytes(keB, keP);
113
+ putBytes(idB, idP);
114
+ putBytes(c1B, c1P);
115
+ const rc = exports.sm9KemDecryptOut(keP, idP, idB.length, c1P, klen, kP);
116
+ if (rc !== 1)
117
+ throw new DecryptionError('sm9: kemDecrypt 失败(封装非法 / K 全 0)');
118
+ return readHex(kP, klen);
119
+ }
120
+ finally {
121
+ exports.freeAll();
122
+ }
123
+ }
package/dist/sm9/sm9.wasm CHANGED
Binary file
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "sm-crypto-wasm",
3
- "version": "0.2.1",
3
+ "version": "0.3.0",
4
4
  "description": "国密 SM2/SM3/SM4/SM9/ZUC 的 WASM 实现,Node 18+ 与现代浏览器均可使用,按算法分包懒加载。",
5
5
  "description:en": "SM2/SM3/SM4/SM9/ZUC (China crypto) implemented in AssemblyScript -> WASM. Node 18+ & modern browsers, per-algorithm lazy loading.",
6
6
  "license": "Apache-2.0",