加密工具类 提供安全的加密和解密功能,支持AES-256-GCM加密算法 包含数据加密、敏感字段处理、密钥管理等功能
// 生成密钥const { key, salt } = await EncryptionUtils.generateKey('my-password')// 加密数据const encrypted = EncryptionUtils.encrypt('secret data', key)// 解密数据const decrypted = EncryptionUtils.decrypt(encrypted, key)// 加密敏感字段const data = { username: 'john', password: 'secret' }const encryptedData = EncryptionUtils.encryptSensitiveFields( data, key, ['password']) Copy
// 生成密钥const { key, salt } = await EncryptionUtils.generateKey('my-password')// 加密数据const encrypted = EncryptionUtils.encrypt('secret data', key)// 解密数据const decrypted = EncryptionUtils.decrypt(encrypted, key)// 加密敏感字段const data = { username: 'john', password: 'secret' }const encryptedData = EncryptionUtils.encryptSensitiveFields( data, key, ['password'])
Static
从密码生成加密密钥(异步版本) 使用 scrypt 密钥派生函数从密码生成安全的加密密钥
密码
Optional
盐值,如果不提供则自动生成
加密密钥和盐值
const { key, salt } = await EncryptionUtils.generateKey('my-password')// 保存 salt 以便后续使用 Copy
const { key, salt } = await EncryptionUtils.generateKey('my-password')// 保存 salt 以便后续使用
加密数据
要加密的数据
加密密钥
加密后的数据(包含盐值、IV和认证标签)
解密数据 解密使用 encrypt 方法加密的数据
Base64 编码的加密数据
解密密钥
解密后的原始数据
const decrypted = EncryptionUtils.decrypt(encrypted, key) Copy
const decrypted = EncryptionUtils.decrypt(encrypted, key)
加密对象中的敏感字段 只加密指定的敏感字段,其他字段保持不变
要加密的对象
敏感字段列表
加密后的对象
const data = { username: 'john', password: 'secret', email: 'john@example.com' }const encrypted = EncryptionUtils.encryptSensitiveFields( data, key, ['password', 'email']) Copy
const data = { username: 'john', password: 'secret', email: 'john@example.com' }const encrypted = EncryptionUtils.encryptSensitiveFields( data, key, ['password', 'email'])
解密对象中的敏感字段 解密使用 encryptSensitiveFields 方法加密的敏感字段
要解密的对象
解密后的对象
const decrypted = EncryptionUtils.decryptSensitiveFields( encryptedData, key, ['password', 'email']) Copy
const decrypted = EncryptionUtils.decryptSensitiveFields( encryptedData, key, ['password', 'email'])
生成安全的随机密码 生成包含大小写字母、数字和特殊字符的随机密码
密码长度,默认为16
随机生成的密码
const password = EncryptionUtils.generateRandomPassword(20) Copy
const password = EncryptionUtils.generateRandomPassword(20)
屏蔽敏感数据(用于日志记录) 将敏感字段的部分字符替换为星号,用于安全地记录日志
要屏蔽的数据
屏蔽后的数据
const data = { username: 'john', password: 'secret123', email: 'john@example.com' }const masked = EncryptionUtils.maskSensitiveData(data, ['password', 'email'])// { username: 'john', password: 'se****23', email: 'jo****om' } Copy
const data = { username: 'john', password: 'secret123', email: 'john@example.com' }const masked = EncryptionUtils.maskSensitiveData(data, ['password', 'email'])// { username: 'john', password: 'se****23', email: 'jo****om' }
加密工具类 提供安全的加密和解密功能,支持AES-256-GCM加密算法 包含数据加密、敏感字段处理、密钥管理等功能
Example