前端SM4加解密问题
·
import { sm4 } from 'sm-crypto';
// ================= 优化配置 =================
const secretConfig = {
key: '2232463d332e722fb123e4bd772ff08f', // 128-bit HEX
iv: '378f9ghr01hjU2jh', // UTF8 IV(需确保转换后为32位HEX)
mode: 'cbc',
};
// ================ 增强型SM4工具类 =================
class SM4Processor {
constructor(hexKey, utf8Iv, mode) {
// 密钥校验增强
if (!/^[0-9a-fA-F]{32}$/.test(hexKey)) {
throw new Error('密钥需为32位HEX字符(128位)');
}
this._key = hexKey.toLowerCase(); // 统一小写格式
// IV转换与校验
this._iv = this.validateIV(this.stringToHex(utf8Iv));
this._mode = mode;
}
// UTF8转HEX(支持非ASCII字符)
stringToHex(str) {
return unescape(encodeURIComponent(str))
.split('')
.map((c) => c.charCodeAt(0).toString(16).padStart(2, '0'))
.join('');
}
// IV有效性验证
validateIV(hexIv) {
if (hexIv.length !== 32) {
throw new Error(`IV转换后需32位HEX,当前长度:${hexIv.length}`);
}
return hexIv;
}
// 优化加密方法
encryptData(data, isObject = true) {
const input = isObject ? JSON.stringify(data) : data;
return sm4.encrypt(input, this._key, {
mode: this._mode,
iv: this._iv,
inputEncoding: 'utf8', // 修正编码
outputEncoding: 'hex', // 输出HEX格式
});
}
// 强化解密方法
decryptData(ciphertext, isObject = true) {
const plaintext = sm4.decrypt(ciphertext, this._key, {
mode: this._mode,
iv: this._iv,
inputEncoding: 'hex', // 输入HEX格式
outputEncoding: 'utf8',
});
return isObject ? JSON.parse(plaintext) : plaintext;
}
}
// ================ 使用示例 =================
const sm4Helper = new SM4Processor(secretConfig.key, secretConfig.iv, secretConfig.mode);
const plaintext = 'testtest'; // 或传输对象{data: 'testtest'}
// 加密测试
const cipher = sm4Helper.encryptData(plaintext, false); // 第二个参数标识非JSON对象
console.log('密文:', cipher); // 预期输出类似:3c64c6294bed3cdaec5943f2303cc3eecb9b8a5f8fb38161e4c0cb045b368084
// 解密验证
console.log('解密:', sm4Helper.decryptData(cipher, false)); // 应输出testtest

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。
更多推荐



所有评论(0)