Quickstart
安装 SDK 包,并跑通加密与工具函数的第一段代码。
本指南用几分钟时间带你完成从安装到实际调用的全过程。所有 API 页面都由源码自动生成, 因此这里的示例与仓库里的实际实现始终一致。
安装
两个包都以 @guohanmin 作用域发布,按需安装即可:
pnpm add @guohanmin/encryptor
pnpm add @guohanmin/utils
两个包都提供 TypeScript 类型声明,无需额外安装 @types。
加密:从摘要到对称加密
@guohanmin/encryptor 把常见算法拆成了独立的命名导出,用到哪个引哪个,便于打包器摇树。
摘要与 HMAC
摘要函数是同步的,返回十六进制字符串:
import { md5Hash, sha256Hash, hmacSHA256 } from '@guohanmin/encryptor'
md5Hash('hello') // 32 位十六进制
sha256Hash('hello') // 64 位十六进制
hmacSHA256('hello', 'secret-key') // 带密钥的签名
MD5 只适合做校验和或与既有系统对接,不要用于密码存储等安全场景。
AES-CBC 对称加密
密钥与初始向量都要求十六进制字符串,可以先用工具函数生成:
import { aesDecrypt, aesEncrypt, aesGenerateIV, aesGenerateKey } from '@guohanmin/encryptor'
const key = aesGenerateKey(256) // 64 位十六进制,对应 AES-256
const iv = aesGenerateIV() // 32 位十六进制,固定 16 字节
const ciphertext = aesEncrypt('hello world', { key, iv }) // Base64 密文
const plaintext = aesDecrypt(ciphertext, { key, iv })
aesEncrypt 使用 Pkcs7 填充,aesDecrypt 收到的密文必须是同一组 key / iv 加密的结果。
如果偏好免填充的方案,可以改用 GCM 系列:
import { aesGcmDecrypt, aesGcmEncrypt, aesGcmGenerateKey } from '@guohanmin/encryptor'
const gcmKey = await aesGcmGenerateKey(256)
const { ciphertext: secret, iv: gcmIv } = await aesGcmEncrypt('hello world', gcmKey)
const recovered = await aesGcmDecrypt(secret, gcmKey, gcmIv)
GCM 加密时若不传 iv,函数会随机生成一个并随密文一起返回,因此调用方必须把返回的 iv 一并保存。
非对称加密
RSA 与 ECC 的密钥生成、加解密、签名验签同样是扁平导出:
import { rsaDecrypt, rsaEncrypt, rsaGenerateKeyPair, rsaSign, rsaVerify } from '@guohanmin/encryptor'
const { publicKey, privateKey } = rsaGenerateKeyPair()
const encrypted = rsaEncrypt('hello world', publicKey)
const decrypted = rsaDecrypt(encrypted, privateKey)
const signature = rsaSign('hello world', privateKey)
rsaVerify('hello world', signature, publicKey) // true
ECC 的同类函数返回 Promise,曲线通过可选的 curve 参数指定。
工具函数
@guohanmin/utils 把 radash、luxon、nanoid、qs 等库的高频方法聚合成一个入口,
省去在业务代码里逐个引入底层依赖。
import { DateTime, debounce, nanoid, unique } from '@guohanmin/utils'
nanoid() // 短随机 id
unique([1, 2, 2, 3]) // [1, 2, 3]
const search = debounce({ delay: 300 }, (keyword: string) => {
console.log(keyword)
})
日期时间全部来自 luxon,DateTime / Duration / Interval 与 luxon 的用法完全一致:
import { DateTime } from '@guohanmin/utils'
DateTime.now().plus({ days: 7 }).toISODate()
下一步
- 在左侧导航里选择具体的包,查看每个导出的完整签名、参数表与源码位置
- 按 ⌘ + K(Windows 下为 Ctrl + K)打开全局搜索,直接跳转到任意导出