npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

secure-crypto-top-sdk

v0.1.0

Published

可插拔多算法 + 多协议(自定义 / TOP 风格)端到端加密 SDK,AES-GCM/CBC、HMAC/MD5/SHA、SM3/SM4,RSA-OAEP 混合加密,Fastify 集成

Readme

🔐 secure-crypto-top-sdk

可插拔多算法 + 多协议(自定义 / TOP 风格)端到端加密 SDK AES-GCM/CBC · SM4 · SM3 · HMAC · RSA-OAEP 混合加密 · Fastify 集成

npm version license

✨ 特性

| 能力 | 说明 | |---|---| | 多算法可插拔 | aes-256-gcmaes-256-cbcaes-128-cbcsm4-cbcrsa-oaep-aes-256-gcm | | 多签名算法 | hmac-sha256hmac-sha512md5sha256sm3 | | 多协议并存 | 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

🔒 安全建议

  1. 生产环境:KeyStore.setHex 显式注入密钥,不要deriveFromApp(它从 appSecret 派生对称密钥,弱于独立密钥)。
  2. MD5 / SHA-256 摘要:仅用于兼容老接口,默认应在 allowedDigests 中显式开启。
  3. CBC 模式:每次加密必须用新随机 IV(SDK 内已自动处理)。
  4. 混合加密:用 rsa-oaep-aes-256-gcm,每次请求 AES key 临时生成,提供前向安全。
  5. 重放防护:传 redis 给 Fastify 插件,启用 nonce 校验。
  6. 时间窗口:默认 5 分钟,生产建议 ≤ 60 秒。

📄 License

MIT © 2026 Atengliyun