secure-crypto-sdk
v1.0.0
Published
🔐 端到端加密 SDK - AES-256-GCM + HMAC-SHA256,支持 Node.js / 浏览器 / Fastify
Maintainers
Readme
🔐 secure-crypto-sdk
端到端加密 SDK · AES-256-GCM + HMAC-SHA256 同时支持 Node.js 服务端、浏览器端和 Fastify 框架
✨ 特性
- AES-256-GCM 提供机密性、完整性和认证性
- HMAC-SHA256 签名防篡改
- 时间戳 + Nonce 防重放攻击
- 多端复用 同一份加密协议,浏览器 / Node.js / Fastify 互通
- TypeScript 全量类型 + Zod 校验
📦 安装
npm install secure-crypto-sdk
# 或
pnpm add secure-crypto-sdk🔑 生成密钥
import { generateEncryptionKey, generateHmacSecret } from 'secure-crypto-sdk';
const ENCRYPTION_KEY = generateEncryptionKey(); // 64 字符 hex
const HMAC_SECRET = generateHmacSecret(); // 128 字符 hex🚀 快速开始
浏览器端 (Web Crypto)
import { SecureClient } from 'secure-crypto-sdk/client';
const client = new SecureClient({
baseURL: 'https://api.example.com',
encryptionKey: '62af5a4e...7f1', // 64 字符 hex
hmacSecret: '3818833d...b803', // >=32 字符
});
// 加密登录
const result = await client.post<{ accessToken: string }>(
'/api/v1/auth/login',
{ email: '[email protected]', password: 'User@123456' }
);
console.log(result);Node.js 服务端
import {
encryptJSON,
decryptJSON,
signRequest,
verifyRequestSignature,
} from 'secure-crypto-sdk';
// 加密
const { encrypted, iv, authTag } = encryptJSON(
{ userId: 123, action: 'pay' },
ENCRYPTION_KEY
);
// 签名
const timestamp = Date.now();
const nonce = crypto.randomUUID();
const signature = signRequest(HMAC_SECRET, timestamp, nonce, encrypted, iv, authTag);
// 验签 + 解密
const ok = verifyRequestSignature(signature, HMAC_SECRET, timestamp, nonce, encrypted, iv, authTag);
const plain = decryptJSON(encrypted, iv, authTag, ENCRYPTION_KEY);Fastify 集成
import Fastify from 'fastify';
import secureCryptoPlugin from 'secure-crypto-sdk/server';
import Redis from 'ioredis';
const app = Fastify({ logger: true });
const redis = new Redis({ host: 'localhost', port: 6379 });
await app.register(secureCryptoPlugin, {
encryptionKey: process.env.ENCRYPTION_KEY!,
hmacSecret: process.env.HMAC_SECRET!,
redis, // 可选:nonce 防重放
bypassPaths: ['/health', '/docs'], // 可选:白名单
requestWindowMs: 5 * 60 * 1000, // 可选:时间窗口
});
// 业务路由可以直接读取 request.secureRequest
app.post('/api/v1/auth/login', async (req, reply) => {
// req.body 已经是解密后的明文!
const { email, password } = req.body as any;
// ...
});🔄 加密协议
请求结构
POST /api/v1/auth/login HTTP/1.1
Content-Type: application/json
x-timestamp: 1718000000000
x-nonce: 550e8400-e29b-41d4-a716-446655440000
{
"encryptedPayload": "base64 密文",
"iv": "base64 12字节",
"authTag": "base64 16字节",
"signature": "hex HMAC-SHA256",
"timestamp": 1718000000000,
"nonce": "550e8400-e29b-41d4-a716-446655440000"
}加密的明文结构(encryptJSON):
{
"path": "/api/v1/auth/login",
"method": "POST",
"body": { "email": "...", "password": "..." }
}签名内容
signature = HMAC-SHA256(secret, `${timestamp}.${nonce}.${encrypted}.${iv}.${authTag}`)响应结构
{
"encryptedPayload": "base64 密文",
"iv": "base64",
"authTag": "base64",
"signature": "hex",
"timestamp": 1718000000000,
"nonce": "原请求 nonce 回显"
}📚 API 文档
| 导出 | 说明 |
|---|---|
| SecureClient (client) | 浏览器端 SDK |
| secureCryptoPlugin (server) | Fastify 插件 |
| encrypt / decrypt | 基础 AES-256-GCM |
| encryptJSON / decryptJSON | JSON 加解密 |
| createSignature / verifySignature | HMAC 签名/验证 |
| signRequest / verifyRequestSignature | 标准化请求签名 |
| EncryptedRequestSchema | Zod 加密请求校验 |
| SecureError / ErrorCode | 错误体系 |
📁 目录结构
secure-crypto-sdk/
├── src/
│ ├── crypto/ # 底层 AES / HMAC
│ ├── errors/ # 错误码体系
│ ├── types/ # 类型 & Zod
│ ├── client/ # 浏览器 SecureClient
│ ├── server/ # Fastify 钩子 + 插件
│ └── index.ts # 统一导出
├── demo/ # 演示 (浏览器 + 服务端)
├── package.json
├── tsconfig.json
└── README.md📄 License
MIT © 2026 Atengliyun
