crypto-js 是一个纯 JavaScript 实现的加密库,提供独立的 API 接口,支持 AES、SHA 等常见算法,专为浏览器和 Node.js 环境设计。crypto-browserify 则是 Node.js crypto 模块的浏览器端 polyfill,旨在让浏览器环境能够运行依赖 Node 核心模块的代码。两者都能在前端实现加密功能,但设计理念和集成方式截然不同。
在前端开发中,处理敏感数据加密时,开发者常面临两个主要选择:crypto-js 和 crypto-browserify。虽然它们都能实现 AES、SHA 等算法,但底层设计哲学完全不同。crypto-js 是独立的加密库,而 crypto-browserify 是 Node 核心模块的模拟器。让我们从架构师的角度,深入对比它们在真实工程中的表现。
crypto-js 使用独立的全局或模块命名空间 CryptoJS。
AES.encrypt)。// crypto-js: 直接调用算法接口
import CryptoJS from 'crypto-js';
const ciphertext = CryptoJS.AES.encrypt('my message', 'secret key').toString();
const bytes = CryptoJS.AES.decrypt(ciphertext, 'secret key');
const plaintext = bytes.toString(CryptoJS.enc.Utf8);
crypto-browserify 模拟 Node.js 的 crypto 模块接口。
createCipheriv 等底层方法,需要手动管理 IV(初始化向量)。// crypto-browserify: 模拟 Node crypto 模块
import crypto from 'crypto'; // 需要构建工具支持 polyfill
const cipher = crypto.createCipheriv('aes-256-cbc', Buffer.from(key), iv);
let encrypted = cipher.update('my message', 'utf8', 'hex');
encrypted += cipher.final('hex');
crypto-js 是纯 JavaScript 库,不依赖 Node 核心模块。
// webpack.config.js (crypto-js 无需特殊配置)
module.exports = {
// 无需 resolve.fallback 配置
entry: './src/index.js'
};
crypto-browserify 依赖 Node 核心模块的 shim。
resolve.fallback,否则构建会报错。// webpack.config.js (crypto-browserify 必须配置)
module.exports = {
resolve: {
fallback: {
crypto: require.resolve('crypto-browserify'),
stream: require.resolve('stream-browserify')
}
}
};
crypto-js 封装了部分安全细节。
// crypto-js: 自动生成 IV(方便但需知情)
const ciphertext = CryptoJS.AES.encrypt('message', 'key').toString();
// IV 隐藏在 ciphertext 字符串中
crypto-browserify 强制开发者显式管理 IV。
createCipheriv 而不是已废弃的 createCipher。// crypto-browserify: 必须显式提供 IV
const iv = crypto.randomBytes(16);
const cipher = crypto.createCipheriv('aes-256-cbc', key, iv);
// 开发者需自行存储 iv 以便解密
crypto-js 支持广泛的算法集合。
// crypto-js: 支持多种哈希算法
const hashSha256 = CryptoJS.SHA256("message").toString();
const hashMd5 = CryptoJS.MD5("message").toString();
crypto-browserify 依赖底层 shim 实现。
crypto 模块涵盖的算法。crypto-js 相近,但在某些哈希算法上可能更慢。// crypto-browserify: 使用 createHash
const hash = crypto.createHash('sha256').update('message').digest('hex');
尽管实现方式不同,这两个库在前端加密场景中也有许多共同点。
// 共同目标:SHA256 哈希
// crypto-js
CryptoJS.SHA256("data").toString();
// crypto-browserify
crypto.createHash('sha256').update("data").digest('hex');
// 安装方式相似
npm install crypto-js
npm install crypto-browserify
// 共同警告:不要硬编码密钥
// ❌ 不安全
const key = "secret123";
// ✅ 建议:密钥通过安全通道动态获取
| 特性 | crypto-js | crypto-browserify |
|---|---|---|
| 定位 | 独立加密库 | Node crypto 模块 polyfill |
| API 风格 | CryptoJS.AES 命名空间 | crypto.createCipheriv 原生风格 |
| 构建配置 | 零配置,开箱即用 | 需配置 webpack/vite polyfill |
| IV 管理 | 可自动处理 | 必须手动管理 |
| 代码复用 | 前端专用 | 前后端代码共享友好 |
| 维护状态 | 稳定维护 | 稳定,但依赖构建生态 |
crypto-js 就像一把专用瑞士军刀 🇨🇭 — 适合大多数纯前端项目,快速、简单、无需配置。如果你的团队主要关注前端业务,且不需要与 Node 后端共享加密逻辑,这是首选。
crypto-browserify 就像一套标准工业工具 🏭 — 适合全栈 TypeScript 项目,强调代码一致性和环境模拟。如果你的团队希望在前后端使用完全相同的加密模块代码,且愿意承担构建配置成本,它更合适。
最终建议:对于大多数现代前端应用,优先选择 crypto-js。只有在确需前后端代码完全复用且构建流程成熟的情况下,才考虑 crypto-browserify。无论选哪个,请记住 — 前端加密不能替代后端安全,密钥管理永远是第一要务。
选择 crypto-js 如果你的项目是纯前端应用,不需要与 Node 后端共享加密逻辑代码,且希望零配置直接使用。它 API 简单,文档丰富,适合快速集成常见的加密需求,无需关心构建工具的 polyfill 配置。
选择 crypto-browserify 如果你需要在前后端共享同一套加密代码,且代码中已经使用了 require('crypto') 写法。它适合需要严格模拟 Node 环境的大型构建流程,但需要手动配置 bundler 的 polyfill,维护成本相对较高。
JavaScript library of crypto standards.
Active development of CryptoJS has been discontinued. This library is no longer maintained.
Nowadays, NodeJS and modern browsers have a native Crypto module. The latest version of CryptoJS already uses the native Crypto module for random number generation, since Math.random() is not crypto-safe. Further development of CryptoJS would result in it only being a wrapper of native Crypto. Therefore, development and maintenance has been discontinued, it is time to go for the native crypto module.
Requirements:
npm install crypto-js
ES6 import for typical API call signing use case:
import sha256 from 'crypto-js/sha256';
import hmacSHA512 from 'crypto-js/hmac-sha512';
import Base64 from 'crypto-js/enc-base64';
const message, nonce, path, privateKey; // ...
const hashDigest = sha256(nonce + message);
const hmacDigest = Base64.stringify(hmacSHA512(path + hashDigest, privateKey));
Modular include:
var AES = require("crypto-js/aes");
var SHA256 = require("crypto-js/sha256");
...
console.log(SHA256("Message"));
Including all libraries, for access to extra methods:
var CryptoJS = require("crypto-js");
console.log(CryptoJS.HmacSHA1("Message", "Key"));
Requirements:
bower install crypto-js
Modular include:
require.config({
packages: [
{
name: 'crypto-js',
location: 'path-to/bower_components/crypto-js',
main: 'index'
}
]
});
require(["crypto-js/aes", "crypto-js/sha256"], function (AES, SHA256) {
console.log(SHA256("Message"));
});
Including all libraries, for access to extra methods:
// Above-mentioned will work or use this simple form
require.config({
paths: {
'crypto-js': 'path-to/bower_components/crypto-js/crypto-js'
}
});
require(["crypto-js"], function (CryptoJS) {
console.log(CryptoJS.HmacSHA1("Message", "Key"));
});
<script type="text/javascript" src="path-to/bower_components/crypto-js/crypto-js.js"></script>
<script type="text/javascript">
var encrypted = CryptoJS.AES(...);
var encrypted = CryptoJS.SHA256(...);
</script>
See: https://cryptojs.gitbook.io/docs/
var CryptoJS = require("crypto-js");
// Encrypt
var ciphertext = CryptoJS.AES.encrypt('my message', 'secret key 123').toString();
// Decrypt
var bytes = CryptoJS.AES.decrypt(ciphertext, 'secret key 123');
var originalText = bytes.toString(CryptoJS.enc.Utf8);
console.log(originalText); // 'my message'
var CryptoJS = require("crypto-js");
var data = [{id: 1}, {id: 2}]
// Encrypt
var ciphertext = CryptoJS.AES.encrypt(JSON.stringify(data), 'secret key 123').toString();
// Decrypt
var bytes = CryptoJS.AES.decrypt(ciphertext, 'secret key 123');
var decryptedData = JSON.parse(bytes.toString(CryptoJS.enc.Utf8));
console.log(decryptedData); // [{id: 1}, {id: 2}]
crypto-js/corecrypto-js/x64-corecrypto-js/lib-typedarrayscrypto-js/md5crypto-js/sha1crypto-js/sha256crypto-js/sha224crypto-js/sha512crypto-js/sha384crypto-js/sha3crypto-js/ripemd160crypto-js/hmac-md5crypto-js/hmac-sha1crypto-js/hmac-sha256crypto-js/hmac-sha224crypto-js/hmac-sha512crypto-js/hmac-sha384crypto-js/hmac-sha3crypto-js/hmac-ripemd160crypto-js/pbkdf2crypto-js/aescrypto-js/tripledescrypto-js/rc4crypto-js/rabbitcrypto-js/rabbit-legacycrypto-js/evpkdfcrypto-js/format-opensslcrypto-js/format-hexcrypto-js/enc-latin1crypto-js/enc-utf8crypto-js/enc-hexcrypto-js/enc-utf16crypto-js/enc-base64crypto-js/mode-cfbcrypto-js/mode-ctrcrypto-js/mode-ctr-gladmancrypto-js/mode-ofbcrypto-js/mode-ecbcrypto-js/pad-pkcs7crypto-js/pad-ansix923crypto-js/pad-iso10126crypto-js/pad-iso97971crypto-js/pad-zeropaddingcrypto-js/pad-nopaddingChange default hash algorithm and iteration's for PBKDF2 to prevent weak security by using the default configuration.
Custom KDF Hasher
Blowfish support
Fix module order in bundled release.
Include the browser field in the released package.json.
Added url safe variant of base64 encoding. 357
Avoid webpack to add crypto-browser package. 364
This is an update including breaking changes for some environments.
In this version Math.random() has been replaced by the random methods of the native crypto module.
For this reason CryptoJS might not run in some JavaScript environments without native crypto module. Such as IE 10 or before or React Native.
Rollback, 3.3.0 is the same as 3.1.9-1.
The move of using native secure crypto module will be shifted to a new 4.x.x version. As it is a breaking change the impact is too big for a minor release.
The usage of the native crypto module has been fixed. The import and access of the native crypto module has been improved.
In this version Math.random() has been replaced by the random methods of the native crypto module.
For this reason CryptoJS might does not run in some JavaScript environments without native crypto module. Such as IE 10 or before.
If it's absolute required to run CryptoJS in such an environment, stay with 3.1.x version. Encrypting and decrypting stays compatible. But keep in mind 3.1.x versions still use Math.random() which is cryptographically not secure, as it's not random enough.
This version came along with CRITICAL BUG.
DO NOT USE THIS VERSION! Please, go for a newer version!
The 3.1.x are based on the original CryptoJS, wrapped in CommonJS modules.