import Crypto from 'crypto-js'; class AESCrypto { /** * 密钥 * @type {string} */ static _AES_KEY = import.meta.env.VITE_AES_KEY; /** * AES加密 * @param context {string} 加密内容 */ static encrypt = (context) => { 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, }; } /** * AES解密 * @param context {string} * @param iv {string} * @return {string} */ 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; } } export default AESCrypto;