import CryptoJS from 'crypto-js' const KEY = 'abcdefgabcdefg64' const IV = 'abcdefgabcdefg64' export class AESUtil { private static KEY = CryptoJS.enc.Utf8.parse(KEY) private static IV = CryptoJS.enc.Utf8.parse(IV) /** * AES 加密 */ static encrypt(data: string): string { try { // 将数据转换为字节数组并进行填充 const dataBytes = CryptoJS.enc.Utf8.parse(data) const blockSize = 16 const paddingLength = blockSize - (dataBytes.sigBytes % blockSize) const paddingWords = [] for (let i = 0; i < paddingLength; i++) { paddingWords.push(0) } const padding = CryptoJS.lib.WordArray.create(paddingWords) const paddedData = dataBytes.concat(padding) // 加密 const encrypted = CryptoJS.AES.encrypt(paddedData, this.KEY, { iv: this.IV, mode: CryptoJS.mode.CBC, padding: CryptoJS.pad.NoPadding }) // 转换为Base64 return encrypted.ciphertext.toString(CryptoJS.enc.Base64) } catch (error) { console.error('Encryption failed:', error) throw new Error('加密失败') } } /** * AES 解密 */ static decrypt(data: string): string { try { // 将Base64字符串转换为CipherParams对象 const ciphertext = CryptoJS.enc.Base64.parse(data) const cipherParams = CryptoJS.lib.CipherParams.create({ ciphertext: ciphertext }) // 解密 const decrypted = CryptoJS.AES.decrypt(cipherParams, this.KEY, { iv: this.IV, mode: CryptoJS.mode.CBC, padding: CryptoJS.pad.NoPadding }) // 转换为字符串并去除填充 return decrypted.toString(CryptoJS.enc.Utf8).replace(/\x00+$/, '') } catch (error) { console.error('Decryption failed:', error) throw new Error('解密失败') } } /** * 测试方法 */ static test() { const testData = '11212121' console.log('原始数据:', testData) const encrypted = this.encrypt(testData) console.log('加密后:', encrypted) const decrypted = this.decrypt(encrypted) console.log('解密后:', decrypted) // 测试Java加密的数据 const javaEncrypted = '/g2wzfqvMOeazgtsUVbq1kmJawROa6mcRAzwG1/GeJ4=' console.log('Java加密数据解密:', this.decrypt(javaEncrypted)) } }