// 引入加密库,例如 crypto-js 中的 sm4 加密模块
// 你可以通过 npm 安装 crypto-js 或者直接在 HTML 文件中引入对应的 CDN 链接
// npm install crypto-js
const CryptoJS = require('crypto-js');
// SM4 加密函数
function encryptBySM4(message, key) {
// 将 key 转换为字节数组
const keyHex = CryptoJS.enc.Utf8.parse(key);
// 将 message 转换为字节数组
const srcs = CryptoJS.enc.Utf8.parse(message);
// 使用 SM4 算法进行加密
const encrypted = CryptoJS.SM4.encrypt(srcs, keyHex);
// 返回加密后的字符串
return encrypted.toString();
}
// SM4 解密函数
function decryptBySM4(ciphertext, key) {
// 将 key 转换为字节数组
const keyHex = CryptoJS.enc.Utf8.parse(key);
// 将 ciphertext 转换为 CipherParams 对象
const cipherParams = CryptoJS.lib.CipherParams.create({
ciphertext: CryptoJS.enc.Hex.parse(ciphertext)
});
// 使用 SM4 算法进行解密
const decrypted = CryptoJS.SM4.decrypt(cipherParams, keyHex);
// 返回解密后的字符串
return decrypted.toString(CryptoJS.enc.Utf8);
}
// 示例用法
const message = "Hello, SM4!";
const key = "1234567890abcdef"; // 16 字节的密钥
const encryptedMessage = encryptBySM4(message, key);
console.log("Encrypted:", encryptedMessage);
const decryptedMessage = decryptBySM4(encryptedMessage, key);
console.log("Decrypted:", decryptedMessage);
crypto-js
库来实现 SM4 加密和解密。可以通过 npm 安装或直接引入 CDN 链接。encryptBySM4
:decryptBySM4
:如果你无法找到 crypto-js
中的 SM4 模块,可能需要寻找其他支持 SM4 的库,或者手动实现 SM4 算法。
上一篇:js 忽略大小写
下一篇:js 加密解密
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站