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

@crh-fe/crh-crypto-ctrl

v1.2.11

Published

前端国密(SM2 / SM4)加解密工具库,支持 Node.js 和浏览器环境。

Downloads

122

Readme

crh-crypto-ctrl

前端国密(SM2 / SM4)加解密工具库,支持 Node.js 和浏览器环境。

本库基于国家密码管理局批准的 SM2(椭圆曲线公钥密码算法)和 SM4(分组密码算法)实现,提供对称与非对称两种加密模式,可用于接口参数加密、敏感数据传输、请求签名等场景。

功能特性

| 分类 | 说明 | |------|------| | SM2 非对称加密 | 使用椭圆曲线加密,适合加密少量敏感数据(如用户身份信息)。预置公私钥,开箱即用。 | | SM4 v1 静态加密 | 使用预置共享密钥,适合与后端约定固定密钥的场景。自动生成签名(cpesignature)和密文(ciphertextbody)。 | | SM4 v2 动态加密 | 支持服务端动态下发密钥,每次请求使用时间戳 + 密钥混淆生成会话密钥,安全性更高。 | | v1 兼容模式 | DynamicSm4Base 支持传入 version: 'v1',内部自动调用静态加密,与旧版接口兼容。 | | 双端支持 | 通过 Webpack UMD 构建,可在 Node.js 和浏览器中直接使用。 |

安装

npm install crhsecuritycontrol

构建

如需自行构建(适用于修改源码后):

npm run build

构建产物输出到 dist/ 目录。

使用方式

Node.js

const {
  encryptData,
  encryptObjectData,
  getDecryptData,
  decryptData,
  encryptSM4,
  decryptSM4,
  DynamicSm4Base,
} = require('crhsecuritycontrol');

ES Module

import {
  encryptData,
  encryptObjectData,
  getDecryptData,
  decryptData,
  encryptSM4,
  decryptSM4,
  DynamicSm4Base,
} from 'crhsecuritycontrol';

浏览器全局变量(CDN)

<script src="https://unpkg.com/crhsecuritycontrol/dist/index.js"></script>
<script>
  const { encryptSM4, decryptSM4 } = crhsecuritycontrol;
</script>

注意:CDN 引入方式无需运行 npm run build,可直接使用。

API 参考


SM2 加密

encryptData(data)

使用 SM2 公钥加密字符串。

参数

| 参数 | 类型 | 说明 | |------|------|------| | data | string | 待加密的明文字符串 |

返回 string — 以 04 开头的十六进制加密结果。

const plaintext = '敏感数据: 1234567890';
const encrypted = encryptData(plaintext);
console.log(encrypted);
// 04f7c1e5b3a9...

encryptObjectData(data)

将对象序列化为 JSON 后使用 SM2 公钥加密,返回包装对象 { signature }

参数

| 参数 | 类型 | 说明 | |------|------|------| | data | object | 待加密的明文对象 |

返回 { signature: string } — 包含加密结果的签名字段。

const userData = { username: 'admin', idCard: '110101199001011234' };
const encrypted = encryptObjectData(userData);
// { signature: '04f7c1e5b3a9...' }

getDecryptData(encryptData)

自动判断是否需要解密,若 encryptData 含有 signature 字段则解密并自动 JSON.parse 返回对象;否则透传原数据。

参数

| 参数 | 类型 | 说明 | |------|------|------| | encryptData | object | 加密数据对象(含 signature 字段)或普通对象 |

返回 解密后的对象或原数据。

const decrypted = getDecryptData(encryptedObj);
// { username: 'admin', idCard: '110101199001011234' }

decryptData(encryptData)

使用 SM2 私钥解密 signature 字段,返回原始字符串(不做 JSON 解析)。

参数

| 参数 | 类型 | 说明 | |------|------|------| | encryptData | object | 加密数据对象,需含 signature 字段 |

返回 string — 解密后的原始字符串。

const raw = decryptData(encryptedObj);
// '{"username":"admin","idCard":"110101199001011234"}'

SM4 加密

encryptSM4(obj, token, url, closeDecrypt?)

使用 SM4 v1 静态密钥加密接口请求参数,生成签名和密文。

参数

| 参数 | 类型 | 默认值 | 说明 | |------|------|--------|------| | obj | object | — | 请求参数字对象 | | token | string | — | 用户会话令牌 | | url | string | — | 请求 URL(query string 会自动去除) | | closeDecrypt | boolean | false | 是否关闭控制台日志输出 |

返回 { cpesignature: string, ciphertextbody: string }

const params = { page: 1, pageSize: 20, keyword: '国密测试' };
const token = 'user-session-token-123';
const url = 'https://api.example.com/search?debug=true';

const encrypted = encryptSM4(params, token, url, true);
// {
//   cpesignature: 'a8f3b2c1...',
//   ciphertextbody: 'xK9mP2...'
// }

decryptSM4(text, closeDecrypt?)

解密 SM4 密文字符串。

参数

| 参数 | 类型 | 默认值 | 说明 | |------|------|--------|------| | text | string | — | Base64 编码的 SM4 密文 | | closeDecrypt | boolean | false | 是否关闭控制台日志输出 |

返回 string — 解密后的 UTF-8 明文字符串(需手动 JSON.parse)。

const decrypted = decryptSM4(encrypted.ciphertextbody, true);
// '{"page":1,"pageSize":20,"keyword":"国密测试"}'

动态 SM4(DynamicSm4Base)

new DynamicSm4Base(key, version, timeStamp)

创建动态 SM4 加解密实例,支持 v1(静态兼容)和 v2(动态密钥)两种模式。

参数

| 参数 | 类型 | 默认值 | 说明 | |------|------|--------|------| | key | string \| null | — | 服务端下发的 hex 格式密钥(v2 模式必需),传入 null 则使用 v1 兼容模式 | | version | 'v1' \| 'v2' | 'v1' | 加密版本,v1 调用静态加密,v2 使用动态密钥 | | timeStamp | number | — | 毫秒级时间戳(v2 模式必需),用于密钥混淆 |

v2 动态密钥流程

服务端需下发动态密钥配置,前端收到后初始化加解密器:

// 从服务端获取密钥配置
const cryptoConfig = await fetch('/api/crypto/config').then(r => r.json());
// { key: 'a1b2c3d4e5f6...', version: 'v2', timeStamp: 1745136000000 }

const sm4 = new DynamicSm4Base(
  cryptoConfig.key,
  cryptoConfig.version,
  cryptoConfig.timeStamp
);

dynamicSm4.encryptSM4(obj, token, url, closeDecrypt?)

根据实例版本自动选择加密策略:

  • v1 模式 — 调用 sm4Crypoto.js 的静态加密,与后端预置密钥方案兼容。
  • v2 模式 — 使用服务端下发的动态密钥 + 时间戳混淆后进行加密。

返回 { cpesignature: string, ciphertextbody: string }

const encrypted = sm4.encryptSM4(
  { orderId: 'ORD20260101001', amount: 998.5 },
  'payment-token',
  '/api/payment/create',
  true
);

dynamicSm4.decryptSM4(text, closeDecrypt?)

根据实例版本自动选择解密策略,与 encryptSM4 的 v1/v2 对应。

返回 string — 解密后的明文字符串。

const decrypted = sm4.decryptSM4(encrypted.ciphertextbody, true);

完整请求示例

以下示例展示从前端加密请求参数、发送请求,到接收加密响应并解密的全流程:

const params = {
  userId: 12345,
  action: 'updateProfile',
  data: { nickname: 'CryptoUser', email: '[email protected]' },
};
const token = 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...';
const url = 'https://api.example.com/user/profile';

// 1. 加密请求参数
const encryptedParams = encryptSM4(params, token, url, true);

// 2. 发送加密请求(伪代码)
// const response = await fetch(url, {
//   method: 'POST',
//   body: JSON.stringify(encryptedParams),
//   headers: { 'Content-Type': 'application/json' },
// });

// 3. 解密响应
// const encryptedResponse = await response.json();
// const decrypted = decryptSM4(encryptedResponse.ciphertextbody, true);
// const result = JSON.parse(decrypted);

项目结构

crhsecuritycontrol/
├── index.js                    # 统一导出入口
├── package.json                # 包配置
├── webpack.config.js           # Webpack 构建配置(UMD)
├── dist/                       # 构建产物(运行 npm run build 后生成)
│   └── index.js
├── utils/
│   ├── smCrypto.js             # SM2 加密模块(encryptData / encryptObjectData / getDecryptData / decryptData)
│   ├── sm4Crypoto.js          # SM4 v1 静态加密模块(encryptSM4 / decryptSM4)
│   ├── dynamic.js              # DynamicSm4Base 动态加密类(v1 / v2)
│   └── gm-crypt/
│       ├── index.js           # gm-crypt 入口
│       └── src/
│           ├── sm4.js         # SM4 算法实现(CBC / ECB 模式)
│           └── crypt.js       # Base64 / UTF-8 转换工具
└── examples/
    ├── node-example.js        # Node.js 使用示例
    └── browser-example.html   # 浏览器交互式 Demo

技术依赖

| 依赖 | 版本 | 用途 | |------|------|------| | sm-crypto | ^0.3.11 | SM2 椭圆曲线加密算法 | | gm-crypt | ^0.0.2 | SM4 分组密码算法(内置 ECB/CBC 实现) | | js-md5 | ^0.8.3 | MD5 签名计算 | | buffer | ^6.0.3 | Node.js Buffer polyfill(浏览器端使用) |

许可证

ISC