secure-crypto-top-sdk
v0.1.0
Published
可插拔多算法 + 多协议(自定义 / TOP 风格)端到端加密 SDK,AES-GCM/CBC、HMAC/MD5/SHA、SM3/SM4,RSA-OAEP 混合加密,Fastify 集成
Maintainers
Readme
🔐 secure-crypto-top-sdk
可插拔多算法 + 多协议(自定义 / TOP 风格)端到端加密 SDK AES-GCM/CBC · SM4 · SM3 · HMAC · RSA-OAEP 混合加密 · Fastify 集成
✨ 特性
| 能力 | 说明 |
|---|---|
| 多算法可插拔 | aes-256-gcm、aes-256-cbc、aes-128-cbc、sm4-cbc、rsa-oaep-aes-256-gcm |
| 多签名算法 | hmac-sha256、hmac-sha512、md5、sha256、sm3 |
| 多协议并存 | custom(自家信封) + top(TOP 风格,白名单排序 + biz_content 整体加密) |
| 多 App 注册 | 一个服务端可托管多个 app,每个 app 独立密钥 / 独立算法白名单 |
| 混合加密 | RSA-OAEP 包装 AES-256-GCM 临时密钥 → 前向安全 |
| Fastify 插件 | 一行 app.register(...) 启用端到端加密网关 |
| 浏览器 SDK | 同一份协议,浏览器 / Node / Fastify 互通 |
| 零外部依赖 | 算法层全部纯 Node crypto / 纯 JS(SM3、SM4)实现,体积小 |
📦 安装
npm install secure-crypto-top-sdk
# 或
pnpm add secure-crypto-top-sdk🚀 快速开始
1. Node.js 端:多协议 / 多算法(独立工具)
import { buildProtocolRequest, parseAndVerifyProtocol, buildProtocolResponse } from 'secure-crypto-top-sdk';
const apps = [{ appKey: 'demo-app', appSecret: 'my-secret-1234567890' }];
// 客户端构造请求(TOP 协议 + AES-256-GCM + HMAC-SHA256)
const env = await buildProtocolRequest(
{
method: 'POST',
path: 'user.login',
biz: { username: 'alice', password: 'p@ss' },
cipher: 'aes-256-gcm',
digest: 'hmac-sha256',
},
{
appKey: 'demo-app',
appSecret: 'my-secret-1234567890',
encryptionKey: Buffer.alloc(32, 1), // 32 字节对称密钥
hmacSecret: 'my-secret-1234567890',
}
);
// 服务端解析 + 验签
const verified = await parseAndVerifyProtocol(env, { apps });
console.log(verified.biz); // { username: 'alice', password: 'p@ss' }切换到 国密 SM4 + SM3:
const env = await buildProtocolRequest(
{ method: 'POST', path: 'user.pay', biz: { orderId: 'O1' }, cipher: 'sm4-cbc', digest: 'sm3' },
{ appKey: 'demo-app', appSecret: 'my-secret', encryptionKey: Buffer.alloc(16, 1), hmacSecret: 'my-secret' }
);切换到 custom 协议(兼容老 secure-crypto-sdk):
const env = await buildProtocolRequest(
{ method: 'POST', path: '/api/v1/echo', body: { foo: 'bar' }, protocol: 'custom' },
{ appKey: 'demo-app', appSecret: 'my-secret', encryptionKey: Buffer.alloc(32, 1), hmacSecret: 'my-secret' }
);2. Fastify 网关(推荐)
import Fastify from 'fastify';
import secureCryptoPlugin from 'secure-crypto-top-sdk/server';
const app = Fastify({ logger: true });
await app.register(secureCryptoPlugin, {
apps: [
{
appKey: 'demo-app',
appSecret: 'demo-secret-1234567890',
allowedCiphers: ['aes-256-gcm', 'sm4-cbc'], // 限制可用加密算法
allowedDigests: ['hmac-sha256', 'sm3'], // 限制可用签名算法
},
{
appKey: 'legacy',
appSecret: 'legacy-secret',
allowedCiphers: ['aes-256-cbc'], // 老接口:仅 CBC
allowedDigests: ['md5'],
},
],
defaultProtocol: 'top',
bypassPaths: ['/health', '/docs'],
// redis: redisClient, // 可选:nonce 防重放
});
app.post('/api/v1/top/login', async (req) => {
// 业务 handler 里直接读明文
const { username, password } = req.body as any;
// ...
return { success: true, userId: 1 };
});3. 浏览器端
import { SecureClient } from 'secure-crypto-top-sdk/client';
const client = new SecureClient({
baseURL: 'https://api.example.com',
encryptionKey: 'a1b2c3...64字符hex', // 32 字节 hex
hmacSecret: 'my-hmac-secret-1234567890', // >= 32 字符
appKey: 'demo-app',
protocol: 'top', // 默认 'top'
cipher: 'aes-256-gcm',
digest: 'hmac-sha256',
});
const data = await client.post('/api/v1/top/login', { username: 'alice', password: 'p@ss' });🔄 协议格式
TOP 风格(默认)
{
"protocol": "top",
"method": "user.login", // API 名
"app_key": "demo-app",
"timestamp": 1718000000000,
"v": "2.0",
"sign_method": "hmac-sha256", // 或 sm3 / hmac-sha512
"cipher": "aes-256-gcm", // 或 aes-256-cbc / sm4-cbc
"biz_content": "<base64密文>", // 业务参数整体加密后 base64
"iv": "<base64>",
"authTag": "<base64>", // GCM 才有
"sign": "<hex 签名>"
}签名拼接规则:
signSource = sortedBizParams(biz + systemParams) + appSecret + biz_content
sign = digest(signSource, appSecret)不同厂商的"加 secret"位置(头/尾/不参与)略有差异,可修改
src/protocol/top/signer.ts适配。
Custom 风格(兼容旧 SDK)
{
"protocol": "custom",
"encryptedPayload": "<base64 整包密文>", // 加密 {path, method, body, query}
"iv": "<base64>",
"authTag": "<base64>",
"signature": "<hex>",
"timestamp": 1718000000000,
"nonce": "<uuid>"
}签名:timestamp + nonce + encrypted + iv + authTag
🔌 扩展新算法
// 1. 实现 Cipher 接口
import type { Cipher, CipherMeta } from 'secure-crypto-top-sdk';
const meta: CipherMeta = { name: 'chacha20-poly1305', keyLength: 32, ivLength: 12, hasAuthTag: true, blockSize: 1 };
const myCipher: Cipher = { name: 'chacha20-poly1305', meta, /* ... */ };
// 2. 注册
import { cipherRegistry } from 'secure-crypto-top-sdk';
cipherRegistry.set('chacha20-poly1305', myCipher);🧪 测试
pnpm test # vitest
pnpm demo:server # 启动 demo 服务📁 目录结构
secure-crypto-top-sdk/
├── src/
│ ├── algorithms/
│ │ ├── cipher/ # AES-GCM/CBC、SM4、RSA-OAEP 混合
│ │ ├── digest/ # HMAC、MD5/SHA、SM3
│ │ ├── registry.ts # 算法注册表
│ │ └── types.ts
│ ├── protocol/
│ │ ├── custom/ # 自家协议
│ │ ├── top/ # TOP 风格协议
│ │ ├── base.ts # ProtocolStrategy 接口
│ │ └── registry.ts
│ ├── config/ # AppRegistry / KeyStore
│ ├── client/ # 浏览器 SecureClient
│ ├── server/ # Fastify 插件 + 独立工具
│ ├── types/
│ ├── errors/
│ └── index.ts
├── demo/ # demo-server.ts / demo-client.ts
├── tests/ # vitest
├── package.json
├── tsconfig.json
└── tsup.config.ts🔒 安全建议
- 生产环境:
KeyStore.setHex显式注入密钥,不要用deriveFromApp(它从 appSecret 派生对称密钥,弱于独立密钥)。 - MD5 / SHA-256 摘要:仅用于兼容老接口,默认应在
allowedDigests中显式开启。 - CBC 模式:每次加密必须用新随机 IV(SDK 内已自动处理)。
- 混合加密:用
rsa-oaep-aes-256-gcm,每次请求 AES key 临时生成,提供前向安全。 - 重放防护:传
redis给 Fastify 插件,启用 nonce 校验。 - 时间窗口:默认 5 分钟,生产建议 ≤ 60 秒。
📄 License
MIT © 2026 Atengliyun
