import { CryptoUtil } from '@sparta-utils/crypto-util';
// ✅ AES 加密解密
import { CryptoUtil } from '@sparta-utils/crypto-util'
const key = '1234567890abcdef'
const iv = 'abcdef1234567890' // 可选,如果使用 ECB 模式可以不传
const encrypted = CryptoUtil.aes.encrypt('Hello AES', {
key,
iv,
mode: 'cbc'
})
console.log('加密后:', encrypted)
const decrypted = CryptoUtil.aes.decrypt(encrypted, {
key,
iv,
mode: 'cbc'
})
console.log('解密后:', decrypted)
// ✅ RSA 密钥生成、加密解密、签名验签
const { publicKey: rsaPub, privateKey: rsaPriv } = CryptoUtil.rsa.generateKeyPair();
const rsaEncrypted = CryptoUtil.rsa.encrypt('Hello RSA', rsaPub);
const rsaDecrypted = CryptoUtil.rsa.decrypt(rsaEncrypted, rsaPriv);
const rsaSignature = CryptoUtil.rsa.sign('RSA Message', rsaPriv);
const rsaVerified = CryptoUtil.rsa.verify('RSA Message', rsaSignature, rsaPub);
console.log('RSA验签:', rsaVerified);
// ✅ SM2 密钥生成、加密解密、签名验签
const { publicKey: rsaPub, privateKey: rsaPriv } = CryptoUtil.rsa.generateKeyPair()
console.log('RSA公钥:', rsaPub)
console.log('RSA私钥:', rsaPriv)
const rsaEncrypted = CryptoUtil.rsa.encrypt('Hello RSA', rsaPub)
console.log('RSA加密:', rsaEncrypted)
const rsaDecrypted = CryptoUtil.rsa.decrypt(rsaEncrypted, rsaPriv)
console.log('RSA解密:', rsaDecrypted)
const rsaSignature = CryptoUtil.rsa.sign('RSA Message', rsaPriv)
console.log('RSA签名:', rsaSignature)
const rsaVerified = CryptoUtil.rsa.verify('RSA Message', rsaSignature, rsaPub)
console.log('RSA验签结果:', rsaVerified)
// ✅ SM3 摘要
const sm3Hash = CryptoUtil.sm3('Hello SM3')
console.log('SM3摘要:', sm3Hash)
// ✅ SM4 加密解密
const sm4Key = '0123456789abcdef'; // 16字节密钥
const sm4Encrypted = CryptoUtil.sm4.encrypt('Hello SM4', sm4Key);
const sm4Decrypted = CryptoUtil.sm4.decrypt(sm4Encrypted, sm4Key);
console.log('SM4解密:', sm4Decrypted);
// ✅ SHA256 / SHA512
const sha256Hash = CryptoUtil.sha.sha256('Hello SHA256');
const sha512Hash = CryptoUtil.sha.sha512('Hello SHA512');
console.log('SHA256:', sha256Hash);
console.log('SHA512:', sha512Hash);
// ✅ HMAC-SHA
const hmac256 = CryptoUtil.hmac.hmac('sha256', 'hmacKey', 'HMAC Message')
const hmac512 = CryptoUtil.hmac.hmac('sha512', 'hmacKey', 'HMAC Message')
console.log('HMAC-SHA256:', hmac256)
console.log('HMAC-SHA512:', hmac512)
// ✅ MD5
const md5Hash = CryptoUtil.md5('Hello MD5');
console.log('MD5:', md5Hash);
// ✅ Base64
const base64Encoded = CryptoUtil.base64.encode('Hello Base64')
console.log('Base64编码:', base64Encoded)
const base64Decoded = CryptoUtil.base64.decode(base64Encoded)
console.log('Base64解码:', base64Decoded)
// ✅ JWT 签发与验证 浏览器不可使用 / 当前方法尚不完善
const jwtToken = CryptoUtil.jwt.sign({ uid: 1001 }, 'jwtSecretKey');
const jwtPayload = CryptoUtil.jwt.verify(jwtToken, 'jwtSecretKey');
console.log('JWT验证:', jwtPayload);