crypto-js vs crypto-browserify
前端加密库选型:crypto-browserify 与 crypto-js
crypto-jscrypto-browserify类似的npm包:

前端加密库选型:crypto-browserify 与 crypto-js

crypto-js 是一个纯 JavaScript 实现的加密库,提供独立的 API 接口,支持 AES、SHA 等常见算法,专为浏览器和 Node.js 环境设计。crypto-browserify 则是 Node.js crypto 模块的浏览器端 polyfill,旨在让浏览器环境能够运行依赖 Node 核心模块的代码。两者都能在前端实现加密功能,但设计理念和集成方式截然不同。

npm下载趋势

3 年

统计详情

npm包名称
下载量
Stars
大小
Issues
发布时间
License
crypto-js26,112,097-487 kB-3 年前MIT
crypto-browserify0-56 kB-2 年前MIT

前端加密方案深度对比:crypto-browserify vs crypto-js

在前端开发中,处理敏感数据加密时,开发者常面临两个主要选择:crypto-js 和 crypto-browserify。虽然它们都能实现 AES、SHA 等算法,但底层设计哲学完全不同。crypto-js 是独立的加密库,而 crypto-browserify 是 Node 核心模块的模拟器。让我们从架构师的角度,深入对比它们在真实工程中的表现。

🛠️ API 设计风格:独立命名空间 vs Node 原生模拟

crypto-js 使用独立的全局或模块命名空间 CryptoJS。

  • API 设计直观,方法名直接反映算法(如 AES.encrypt)。
  • 不需要理解 Node.js 的流或 Buffer 概念,上手门槛低。
// 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(初始化向量)。
  • 代码风格与 Node 后端保持一致,适合全栈代码复用。
// 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');

⚙️ 构建配置与集成:零配置 vs 手动 Polyfill

crypto-js 是纯 JavaScript 库,不依赖 Node 核心模块。

  • 在任何现代打包工具(Webpack, Vite, Rollup)中开箱即用。
  • 不需要额外配置,减少构建出错的风险。
// webpack.config.js (crypto-js 无需特殊配置)
module.exports = {
  // 无需 resolve.fallback 配置
  entry: './src/index.js'
};

crypto-browserify 依赖 Node 核心模块的 shim。

  • 在 Webpack 5 或 Vite 中,默认不再自动 polyfill Node 模块。
  • 必须手动配置 resolve.fallback,否则构建会报错。
// webpack.config.js (crypto-browserify 必须配置)
module.exports = {
  resolve: {
    fallback: {
      crypto: require.resolve('crypto-browserify'),
      stream: require.resolve('stream-browserify')
    }
  }
};

🔒 安全性与最佳实践:IV 管理与废弃 API

crypto-js 封装了部分安全细节。

  • 如果未提供 IV,它会自动生成随机 IV 并包含在密文中。
  • 适合快速开发,但开发者可能忽略 IV 复用风险。
// 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 支持广泛的算法集合。

  • 包括 AES、DES、Rabbit、TripleDES、MD5、SHA1、SHA256、HMAC 等。
  • 纯 JS 实现,性能在大数据量下可能略低于原生,但对前端场景足够。
// crypto-js: 支持多种哈希算法
const hashSha256 = CryptoJS.SHA256("message").toString();
const hashMd5 = CryptoJS.MD5("message").toString();

crypto-browserify 依赖底层 shim 实现。

  • 支持 Node crypto 模块涵盖的算法。
  • 性能取决于 shim 实现效率,通常与 crypto-js 相近,但在某些哈希算法上可能更慢。
// crypto-browserify: 使用 createHash
const hash = crypto.createHash('sha256').update('message').digest('hex');

🤝 相似之处:共同的基础能力

尽管实现方式不同,这两个库在前端加密场景中也有许多共同点。

1. 🔐 均支持对称加密与非对称哈希

  • 都能处理常见的 AES 加密和 SHA 哈希需求。
  • 适合前端数据脱敏、签名验证等场景。
// 共同目标:SHA256 哈希
// crypto-js
CryptoJS.SHA256("data").toString();

// crypto-browserify
crypto.createHash('sha256').update("data").digest('hex');

2. 📦 均支持 npm 安装与模块化

  • 都可以通过 npm 安装,支持 ES6 import 和 CommonJS require。
  • 类型定义文件(@types)社区支持良好。
// 安装方式相似
npm install crypto-js
npm install crypto-browserify

3. ⚠️ 均面临客户端加密的安全局限

  • 密钥如果写在前端代码中,都存在被提取的风险。
  • 都不适合处理极高敏感度的加密(如支付密码),应优先使用后端加密。
// 共同警告:不要硬编码密钥
// ❌ 不安全
const key = "secret123"; 
// ✅ 建议:密钥通过安全通道动态获取

📊 总结:核心差异对比

特性crypto-jscrypto-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 vs crypto-browserify

  • crypto-js:

    选择 crypto-js 如果你的项目是纯前端应用,不需要与 Node 后端共享加密逻辑代码,且希望零配置直接使用。它 API 简单,文档丰富,适合快速集成常见的加密需求,无需关心构建工具的 polyfill 配置。

  • crypto-browserify:

    选择 crypto-browserify 如果你需要在前后端共享同一套加密代码,且代码中已经使用了 require('crypto') 写法。它适合需要严格模拟 Node 环境的大型构建流程,但需要手动配置 bundler 的 polyfill,维护成本相对较高。

crypto-js的README

crypto-js

JavaScript library of crypto standards.

Discontinued

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.

Node.js (Install)

Requirements:

  • Node.js
  • npm (Node.js package manager)
npm install crypto-js

Usage

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"));

Client (browser)

Requirements:

  • Node.js
  • Bower (package manager for frontend)
bower install crypto-js

Usage

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"));
});

Usage without RequireJS

<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>

API

See: https://cryptojs.gitbook.io/docs/

AES Encryption

Plain text encryption

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'

Object encryption

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}]

List of modules

  • crypto-js/core
  • crypto-js/x64-core
  • crypto-js/lib-typedarrays

  • crypto-js/md5
  • crypto-js/sha1
  • crypto-js/sha256
  • crypto-js/sha224
  • crypto-js/sha512
  • crypto-js/sha384
  • crypto-js/sha3
  • crypto-js/ripemd160

  • crypto-js/hmac-md5
  • crypto-js/hmac-sha1
  • crypto-js/hmac-sha256
  • crypto-js/hmac-sha224
  • crypto-js/hmac-sha512
  • crypto-js/hmac-sha384
  • crypto-js/hmac-sha3
  • crypto-js/hmac-ripemd160

  • crypto-js/pbkdf2

  • crypto-js/aes
  • crypto-js/tripledes
  • crypto-js/rc4
  • crypto-js/rabbit
  • crypto-js/rabbit-legacy
  • crypto-js/evpkdf

  • crypto-js/format-openssl
  • crypto-js/format-hex

  • crypto-js/enc-latin1
  • crypto-js/enc-utf8
  • crypto-js/enc-hex
  • crypto-js/enc-utf16
  • crypto-js/enc-base64

  • crypto-js/mode-cfb
  • crypto-js/mode-ctr
  • crypto-js/mode-ctr-gladman
  • crypto-js/mode-ofb
  • crypto-js/mode-ecb

  • crypto-js/pad-pkcs7
  • crypto-js/pad-ansix923
  • crypto-js/pad-iso10126
  • crypto-js/pad-iso97971
  • crypto-js/pad-zeropadding
  • crypto-js/pad-nopadding

Release notes

4.2.0

Change default hash algorithm and iteration's for PBKDF2 to prevent weak security by using the default configuration.

Custom KDF Hasher

Blowfish support

4.1.1

Fix module order in bundled release.

Include the browser field in the released package.json.

4.1.0

Added url safe variant of base64 encoding. 357

Avoid webpack to add crypto-browser package. 364

4.0.0

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.

3.3.0

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.

3.2.1

The usage of the native crypto module has been fixed. The import and access of the native crypto module has been improved.

3.2.0

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!

3.1.x

The 3.1.x are based on the original CryptoJS, wrapped in CommonJS modules.