2025-05-08 19:54:38 +08:00
|
|
|
import Crypto from 'crypto-js';
|
2025-03-25 16:35:39 +08:00
|
|
|
|
|
|
|
|
class AESCrypto {
|
|
|
|
|
/**
|
|
|
|
|
* 密钥
|
|
|
|
|
* @type {string}
|
|
|
|
|
*/
|
2025-05-08 19:54:38 +08:00
|
|
|
static _AES_KEY = import.meta.env.VITE_AES_KEY;
|
2025-03-25 16:35:39 +08:00
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* AES加密
|
|
|
|
|
* @param context {string} 加密内容
|
|
|
|
|
*/
|
|
|
|
|
static encrypt = (context) => {
|
2025-05-08 19:54:38 +08:00
|
|
|
const IV = this.createIV();
|
|
|
|
|
return {
|
|
|
|
|
context: Crypto.AES.encrypt(
|
|
|
|
|
context,
|
|
|
|
|
Crypto.enc.Utf8.parse(this._AES_KEY),
|
|
|
|
|
{
|
|
|
|
|
iv: Crypto.enc.Utf8.parse(IV),
|
|
|
|
|
mode: Crypto.mode.CBC,
|
|
|
|
|
padding: Crypto.pad.Pkcs7
|
|
|
|
|
}
|
|
|
|
|
).toString(),
|
|
|
|
|
iv: IV,
|
|
|
|
|
};
|
2025-03-25 16:35:39 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* AES解密
|
|
|
|
|
* @param context {string}
|
2025-05-08 19:54:38 +08:00
|
|
|
* @param iv {string}
|
2025-03-25 16:35:39 +08:00
|
|
|
* @return {string}
|
|
|
|
|
*/
|
2025-05-08 19:54:38 +08:00
|
|
|
static decrypt = (context, iv) => {
|
|
|
|
|
return Crypto.AES.decrypt(
|
|
|
|
|
context,
|
|
|
|
|
Crypto.enc.Utf8.parse(this._AES_KEY),
|
|
|
|
|
{
|
|
|
|
|
iv: Crypto.enc.Utf8.parse(iv),
|
|
|
|
|
mode: Crypto.mode.CBC,
|
|
|
|
|
padding: Crypto.pad.Pkcs7
|
|
|
|
|
}
|
|
|
|
|
).toString(Crypto.enc.Utf8);
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
static createIV = (length = 16) => {
|
|
|
|
|
const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
|
|
|
|
|
let result = '';
|
|
|
|
|
for (let i = 0; i < length; i++) {
|
|
|
|
|
const randomIndex = Math.floor(Math.random() * characters.length);
|
|
|
|
|
result += characters[randomIndex];
|
|
|
|
|
}
|
|
|
|
|
return result;
|
2025-03-25 16:35:39 +08:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export default AESCrypto;
|