注意点
前后端的秘钥和偏移量IV都必须是16/24/32字节,且需要保持一致。
后端
func (receiver *basicUtils) AesDecrypt(str string) string {// 将加密字符串转换为字节数组encryptedData, _ := base64.StdEncoding.DecodeString(str)// 创建一个新的AES解密器key := []byte(global.GVA_CONFIG.App.Secret) // 密钥与前端保持一致iv := []byte(global.GVA_CONFIG.App.SecretIv) // 偏移量与前端保持一致block, _ := aes.NewCipher(key)// 使用CBC模式解密mode := cipher.NewCBCDecrypter(block, iv)decryptedData := make([]byte, len(encryptedData))mode.CryptBlocks(decryptedData, encryptedData)// 移除填充padding := int(decryptedData[len(decryptedData)-1])decryptedData = decryptedData[:len(decryptedData)-padding]// 将解密后的字节数组转换为字符串decryptedStr := string(decryptedData)return decryptedStr
}
前端
import CryptoJS from "crypto-js"class Crypto {encrypt = (str: string): string => {const _key = CryptoJS.enc.Utf8.parse(import.meta.env.VITE_BASE_SECRET)const _str = CryptoJS.enc.Utf8.parse(str)const _iv =CryptoJS.enc.Utf8.parse(import.meta.env.VITE_BASE_SECRET_IV)return CryptoJS.AES.encrypt(_str, _key,{iv:_iv,mode:CryptoJS.mode.CBC,padding:CryptoJS.pad.Pkcs7}).toString()}decrypt = (str: string): string => {const _iv =CryptoJS.enc.Utf8.parse(import.meta.env.VITE_BASE_SECRET_IV)const _key = CryptoJS.enc.Utf8.parse(import.meta.env.VITE_BASE_SECRET)return CryptoJS.AES.decrypt(str, _key,{iv:_iv,mode:CryptoJS.mode.CBC,padding:CryptoJS.pad.Pkcs7}).toString(CryptoJS.enc.Utf8)}cryptCheck = (str1: string, str2: string): boolean => str1 === this.decrypt(str2)
}export const crypto = new Crypto()