import CryptoJS from 'crypto-js' import JSEncrypt from 'jsencrypt' const publicKey = atob(import.meta.env.VITE_RSA_PUBLIC_KEY) // 生成随机 AES 密钥 export function generateAesKey(length = 16) { const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789' let key = '' for (let i = 0; i < length; i++) { key += chars.charAt(Math.floor(Math.random() * chars.length)) } return key } // AES 加密 export function aesEncrypt(data, key) { return CryptoJS.AES.encrypt(JSON.stringify(data), CryptoJS.enc.Utf8.parse(key), { mode: CryptoJS.mode.ECB, padding: CryptoJS.pad.Pkcs7 }).toString() } export function aesDecrypt(encryptedData, aesKey) { const bytes = CryptoJS.AES.decrypt(encryptedData, CryptoJS.enc.Utf8.parse(aesKey), { mode: CryptoJS.mode.ECB, padding: CryptoJS.pad.Pkcs7 }) return JSON.parse(bytes.toString(CryptoJS.enc.Utf8)) } // RSA 加密 AES 密钥 export function rsaEncryptKey(aesKey) { const encryptor = new JSEncrypt() encryptor.setPublicKey(publicKey) return encryptor.encrypt(aesKey) }