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

@composy/crypto-core

v0.0.2

Published

Framework-agnostic crypto core - AES, RSA, Hash, HMAC algorithms with high performance

Readme

@composy/crypto-core

框架无关的加密核心库 —— 提供高性能对称/非对称加密、哈希、编码、密钥管理和安全工具能力

📦 安装

pnpm add @composy/crypto-core

零框架依赖,可在浏览器、Web Worker 与现代 Node 中直接使用;Vue 项目请配合 @composy/crypto-vue 适配层。

升级维护指南

  • 新算法先实现 types、algorithms、core/services 和 core/api 的最小闭环,再补测试和 README。
  • 热路径工具函数中的正则、字符集、常量必须放在模块作用域,避免每次调用重新创建。
  • 浏览器、Worker、Node 共享代码统一通过 globalThis 和显式类型守卫访问环境能力,不直接依赖全局 process、self 或 Buffer。
  • Worker、WASM、批处理只做性能增强,失败时必须能回退到主线程或纯 TypeScript 实现。
  • src/types/*.ts 是公开类型模块,Builder 会生成对应 .d.ts;postbuild 清理脚本只清理其它源目录的生成声明。
  • 验证命令:pnpm run lint:check、pnpm run type-check、pnpm run test:run、pnpm run build、pnpm run check:outputs、pnpm run check:consumer、pnpm run check:browser。

架构定位

@composy/crypto-core 是 packages/crypto 的唯一核心实现层,负责:

  • 算法实现:AES、DES、3DES、Blowfish、ChaCha20-Poly1305、RSA
  • 摘要与编码:Hash(MD5/SHA 系列)、HMAC、Base64、Hex
  • 统一 Facade:createCryptoApi() 提供一站式加密/哈希/编码接口
  • 性能优化:LRU 缓存、对象池、批处理、Worker 线程池、WASM 加速
  • 安全能力:安全存储、数据脱敏、Token 生成、密钥派生/轮换、限流器
  • Engine 集成:createCryptoEnginePlugin 对接 LDesign 引擎体系

适配层(如 @composy/crypto-vue)只做框架生命周期桥接,不复制核心算法逻辑。

主要能力

| 模块 | 能力 | 说明 | | ------------- | ----------- | ------------------------------------------------------------------------------------------- | | algorithms/ | 对称加密 | AES(CBC/ECB/CFB/OFB/CTR)、DES、3DES、Blowfish | | algorithms/ | 非对称加密 | RSA(OAEP/PKCS1)、数字签名与验签 | | algorithms/ | 现代加密 | ChaCha20-Poly1305 AEAD(RFC 8439,noble 实现) | | algorithms/ | 编码 | Base64、Base64URL、Hex、UTF-8 | | algorithms/ | 哈希 | MD5、SHA-1/224/256/384/512、HMAC | | algorithms/ | 密钥派生 | PBKDF2-SHA256、Argon2id、scrypt(标准实现) | | core/ | 统一 Facade | CryptoManager、createCryptoApi()、链式调用 | | core/ | 认证加密 | 默认 AES-GCM;显式兼容 AES-CBC + HMAC-SHA256 | | core/ | 安全随机 | CSPRNG:仅使用 Web Crypto 的系统安全随机源 | | core/ | 批处理 | BatchProcessor 并行加解密 | | utils/ | 安全存储 | SecureStorage 默认 AES-GCM,绑定存储键 AAD | | utils/ | 数据脱敏 | 手机号/身份证/银行卡/邮箱/IP/姓名掩码 | | utils/ | Token 生成 | UUID、NanoID、随机 Token、数字验证码 | | utils/ | 密钥管理 | 派生、轮换、验证 | | utils/ | 性能监控 | PerformanceMonitor 算法统计与报告 | | utils/ | 限流器 | 固定窗口、滑动窗口、令牌桶 | | workers/ | Worker 池 | 多线程并行加解密 | | wasm/ | WASM 加速 | 可选调用方 SHA-256/PBKDF2 WebAssembly 适配器(默认不加载,失败降级到 JS;AES 保持规范实现) | | stream/ | 流式加密 | 文件级加解密、进度回调与 AbortSignal 取消 | | engine/ | Engine 插件 | createCryptoEnginePlugin 引擎集成 |

推荐 API

1. 直接用算法

aes.encrypt() 的高层便捷入口默认使用 AES-GCM,并返回完整 envelope(ciphertext、salt、nonce、authTag、AAD、KDF 参数和版本)。new AESEncryptor().encrypt() 是低层、未认证的 AES 模式接口,默认 CBC 仅用于既有协议兼容。

import { aes, hash, rsa } from '@composy/crypto-core'

// AES 对称加密
const encrypted = aes.encrypt('hello', 'secret-key')
const decrypted = aes.decrypt(encrypted, 'secret-key')
if (decrypted.data !== 'hello') throw new Error('AES round trip failed')

// SHA-256 哈希
hash.sha256('hello')

// RSA 非对称加密
const keyPair = rsa.generateKeyPair(2048)
rsa.encrypt('hello', keyPair.publicKey)

blowfish 导出同样是历史兼容入口,运行时实际使用 AES-256-CBC,并不提供 Blowfish 算法;新协议不要依赖它的算法名称。

DES、3DES 和该 Blowfish 兼容入口的加密必须显式传入 { allowLegacy: true },防止新业务误生成弱算法或未认证密文。解密仍可读取既有数据;新数据请使用 encryptWithAuth() 或公开 stream v2。

5. 密码哈希与隔离实例

import { createKeyManager, hashPasswordRecord, verifyPasswordRecord } from '@composy/crypto-core'

const record = hashPasswordRecord('password')
if (!verifyPasswordRecord('password', record)) throw new Error('invalid password')

// 每个应用/租户创建独立实例;持久化必须注入 storage adapter。
createKeyManager({ encrypted: true })

密码哈希 record 会保存随机 salt、KDF、迭代参数和版本;不要再使用无 salt 的重复 SHA-256。旧版重复 SHA-256 仅以 iterativeChecksum() 兼容导出保留,不能用于密码存储。 SecureStorage 在浏览器中可使用 local/sessionStorage,SSR/Node 中必须通过 storage 显式注入后端。

KeyManager 的非 memory 模式同样只接受显式 KeyManagerStorageBackend。加密持久化适配器必须同时实现 loadValue('master_salt') 与 saveValue,以便重新打开实例时恢复同一主密钥;适配器不能只报告写入成功而丢弃数据。

2. 用统一 Facade

import { createCryptoApi } from '@composy/crypto-core'

const api = createCryptoApi()

// 一站式接口
api.token.generate(32)
api.aes.encrypt('hello', 'secret-key')
api.mask.maskPhone('13800138000')

3. 认证加密

import { decryptWithAuth, encryptWithAuth } from '@composy/crypto-core'

const encrypted = encryptWithAuth('account secret', password, {
  // AAD is authenticated but intentionally not encrypted.
  aad: 'account:42',
})

const decrypted = decryptWithAuth(encrypted, password, { aad: 'account:42' })
if (!decrypted.verified) throw new Error(decrypted.error)

密码派生使用 PBKDF2-SHA256,iterations 接受 100,000 到 1,000,000(含边界),默认值为 100,000。解密会拒绝超出此范围的 envelope 元数据,避免不可信输入触发无界计算。

新建数据默认使用 AES-GCM(12 字节 nonce、16 字节认证标签)。仅在迁移既有数据时才传入 useGCM: false 以使用 AES-CBC + HMAC-SHA256;该兼容格式不应作为新数据的默认选择。

SecureStorage 和密码保护的 KeyManager.backup() 同样默认写入 AES-GCM;前者将存储 key 作为 AAD,因此不能把一个条目的密文移动到另一个 key 后继续读取。两者仍可读取既有 AES-CBC 数据以完成迁移。

4. 流式文件加密

import { streamDecrypt, streamEncrypt } from '@composy/crypto-core/stream'

const encrypted = await streamEncrypt.file(file, password, {
  chunkSize: 1024 * 1024,
})
if (!encrypted.success || !encrypted.data) throw new Error(encrypted.error)

const decrypted = await streamDecrypt.file(encrypted.data, password, encrypted.metadata)
if (!decrypted.success || !decrypted.data) throw new Error(decrypted.error)

流式 API 使用版本化二进制 AES-GCM 容器:每个分块都有独立的随机 96 位 nonce 和 128 位认证标签,并将分块序号、文件长度、salt 与格式元数据作为 AAD 认证。它保留原始二进制字节,适用于图片、视频及其他非文本文件。旧版 v1 流格式复用 IV 且没有可靠的分块边界,不能安全、确定地恢复,因此会被明确拒绝;需要从旧数据迁移时请在旧版本中解密后,再用 v2 重新加密。

历史深层路径 @composy/crypto-core/core/stream 已停止导出,因为其格式不具备安全迁移条件;请只使用 @composy/crypto-core/stream。

可靠性补充:CSPRNG.randomToken(length) 使用 URL-safe 字符采样并保证精确长度;LRUCache 的新增与更新都会遵守 maxMemorySize,单条超限时保留旧值;WorkerPool.batchEncrypt()/batchDecrypt() 在无 Worker 的 SSR/Node 环境会返回一致的能力错误,初始化部分失败时会清理已创建的 Worker。流式加密和解密 options 支持 signal?: AbortSignal,取消会在 chunk 边界或暂停等待期间生效,并清理派生 key。

单个 StreamEncryptor 实例一次只处理一个加密或解密任务;重叠调用会返回 success: false 和明确错误,不会重置当前任务的暂停/取消状态。需要并行处理时,为每个任务创建独立实例,或使用会为每次调用创建实例的 streamEncrypt.file() / streamDecrypt.file()。

5. 用 Engine Plugin

import { createCryptoEnginePlugin } from '@composy/crypto-core/engine'

await engine.use(createCryptoEnginePlugin())
// 注册 crypto:api、crypto:manager、crypto:aes、crypto:rsa 等到 engine state

6. 懒加载入口

import { aes, preload } from '@composy/crypto-core/lazy'

// 首次调用时延迟加载模块
await aes.encrypt('data', 'key')

// 预加载常用模块
await preload(['algorithms', 'utils'])

目录约定

src/
  algorithms/  加密算法实现(AES/RSA/DES/Hash/HMAC/编码/KDF)
  core/        管理器、统一 Facade、批处理、性能优化
  engine/      engine plugin 与 state/event key
  stream/      流式加解密
  types/       公共类型定义与 CryptoJS 类型增强
  utils/       安全存储、脱敏、Token、校验、限流、对象池等工具
  wasm/        可选 WebAssembly 加速
  workers/     Worker 线程池

设计原则

  1. 单一核心实现:所有加密逻辑在 core 层,适配层只做框架桥接
  2. 高性能默认:LRU 缓存、对象池、模式缓存、Worker 池
  3. 安全优先:恒定时间比较、OWASP 合规迭代、安全内存清零
  4. 优雅降级:WASM/Worker 失败时自动回退到纯 JS 实现
  5. 可扩展:createCryptoApi() 和 createCryptoEnginePlugin() 支持自定义 manager/storage

构建产物

| 目录 | 格式 | 用途 | | ------- | ---- | -------------------------------------------------------------------------------------------------------------------------------- | | dist/ | UMD | CDN 主入口与独立 Worker(index.min.js、crypto.worker.js);Worker 由 .ldesign/builder.config.ts 的 build:worker 流程生成 | | es/ | ESM | 现代打包器 import | | esm/ | ESM | 兼容输出 | | lib/ | CJS | Node.js require |

构建统一使用 @composy/builder 内置的 rolldown。build 会归一化声明文件和 lib/package.json,确保 dist/index.min.js 是实际压缩产物,并检查每个 exports 目标。UMD 检查会拒绝将 crypto-es 或 node-forge 留作外部引用,以保证 CDN 入口可独立使用。它还会验证 dist/crypto.worker.js 与其压缩版本的 Worker AES 加解密往返。CDN 使用 Worker 时可直接采用默认同目录路径,或通过 WorkerPoolOptions.workerPath 提供部署后的 Worker URL。

验证命令

# 类型检查
pnpm run type-check

# 代码规范
pnpm run lint:check

# 单元测试
pnpm run test:run

# 构建
pnpm run build

# 检查发布入口是否对应真实产物
pnpm run check:outputs

# 真实 tarball consumer:ESM、CJS、TypeScript 类型和 AES-GCM
pnpm run check:consumer

# 浏览器级 AES-GCM smoke(Windows + Microsoft Edge,需先完成构建)
pnpm run check:browser

🔗 相关链接