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.
package/dist/sm2/index.js CHANGED
@@ -7,6 +7,8 @@
7
7
  * - `verify(publicKey, message, signature)`:验签
8
8
  * - `encrypt(publicKey, message, options?)`:加密(默认 C1C3C2)
9
9
  * - `decrypt(privateKey, ciphertext)`:解密
10
+ * - `kemEncrypt` / `kemDecrypt`:KEM(用公钥保护随机对称密钥,见 `./kem.ts`)
11
+ * - `hybridEncrypt` / `hybridDecrypt`:KEM + SM4-GCM 混合加密(见 `./hybrid.ts`)
10
12
  *
11
13
  * 说明:
12
14
  * - 密钥输入同时接受裸字节(hex)与 PEM(PKCS#8/SEC1 私钥、SPKI 公钥)。
@@ -478,3 +480,6 @@ function decryptRaw(d, ct) {
478
480
  // SM2 密钥交换协议(GM/T 0003.3-2014):createExchangeInitiator /
479
481
  // createExchangeResponder 由 `./exchange` 提供,在此并入 sm2 命名空间。
480
482
  export * from './exchange.js';
483
+ // SM2 KEM(用公钥保护随机对称密钥)与混合加密(KEM + SM4-GCM)。
484
+ export * from './hybrid.js';
485
+ export * from './kem.js';
@@ -0,0 +1,58 @@
1
+ /**
2
+ * SM2 密钥封装(KEM)—— 用 SM2 公钥保护一把随机对称密钥。
3
+ *
4
+ * **注意:这不是国标定义的“SM2-KEM”。** GM/T 0003 只定义了 SM2 公钥加密,
5
+ * 没有定义独立的 KEM 构造;本模块是业界约定俗成的做法:
6
+ *
7
+ * key = 宿主 CSPRNG 生成的 `klen` 字节对称密钥
8
+ * encapsulation = SM2 加密(key)(完整 C1C3C2 密文,自带 C3 完整性校验)
9
+ *
10
+ * 接收方用 `kemDecrypt` 解出同一把 key。它的安全性完全继承自 SM2 公钥加密:
11
+ * - 每次封装都取新的随机数 `k`(由 `sm2.encrypt` 内部完成);
12
+ * - encapsulation 被篡改时 C3 校验失败,抛 `DecryptionError`;
13
+ * - 错误私钥同样过不了 C3 校验,不会返回垃圾密钥。
14
+ *
15
+ * 若需要“公钥只保护短密钥、数据交给对称算法”的完整用法,直接用
16
+ * `hybridEncrypt` / `hybridDecrypt`(本模块的 KEM + SM4-GCM 组装)。
17
+ *
18
+ * spec/plan 对应:`docs/superpowers/plans/2026-10-16-sm2-sm9-hybrid-encryption.md`
19
+ * Task 1。
20
+ */
21
+ /** KEM 封装结果。 */
22
+ export interface Sm2KemResult {
23
+ /** 会话密钥(hex,`2*klen` 个字符)。 */
24
+ key: string;
25
+ /** SM2 密文(C1C3C2 hex,长度 `97 + klen` 字节)。 */
26
+ encapsulation: string;
27
+ }
28
+ /** `kemDecrypt` 选项。 */
29
+ export interface Sm2KemDecryptOptions {
30
+ /**
31
+ * 解封装失败时返回 `null` 而不抛错。
32
+ *
33
+ * 只覆盖密文支错误(`CiphertextError`:密文结构错 / C3 校验失败);
34
+ * 参数类型错误(`TypeError` / `RangeError`)仍会抛出。
35
+ */
36
+ safeMode?: boolean;
37
+ }
38
+ /**
39
+ * SM2 密钥封装:生成一把随机会话密钥,并用接收方公钥封装。
40
+ *
41
+ * @param publicKey 64 或 65 字节公钥(hex / Uint8Array / PEM)。
42
+ * @param klen 会话密钥字节长度,默认 32。
43
+ * @returns `{ key, encapsulation }`,均为 hex。
44
+ */
45
+ export declare function kemEncrypt(publicKey: string | Uint8Array, klen?: number): Sm2KemResult;
46
+ /**
47
+ * SM2 密钥解封装:从 encapsulation 恢复会话密钥。
48
+ *
49
+ * @param privateKey 32 字节私钥(hex / Uint8Array / PEM)。
50
+ * @param encapsulation `kemEncrypt` 产出的 SM2 密文。
51
+ * @param klen 会话密钥字节长度,默认 32;必须与封装时一致。
52
+ * @returns 会话密钥 hex。
53
+ * @throws {DecryptionError} C3 校验失败、私钥错误,或解出的长度与 `klen` 不符。
54
+ */
55
+ export declare function kemDecrypt(privateKey: string | Uint8Array, encapsulation: string | Uint8Array, klen: number, opts: Sm2KemDecryptOptions & {
56
+ safeMode: true;
57
+ }): string | null;
58
+ export declare function kemDecrypt(privateKey: string | Uint8Array, encapsulation: string | Uint8Array, klen?: number, opts?: Sm2KemDecryptOptions): string;
@@ -0,0 +1,59 @@
1
+ /**
2
+ * SM2 密钥封装(KEM)—— 用 SM2 公钥保护一把随机对称密钥。
3
+ *
4
+ * **注意:这不是国标定义的“SM2-KEM”。** GM/T 0003 只定义了 SM2 公钥加密,
5
+ * 没有定义独立的 KEM 构造;本模块是业界约定俗成的做法:
6
+ *
7
+ * key = 宿主 CSPRNG 生成的 `klen` 字节对称密钥
8
+ * encapsulation = SM2 加密(key)(完整 C1C3C2 密文,自带 C3 完整性校验)
9
+ *
10
+ * 接收方用 `kemDecrypt` 解出同一把 key。它的安全性完全继承自 SM2 公钥加密:
11
+ * - 每次封装都取新的随机数 `k`(由 `sm2.encrypt` 内部完成);
12
+ * - encapsulation 被篡改时 C3 校验失败,抛 `DecryptionError`;
13
+ * - 错误私钥同样过不了 C3 校验,不会返回垃圾密钥。
14
+ *
15
+ * 若需要“公钥只保护短密钥、数据交给对称算法”的完整用法,直接用
16
+ * `hybridEncrypt` / `hybridDecrypt`(本模块的 KEM + SM4-GCM 组装)。
17
+ *
18
+ * spec/plan 对应:`docs/superpowers/plans/2026-10-16-sm2-sm9-hybrid-encryption.md`
19
+ * Task 1。
20
+ */
21
+ import { bytesToHex } from '../runtime/convert.js';
22
+ import { CiphertextError, DecryptionError } from '../runtime/errors.js';
23
+ import { randomBytes } from '../runtime/random.js';
24
+ import { decrypt, encrypt } from './index.js';
25
+ /** `klen` 必须是正整数,且不超过宿主 CSPRNG 单次取数上限(65536)。 */
26
+ function requireKlen(klen) {
27
+ if (!Number.isInteger(klen) || klen <= 0 || klen > 65_536) {
28
+ throw new RangeError(`sm2.kemEncrypt: klen 必须是 [1, 65536] 内的整数,实际 ${klen}`);
29
+ }
30
+ }
31
+ /**
32
+ * SM2 密钥封装:生成一把随机会话密钥,并用接收方公钥封装。
33
+ *
34
+ * @param publicKey 64 或 65 字节公钥(hex / Uint8Array / PEM)。
35
+ * @param klen 会话密钥字节长度,默认 32。
36
+ * @returns `{ key, encapsulation }`,均为 hex。
37
+ */
38
+ export function kemEncrypt(publicKey, klen = 32) {
39
+ requireKlen(klen);
40
+ const key = randomBytes(klen);
41
+ const encapsulation = encrypt(publicKey, key);
42
+ return { key: bytesToHex(key), encapsulation };
43
+ }
44
+ export function kemDecrypt(privateKey, encapsulation, klen = 32, opts = {}) {
45
+ requireKlen(klen);
46
+ try {
47
+ const key = decrypt(privateKey, encapsulation);
48
+ if (key.length !== klen * 2) {
49
+ // C3 已通过,说明私钥正确;长度不符通常是调用方把 klen 传错了。
50
+ throw new DecryptionError(`sm2.kemDecrypt: 解出的密钥长度为 ${key.length / 2} 字节,与 klen=${klen} 不符`);
51
+ }
52
+ return key;
53
+ }
54
+ catch (err) {
55
+ if (opts.safeMode && err instanceof CiphertextError)
56
+ return null;
57
+ throw err;
58
+ }
59
+ }
@@ -0,0 +1,48 @@
1
+ /**
2
+ * SM9 WASM 模块的共享访问层。
3
+ *
4
+ * 把 `ensureLoaded` / `getModule` / 内存视图从业务 API 中拆出来,供
5
+ * `index.ts`、`kem.ts`、`hybrid.ts` 共用,避免模块间循环依赖。
6
+ *
7
+ * spec/plan 对应:`docs/superpowers/plans/2026-10-16-sm2-sm9-hybrid-encryption.md`。
8
+ */
9
+ /** SM9 曲线阶 n。 */
10
+ export declare const N: bigint;
11
+ /** WASM 导出的最小子集。诊断入口的子集。 */
12
+ export interface Sm9Exports extends WebAssembly.Exports {
13
+ readonly alloc: (n: number) => number;
14
+ readonly freeAll: () => void;
15
+ readonly signPubOut: (ksPtr: number, outPtr: number) => void;
16
+ readonly encPubOut: (kePtr: number, outPtr: number) => void;
17
+ readonly signDsOut: (ksPtr: number, idPtr: number, idLen: number, outPtr: number) => void;
18
+ readonly encDeOut: (kePtr: number, idPtr: number, idLen: number, outPtr: number) => void;
19
+ readonly sm9VerifyPubOut: (pubPtr: number, idPtr: number, idLen: number, msgPtr: number, msgLen: number, sigPtr: number) => number;
20
+ readonly sm9EncryptPubOut: (pubPtr: number, idPtr: number, idLen: number, msgPtr: number, msgLen: number, rPtr: number, outPtr: number, outCap: number) => number;
21
+ readonly sm9UserEncPubOut: (pubPtr: number, idPtr: number, idLen: number, outPtr: number) => void;
22
+ readonly sm9UserSignPubOut: (pubPtr: number, idPtr: number, idLen: number, outPtr: number) => void;
23
+ readonly sm9SignOut: (ksPtr: number, idPtr: number, idLen: number, msgPtr: number, msgLen: number, rPtr: number, outPtr: number) => void;
24
+ readonly sm9VerifyOut: (ksPtr: number, idPtr: number, idLen: number, msgPtr: number, msgLen: number, sigPtr: number) => number;
25
+ readonly sm9EncryptOut: (kePtr: number, idPtr: number, idLen: number, msgPtr: number, msgLen: number, rPtr: number, outPtr: number, outCap: number) => number;
26
+ readonly sm9DecryptOut: (kePtr: number, idPtr: number, idLen: number, ctPtr: number, ctLen: number, outPtr: number) => number;
27
+ readonly sm9KemEncryptOut: (kePtr: number, idPtr: number, idLen: number, rPtr: number, klen: number, c1Ptr: number, kPtr: number) => number;
28
+ /** 用加密主公钥(G1 仿射 64B)做 KEM 封装。 */
29
+ readonly sm9KemEncryptPubOut: (pubPtr: number, idPtr: number, idLen: number, rPtr: number, klen: number, c1Ptr: number, kPtr: number) => number;
30
+ readonly sm9KemDecryptOut: (kePtr: number, idPtr: number, idLen: number, c1Ptr: number, klen: number, kPtr: number) => number;
31
+ readonly sm9ExchEphemeralOut: (kePtr: number, peerIdPtr: number, peerIdLen: number, rPtr: number, outPtr: number) => void;
32
+ readonly sm9ExchKeyOut: (kePtr: number, isInitiator: number, selfIdPtr: number, selfIdLen: number, peerIdPtr: number, peerIdLen: number, rPtr: number, selfRPtr: number, peerRPtr: number, klen: number, outPtr: number) => number;
33
+ readonly sm9ExchConfirmOut: (kePtr: number, isInitiator: number, selfIdPtr: number, selfIdLen: number, peerIdPtr: number, peerIdLen: number, rPtr: number, selfRPtr: number, peerRPtr: number, prefix: number, outPtr: number) => void;
34
+ readonly sm9ExchAllOut: (kePtr: number, isInitiator: number, selfIdPtr: number, selfIdLen: number, peerIdPtr: number, peerIdLen: number, rPtr: number, selfRPtr: number, peerRPtr: number, klen: number, saPtr: number, sbPtr: number, kPtr: number) => number;
35
+ /** 诊断:cyclotomic 平方自测(随机子群元素上 cyc 平方 vs 通用平方)。1=一致。 */
36
+ readonly sqrCycSelfTestOut: (seed: number) => number;
37
+ readonly memory: WebAssembly.Memory;
38
+ }
39
+ export interface Sm9Module {
40
+ exports: Sm9Exports;
41
+ memory: WebAssembly.Memory;
42
+ }
43
+ /** 预热 WASM 模块。 */
44
+ export declare function ensureLoaded(): Promise<void>;
45
+ /** 取已加载的模块;未预热时抛错(调用方应先 `await ensureLoaded()`)。 */
46
+ export declare function getModule(): Sm9Module;
47
+ /** WASM 线性内存视图(每次现取,避免 memory.grow 后旧视图失效)。 */
48
+ export declare function mem(): Uint8Array;
@@ -0,0 +1,32 @@
1
+ /**
2
+ * SM9 WASM 模块的共享访问层。
3
+ *
4
+ * 把 `ensureLoaded` / `getModule` / 内存视图从业务 API 中拆出来,供
5
+ * `index.ts`、`kem.ts`、`hybrid.ts` 共用,避免模块间循环依赖。
6
+ *
7
+ * spec/plan 对应:`docs/superpowers/plans/2026-10-16-sm2-sm9-hybrid-encryption.md`。
8
+ */
9
+ import { loadWasm } from '../runtime/loadWasm.js';
10
+ /** SM9 曲线阶 n。 */
11
+ export const N = BigInt('0xb640000002a3a6f1d603ab4ff58ec74449f2934b18ea8beee56ee19cd69ecf25');
12
+ /** 预热 WASM 模块。 */
13
+ export async function ensureLoaded() {
14
+ if (globalThis.__sm9Wasm)
15
+ return;
16
+ const mod = await loadWasm('sm9');
17
+ globalThis.__sm9Wasm = {
18
+ exports: mod.exports,
19
+ memory: mod.memory,
20
+ };
21
+ }
22
+ /** 取已加载的模块;未预热时抛错(调用方应先 `await ensureLoaded()`)。 */
23
+ export function getModule() {
24
+ const m = globalThis.__sm9Wasm;
25
+ if (!m)
26
+ throw new Error('sm9: 未初始化,请先 `await ensureLoaded()`。');
27
+ return m;
28
+ }
29
+ /** WASM 线性内存视图(每次现取,避免 memory.grow 后旧视图失效)。 */
30
+ export function mem() {
31
+ return new Uint8Array(getModule().memory.buffer);
32
+ }
@@ -0,0 +1,69 @@
1
+ /**
2
+ * SM9 混合加密(KEM + DEM):主公钥只保护一把短密钥,消息交给 SM4-GCM。
3
+ *
4
+ * 流程:
5
+ * ```
6
+ * { key, encapsulation } = KEM(masterPublicKey 或 masterPrivateKey, id, 16)
7
+ * { ct, tag } = SM4-GCM(key, iv, msg, aad = encapsulation)
8
+ * sealed = version || klen || encapLen || encapsulation
9
+ * || iv || tag || ct
10
+ * ```
11
+ *
12
+ * 与 `sm9.encrypt` 一致,第一参数既接受**加密主公钥**(64 字节 / SPKI PEM),
13
+ * 也接受**加密主私钥**(32 字节 / PKCS#8 PEM);前者是发送方的典型形态。
14
+ *
15
+ * 本模块同时用到 `sm9.wasm` 与 `sm4.wasm`:首次调用前请分别
16
+ * `await sm9.ensureLoaded()` 与 `await sm4.ensureLoaded()`。
17
+ *
18
+ * 完整性边界:SM9 KEM 的 encapsulation 只有 C1(65 字节),本身没有 C3/HMAC;
19
+ * 错误 id / 错误主公钥会得到不同的 K,最终由 GCM tag 认证失败暴露。因此
20
+ * `hybridDecrypt` 对错误 id 抛的是 GCM 的 `DecryptionError`,而不是 KEM 错误。
21
+ *
22
+ * spec/plan 对应:`docs/superpowers/plans/2026-10-16-sm2-sm9-hybrid-encryption.md`
23
+ * Task 4。
24
+ */
25
+ import { sealedFromObject, sealedToObject } from '../common/sealed.js';
26
+ export { sealedFromObject, sealedToObject };
27
+ /** `hybridEncrypt` 选项。 */
28
+ export interface Sm9HybridEncryptOptions {
29
+ /**
30
+ * 显式指定 GCM IV(12 字节 hex / Uint8Array)。
31
+ *
32
+ * 默认由宿主 CSPRNG 生成。**显式复用同一个 IV 配不同消息会破坏 GCM 的机密性**,
33
+ * 该参数只用于测试 / 协议互操作;正常调用不要传。
34
+ */
35
+ iv?: string | Uint8Array;
36
+ }
37
+ /** `hybridDecrypt` 选项。 */
38
+ export interface Sm9HybridDecryptOptions {
39
+ /**
40
+ * 解密失败时返回 `null` 而不抛错。
41
+ *
42
+ * 只覆盖密文支错误(`CiphertextError`:sealed 结构错、GCM tag 校验失败);
43
+ * 参数类型错误 / 密钥格式错误仍会抛出。
44
+ */
45
+ safeMode?: boolean;
46
+ }
47
+ /**
48
+ * SM9 混合加密。
49
+ *
50
+ * @param key 加密主公钥(64 字节 / SPKI PEM)或加密主私钥(32 字节 / PKCS#8 PEM)。
51
+ * @param id 接收方标识。
52
+ * @param message 明文(hex / Uint8Array;空消息传 `new Uint8Array(0)`)。
53
+ * @param opts `iv` 可选,默认随机 12 字节。
54
+ * @returns sealed hex(版本化,与 SM2 hybrid 同一布局)。
55
+ */
56
+ export declare function hybridEncrypt(key: string | Uint8Array, id: string | Uint8Array, message: string | Uint8Array, opts?: Sm9HybridEncryptOptions): string;
57
+ /**
58
+ * SM9 混合解密。
59
+ *
60
+ * @param ke 加密主私钥(32 字节 / PKCS#8 PEM)。
61
+ * @param id 接收方标识;必须与封装时一致。
62
+ * @param sealed `hybridEncrypt` 的返回值。
63
+ * @param opts `safeMode`:失败时返回 `null`。
64
+ * @returns 明文 hex。
65
+ */
66
+ export declare function hybridDecrypt(ke: string | Uint8Array, id: string | Uint8Array, sealed: string | Uint8Array, opts: Sm9HybridDecryptOptions & {
67
+ safeMode: true;
68
+ }): string | null;
69
+ export declare function hybridDecrypt(ke: string | Uint8Array, id: string | Uint8Array, sealed: string | Uint8Array, opts?: Sm9HybridDecryptOptions): string;
@@ -0,0 +1,80 @@
1
+ /**
2
+ * SM9 混合加密(KEM + DEM):主公钥只保护一把短密钥,消息交给 SM4-GCM。
3
+ *
4
+ * 流程:
5
+ * ```
6
+ * { key, encapsulation } = KEM(masterPublicKey 或 masterPrivateKey, id, 16)
7
+ * { ct, tag } = SM4-GCM(key, iv, msg, aad = encapsulation)
8
+ * sealed = version || klen || encapLen || encapsulation
9
+ * || iv || tag || ct
10
+ * ```
11
+ *
12
+ * 与 `sm9.encrypt` 一致,第一参数既接受**加密主公钥**(64 字节 / SPKI PEM),
13
+ * 也接受**加密主私钥**(32 字节 / PKCS#8 PEM);前者是发送方的典型形态。
14
+ *
15
+ * 本模块同时用到 `sm9.wasm` 与 `sm4.wasm`:首次调用前请分别
16
+ * `await sm9.ensureLoaded()` 与 `await sm4.ensureLoaded()`。
17
+ *
18
+ * 完整性边界:SM9 KEM 的 encapsulation 只有 C1(65 字节),本身没有 C3/HMAC;
19
+ * 错误 id / 错误主公钥会得到不同的 K,最终由 GCM tag 认证失败暴露。因此
20
+ * `hybridDecrypt` 对错误 id 抛的是 GCM 的 `DecryptionError`,而不是 KEM 错误。
21
+ *
22
+ * spec/plan 对应:`docs/superpowers/plans/2026-10-16-sm2-sm9-hybrid-encryption.md`
23
+ * Task 4。
24
+ */
25
+ import { resolveIv, toMessageBytes } from '../common/hybrid.js';
26
+ import { DEM_KEY_LEN, decodeSealed, encodeSealed, SEALED_VERSION, sealedFromObject, sealedToObject, } from '../common/sealed.js';
27
+ import { bytesToHex, hexToBytes } from '../runtime/convert.js';
28
+ import { CiphertextError, InvalidCiphertextError } from '../runtime/errors.js';
29
+ import { decryptGCM, encryptGCM } from '../sm4/index.js';
30
+ import { keyArg, toBytes } from './input.js';
31
+ import { kemDecrypt, kemEncapsulateWithMasterPublic, kemEncrypt } from './kem.js';
32
+ export { sealedFromObject, sealedToObject };
33
+ /**
34
+ * SM9 混合加密。
35
+ *
36
+ * @param key 加密主公钥(64 字节 / SPKI PEM)或加密主私钥(32 字节 / PKCS#8 PEM)。
37
+ * @param id 接收方标识。
38
+ * @param message 明文(hex / Uint8Array;空消息传 `new Uint8Array(0)`)。
39
+ * @param opts `iv` 可选,默认随机 12 字节。
40
+ * @returns sealed hex(版本化,与 SM2 hybrid 同一布局)。
41
+ */
42
+ export function hybridEncrypt(key, id, message, opts = {}) {
43
+ const k = keyArg(key, 64, 'key');
44
+ const idB = toBytes(id, 'id');
45
+ const msg = toMessageBytes(message, 'message');
46
+ const iv = resolveIv(opts.iv);
47
+ // DEK 固定为 SM4-128 的 16 字节;封装方不需要 KGC 的加密主私钥。
48
+ const kem = k.kind === 'public'
49
+ ? kemEncapsulateWithMasterPublic(k.bytes, idB, DEM_KEY_LEN)
50
+ : kemEncrypt(k.bytes, idB, DEM_KEY_LEN);
51
+ const enc = hexToBytes(kem.encapsulation, 'encapsulation');
52
+ const { ct, tag } = encryptGCM(kem.key, iv, msg, enc);
53
+ return bytesToHex(encodeSealed({
54
+ version: SEALED_VERSION,
55
+ klen: DEM_KEY_LEN,
56
+ encapsulation: enc,
57
+ iv,
58
+ tag: hexToBytes(tag, 'tag'),
59
+ ct: ct.length === 0 ? new Uint8Array(0) : hexToBytes(ct, 'ct'),
60
+ }));
61
+ }
62
+ export function hybridDecrypt(ke, id, sealed, opts = {}) {
63
+ try {
64
+ const parts = decodeSealed(sealed);
65
+ if (parts.klen !== DEM_KEY_LEN) {
66
+ throw new InvalidCiphertextError(`sm9.hybridDecrypt: sealed.klen=${parts.klen},当前版本只支持 ${DEM_KEY_LEN}`);
67
+ }
68
+ if (parts.encapsulation.length !== 65) {
69
+ throw new InvalidCiphertextError(`sm9.hybridDecrypt: encapsulation 必须是 65 字节,实际 ${parts.encapsulation.length}`);
70
+ }
71
+ // KEM 只算 K;错误 id 不会在这里报错,由下面的 GCM tag 兜底。
72
+ const key = kemDecrypt(ke, id, parts.encapsulation, parts.klen);
73
+ return decryptGCM(key, parts.iv, parts.ct, parts.tag, { aad: parts.encapsulation });
74
+ }
75
+ catch (err) {
76
+ if (opts.safeMode && err instanceof CiphertextError)
77
+ return null;
78
+ throw err;
79
+ }
80
+ }
@@ -9,6 +9,8 @@
9
9
  * - `verify(ks, id, msg, sig)`:SM9 验签,通过返回 true
10
10
  * - `encrypt(ke, id, msg, r?)`:SM9 加密,输出 C1||C3||C2 hex(C1=65B, C3=32B, C2=|msg|)
11
11
  * - `decrypt(ke, id, ct)`:SM9 解密,输出明文 hex;C3 HMAC 校验失败抛错
12
+ * - `kemEncrypt` / `kemDecrypt`:KEM(GM/T 0044.4,见 `./kem.ts`)
13
+ * - `hybridEncrypt` / `hybridDecrypt`:KEM + SM4-GCM 混合加密(见 `./hybrid.ts`)
12
14
  *
13
15
  * 输入/输出 hex 全部不带 0x 前缀。
14
16
  * r 不传时由宿主 CSPRNG 提供(Node: crypto.randomBytes / 浏览器: crypto.getRandomValues)。
@@ -22,8 +24,8 @@
22
24
  *
23
25
  * spec/plan 对应:plan Task 10;spec §6 API、§12.1 Q2(同步优先)、Q3(PKCS#8 + SM9 OID)。
24
26
  */
25
- /** 预热 WASM 模块。 */
26
- export declare function ensureLoaded(): Promise<void>;
27
+ import { ensureLoaded } from './core.js';
28
+ export { ensureLoaded };
27
29
  /** SM9 主密钥用途。 */
28
30
  export type Sm9KeyPurpose = 'sign' | 'enc';
29
31
  /** `generateKeyPair` 选项。 */
@@ -125,30 +127,7 @@ export declare function decrypt(ke: string | Uint8Array, id: string | Uint8Array
125
127
  safeMode: true;
126
128
  }): string | null;
127
129
  export declare function decrypt(ke: string | Uint8Array, id: string | Uint8Array, ct: string | Uint8Array, opts?: Sm9DecryptOptions): string;
128
- /** KEM 封装结果。 */
129
- export interface KemResult {
130
- /** 会话密钥 K(hex,长度为 `2*klen`)。 */
131
- key: string;
132
- /** 封装点 C1(65 字节未压缩 G1 点 hex:`04 || x || y`)。 */
133
- encapsulation: string;
134
- }
135
- /**
136
- * SM9 密钥封装(GM/T 0044.4):用接收方 id 与其加密主公钥 [ke]P1 封装一个会话密钥。
137
- *
138
- * @param ke 32 字节加密主私钥 hex(用于派生主公钥 [ke]P1)
139
- * @param id 接收方标识
140
- * @param klen 会话密钥字节长度(默认 32)
141
- * @param r 32 字节随机数 hex(可选;不传则由宿主 CSPRNG 提供)
142
- * @returns `{ key, encapsulation }`
143
- */
144
- export declare function kemEncrypt(ke: string | Uint8Array, id: string | Uint8Array, klen?: number, r?: string | Uint8Array): KemResult;
145
- /**
146
- * SM9 密钥解封装:用本端加密主私钥 ke 与 id 从封装点 C1 恢复会话密钥。
147
- *
148
- * @param encapsulation 65 字节封装点 C1 hex
149
- * @returns 会话密钥 hex
150
- */
151
- export declare function kemDecrypt(ke: string | Uint8Array, id: string | Uint8Array, encapsulation: string | Uint8Array, klen?: number): string;
130
+ export { type KemResult, kemDecrypt, kemEncrypt } from './kem.js';
152
131
  /** 密钥交换端点配置。 */
153
132
  export interface Sm9ExchangeOptions {
154
133
  /** 会话密钥字节长度(默认 32)。 */
@@ -193,3 +172,4 @@ export declare function createExchangeInitiator(ke: string | Uint8Array, selfId:
193
172
  * @param peerId 对端(A)标识 ID_A
194
173
  */
195
174
  export declare function createExchangeResponder(ke: string | Uint8Array, selfId: string | Uint8Array, peerId: string | Uint8Array, options?: Sm9ExchangeOptions): Promise<Sm9KeyExchangeResponder>;
175
+ export * from './hybrid.js';
package/dist/sm9/index.js CHANGED
@@ -9,6 +9,8 @@
9
9
  * - `verify(ks, id, msg, sig)`:SM9 验签,通过返回 true
10
10
  * - `encrypt(ke, id, msg, r?)`:SM9 加密,输出 C1||C3||C2 hex(C1=65B, C3=32B, C2=|msg|)
11
11
  * - `decrypt(ke, id, ct)`:SM9 解密,输出明文 hex;C3 HMAC 校验失败抛错
12
+ * - `kemEncrypt` / `kemDecrypt`:KEM(GM/T 0044.4,见 `./kem.ts`)
13
+ * - `hybridEncrypt` / `hybridDecrypt`:KEM + SM4-GCM 混合加密(见 `./hybrid.ts`)
12
14
  *
13
15
  * 输入/输出 hex 全部不带 0x 前缀。
14
16
  * r 不传时由宿主 CSPRNG 提供(Node: crypto.randomBytes / 浏览器: crypto.getRandomValues)。
@@ -22,152 +24,12 @@
22
24
  *
23
25
  * spec/plan 对应:plan Task 10;spec §6 API、§12.1 Q2(同步优先)、Q3(PKCS#8 + SM9 OID)。
24
26
  */
25
- import { encodeSm9PrivateKeyPem, encodeSm9PublicKeyPem, parseSm9PrivateKeyPem, parseSm9PublicKeyPem, } from '../pem/sm9.js';
27
+ import { encodeSm9PrivateKeyPem, encodeSm9PublicKeyPem } from '../pem/sm9.js';
26
28
  import { bytesToHex, hexToBytes } from '../runtime/convert.js';
27
- import { CiphertextError, DecryptionError, InvalidCiphertextError, InvalidKeyError, } from '../runtime/errors.js';
28
- import { loadWasm } from '../runtime/loadWasm.js';
29
- import { randomScalarBelow } from '../runtime/random.js';
30
- /** SM9 曲线阶 n。 */
31
- const N = BigInt('0xb640000002a3a6f1d603ab4ff58ec74449f2934b18ea8beee56ee19cd69ecf25');
32
- /** 预热 WASM 模块。 */
33
- export async function ensureLoaded() {
34
- if (globalThis.__sm9Wasm)
35
- return;
36
- const mod = await loadWasm('sm9');
37
- globalThis.__sm9Wasm = {
38
- exports: mod.exports,
39
- memory: mod.memory,
40
- };
41
- }
42
- function getModule() {
43
- const m = globalThis.__sm9Wasm;
44
- if (!m)
45
- throw new Error('sm9: 未初始化,请先 `await ensureLoaded()`。');
46
- return m;
47
- }
48
- // ---------------- 工具 ----------------
49
- /** 任意输入 → Uint8Array。
50
- * - Uint8Array: 拷一份
51
- * - string 且看起来是 hex(偶数长度 + 全部 0-9a-fA-F):按 hex 解
52
- * - 其他 string:按 UTF-8 编码(用于 id、msg 等人类可读输入)
53
- * 失败抛 TypeError。 */
54
- /**
55
- * 通用输入归一化:Uint8Array 拷贝、hex 解码、其它按 UTF-8。
56
- *
57
- * **刻意不做 PEM 嗅探** —— PEM 只可能出现在密钥参数上,由 `masterPrivateBytes`
58
- * 显式处理;这样 id / msg 里出现 `-----BEGIN` 也不会被误吞。
59
- */
60
- function toBytes(input, label) {
61
- if (input instanceof Uint8Array)
62
- return new Uint8Array(input);
63
- if (typeof input !== 'string')
64
- throw new TypeError(`sm9: ${label} 必须是字符串或 Uint8Array`);
65
- if (input.startsWith('0x') || /^[0-9a-fA-F]+$/.test(input)) {
66
- const s = input.startsWith('0x') ? input.slice(2) : input;
67
- if (s.length % 2 !== 0)
68
- throw new TypeError(`sm9: ${label} hex 长度必须为偶数`);
69
- return hexToBytes(s, label);
70
- }
71
- return new TextEncoder().encode(input);
72
- }
73
- /**
74
- * 主私钥参数归一化:接受 32 字节(hex / Uint8Array)或 PKCS#8 私钥 PEM
75
- * (spec §12.1 Q3,算法 OID `1.2.156.10197.1.100`)。
76
- */
77
- function masterPrivateBytes(input, label) {
78
- let bytes;
79
- if (typeof input === 'string' && input.includes('-----BEGIN')) {
80
- const parsed = parseSm9PrivateKeyPem(input);
81
- if (parsed.length !== 32) {
82
- throw new InvalidKeyError(`sm9: ${label} 作为 PEM 主私钥应为 32 字节,实际 ${parsed.length}`);
83
- }
84
- bytes = parsed;
85
- }
86
- else {
87
- const b = toBytes(input, label);
88
- if (b.length !== 32) {
89
- throw new InvalidKeyError(`sm9: ${label} 必须是 32 字节主私钥,实际 ${b.length}`);
90
- }
91
- bytes = b;
92
- }
93
- // 标量范围:SM9(GM/T 0044)要求 1 ≤ k ≤ n−1。
94
- // 越界值不会崩,但 wasm 侧的 addModN → modAdd 只做一次条件减、要求输入已
95
- // 约化(h1 + k < 2n),k ≥ n 时 k + h1 可能 ≥ 2n 而静默产出错值,故在此显式拒绝。
96
- const k = BigInt(`0x${bytesToHex(bytes)}`);
97
- if (k < 1n || k >= N) {
98
- throw new InvalidKeyError(`sm9: ${label} 必须在 [1, n−1] 范围内(SM9 主私钥标量)`);
99
- }
100
- return bytes;
101
- }
102
- /** 主公钥参数归一化:64(加密 G1)或 128(签名 G2)字节点,或 SPKI 主公钥 PEM。 */
103
- function masterPublicBytes(input, label) {
104
- if (typeof input === 'string' && input.includes('-----BEGIN')) {
105
- const pub = parseSm9PublicKeyPem(input);
106
- if (pub.length !== 64 && pub.length !== 128) {
107
- throw new InvalidKeyError(`sm9: ${label} 作为 PEM 主公钥必须是 64 或 128 字节,实际 ${pub.length}`);
108
- }
109
- return pub;
110
- }
111
- const b = toBytes(input, label);
112
- if (b.length !== 64 && b.length !== 128) {
113
- throw new InvalidKeyError(`sm9: ${label} 必须是 64(加密)或 128(签名)字节主公钥,实际 ${b.length}`);
114
- }
115
- return b;
116
- }
117
- /**
118
- * 解析 `verify` / `encrypt` 的密钥参数:主私钥(32 字节 / PKCS#8 私钥 PEM)
119
- * 或主公钥(`publicLen` 字节点 / SPKI 公钥 PEM)。
120
- *
121
- * 两者的长度区间不重叠(主私钥恒为 32 字节),因此按长度即可判别。
122
- */
123
- function keyArg(input, publicLen, label) {
124
- if (typeof input === 'string' && input.includes('-----BEGIN')) {
125
- if (input.includes('BEGIN PUBLIC KEY')) {
126
- const pub = parseSm9PublicKeyPem(input);
127
- if (pub.length !== publicLen) {
128
- throw new InvalidKeyError(`sm9: ${label} 作为 PEM 主公钥应为 ${publicLen} 字节,实际 ${pub.length}`);
129
- }
130
- return { kind: 'public', bytes: pub };
131
- }
132
- return { kind: 'secret', bytes: masterPrivateBytes(input, label) };
133
- }
134
- const b = toBytes(input, label);
135
- if (b.length === 32)
136
- return { kind: 'secret', bytes: b };
137
- if (b.length === publicLen)
138
- return { kind: 'public', bytes: b };
139
- throw new InvalidKeyError(`sm9: ${label} 必须是 32 字节主私钥或 ${publicLen} 字节主公钥,实际 ${b.length}`);
140
- }
141
- /**
142
- * 校验字节长度。默认按**密钥支**(`InvalidKeyError`)抛错 —— SM9 各入口的参数绝大多数
143
- * 是主私钥 / 标量;密文、签名、协议消息的调用点显式传 `'cipher'`。
144
- */
145
- function requireLen(b, n, label, kind = 'key') {
146
- if (b.length === n)
147
- return;
148
- const msg = `sm9: ${label} 必须是 ${n} 字节,实际 ${b.length}`;
149
- if (kind === 'cipher')
150
- throw new InvalidCiphertextError(msg);
151
- throw new InvalidKeyError(msg);
152
- }
153
- function mem() {
154
- return new Uint8Array(getModule().memory.buffer);
155
- }
156
- function _allocBytes(n) {
157
- return getModule().exports.alloc(n);
158
- }
159
- function putHex(hex, ptr) {
160
- mem().set(hexToBytes(hex), ptr);
161
- }
162
- function putBytes(b, ptr) {
163
- mem().set(b, ptr);
164
- }
165
- function readHex(ptr, len) {
166
- return bytesToHex(mem().subarray(ptr, ptr + len));
167
- }
168
- function randomRHex() {
169
- return randomScalarBelow(N).toString(16).padStart(64, '0');
170
- }
29
+ import { CiphertextError, DecryptionError, InvalidCiphertextError } from '../runtime/errors.js';
30
+ import { ensureLoaded, getModule, mem } from './core.js';
31
+ import { keyArg, masterPrivateBytes, masterPublicBytes, putBytes, putHex, randomRHex, readHex, requireLen, toBytes, } from './input.js';
32
+ export { ensureLoaded };
171
33
  /**
172
34
  * 生成 SM9 主密钥对与对应用户私钥(spec §6、§12.1 Q3)。
173
35
  *
@@ -443,73 +305,8 @@ function decryptUnsafe(ke, id, ct) {
443
305
  exports.freeAll();
444
306
  }
445
307
  }
446
- /**
447
- * SM9 密钥封装(GM/T 0044.4):用接收方 id 与其加密主公钥 [ke]P1 封装一个会话密钥。
448
- *
449
- * @param ke 32 字节加密主私钥 hex(用于派生主公钥 [ke]P1)
450
- * @param id 接收方标识
451
- * @param klen 会话密钥字节长度(默认 32)
452
- * @param r 32 字节随机数 hex(可选;不传则由宿主 CSPRNG 提供)
453
- * @returns `{ key, encapsulation }`
454
- */
455
- export function kemEncrypt(ke, id, klen = 32, r) {
456
- const keB = masterPrivateBytes(ke, 'ke');
457
- const idB = toBytes(id, 'id');
458
- const rB = r !== undefined ? toBytes(r, 'r') : toBytes(randomRHex(), 'r');
459
- requireLen(rB, 32, 'r');
460
- if (!Number.isInteger(klen) || klen <= 0)
461
- throw new RangeError('sm9: klen 必须为正整数');
462
- const { exports } = getModule();
463
- const keP = exports.alloc(32);
464
- const idP = exports.alloc(idB.length);
465
- const rP = exports.alloc(32);
466
- const c1P = exports.alloc(65);
467
- const kP = exports.alloc(klen);
468
- try {
469
- putBytes(keB, keP);
470
- putBytes(idB, idP);
471
- putBytes(rB, rP);
472
- const rc = exports.sm9KemEncryptOut(keP, idP, idB.length, rP, klen, c1P, kP);
473
- if (rc !== 1)
474
- throw new Error('sm9: kemEncrypt 失败(K 全 0,需换随机数重试)');
475
- return { key: readHex(kP, klen), encapsulation: readHex(c1P, 65) };
476
- }
477
- finally {
478
- exports.freeAll();
479
- }
480
- }
481
- /**
482
- * SM9 密钥解封装:用本端加密主私钥 ke 与 id 从封装点 C1 恢复会话密钥。
483
- *
484
- * @param encapsulation 65 字节封装点 C1 hex
485
- * @returns 会话密钥 hex
486
- */
487
- export function kemDecrypt(ke, id, encapsulation, klen = 32) {
488
- const keB = masterPrivateBytes(ke, 'ke');
489
- const idB = toBytes(id, 'id');
490
- const c1B = toBytes(encapsulation, 'encapsulation');
491
- if (c1B.length !== 65)
492
- throw new RangeError(`sm9: encapsulation 必须是 65 字节,实际 ${c1B.length}`);
493
- if (!Number.isInteger(klen) || klen <= 0)
494
- throw new RangeError('sm9: klen 必须为正整数');
495
- const { exports } = getModule();
496
- const keP = exports.alloc(32);
497
- const idP = exports.alloc(idB.length);
498
- const c1P = exports.alloc(65);
499
- const kP = exports.alloc(klen);
500
- try {
501
- putBytes(keB, keP);
502
- putBytes(idB, idP);
503
- putBytes(c1B, c1P);
504
- const rc = exports.sm9KemDecryptOut(keP, idP, idB.length, c1P, klen, kP);
505
- if (rc !== 1)
506
- throw new DecryptionError('sm9: kemDecrypt 失败(封装非法 / K 全 0)');
507
- return readHex(kP, klen);
508
- }
509
- finally {
510
- exports.freeAll();
511
- }
512
- }
308
+ // KEM 实现拆到 ./kem.ts,供 hybrid.ts 复用且避免循环依赖。
309
+ export { kemDecrypt, kemEncrypt } from './kem.js';
513
310
  function ctEq(a, b) {
514
311
  if (a.length !== b.length)
515
312
  return false;
@@ -678,3 +475,5 @@ export async function createExchangeResponder(ke, selfId, peerId, options = {})
678
475
  },
679
476
  };
680
477
  }
478
+ // SM9 混合加密(KEM + SM4-GCM)。
479
+ export * from './hybrid.js';