// 首先,确保你已经安装了crypto-js库
|
// npm install crypto-js
|
|
// import CryptoJS from "crypto-js";
|
|
|
// 密钥(请确保密钥的安全性,不要硬编码在源代码中)
|
// 16/24/32 字节, 对应 AES-128/192/256
|
|
// 加密函数
|
// export function encryptObject(obj, key) {
|
// // 将对象转换为字符串
|
// const str = JSON.stringify(obj);
|
|
// // 使用AES算法加密
|
// // const encrypted = CryptoJS.AES.encrypt(str, key).toString();
|
|
// const encrypted = CryptoJS.AES.encrypt(str,key);
|
// console.log(encrypted)
|
// const encryptedBase64 = CryptoJS.enc.Base64.stringify(encrypted.ciphertext);
|
|
// return encryptedBase64;
|
// }
|
|
// // 解密函数
|
// export function decryptObject(encrypted, key) {
|
// // 使用AES算法解密
|
// // const bytes = CryptoJS.AES.decrypt(encrypted, key);
|
|
// // // 将解密后的数据转换为字符串
|
// // const str = bytes.toString(CryptoJS.enc.Utf8);
|
|
// // // 将字符串转换回对象
|
// // const obj = JSON.parse(str);
|
|
// // return obj;
|
|
|
// var bytes = CryptoJS.enc.Base64.parse(encrypted);
|
// var decrypted = CryptoJS.AES.decrypt({ciphertext: bytes}, key);
|
// return decrypted.toString(CryptoJS.enc.Utf8);
|
// }
|
|
|
import CryptoJS from 'crypto-js';
|
|
const KEY = CryptoJS.enc.Utf8.parse("f$9Lz#Q@1vT!eW2%"); // AES 128 密钥
|
|
// 加密
|
export function encrypt(plainText) {
|
const encrypted = CryptoJS.AES.encrypt(
|
plainText,
|
KEY,
|
{
|
mode: CryptoJS.mode.ECB,
|
padding: CryptoJS.pad.Pkcs7
|
}
|
);
|
return encrypted.toString(); // 已是 Base64 编码的密文
|
}
|
|
// 解密
|
export function decrypt(cipherText) {
|
const decrypted = CryptoJS.AES.decrypt(
|
cipherText,
|
KEY,
|
{
|
mode: CryptoJS.mode.ECB,
|
padding: CryptoJS.pad.Pkcs7
|
}
|
);
|
return decrypted.toString(CryptoJS.enc.Utf8); // 转回原始字符串
|
}
|