今天遇到js端解密后端AES加密数据报错Malformed UTF-8 data 的问题,找了不少才找的这个方法。还是国外的大佬厉害。
①key要32位数的
Key Length: Ensure your key is 32 bytes for AES-256.
完整的demo
<script>
import CryptoJS from 'crypto-js';//引入库
export default {
data() {
return {
};
},
onLoad: function (options) {
let that = this;
this.test()//调用测试
},
methods: {
test() {
let result = '你的密文';
let iv = 'x0hG4kWKLzrib0M8XXcMEg==';//你的iv,我这里用过base64加密了
let key = '你的可以';//要32位!!!!
let method = 'AES-256-CBC';
// Parse IV using CryptoJS
iv = CryptoJS.enc.Base64.parse(iv);//先base64解密iv
//解密密文
try {
// Assuming `result` is already a Base64 encoded string
result = CryptoJS.enc.Base64.parse(result);
// Decrypt result
result = CryptoJS.AES.decrypt(
{ciphertext: result},
CryptoJS.enc.Utf8.parse(key), // Convert key to WordArray
{
iv: iv,
mode: CryptoJS.mode.CBC,
padding: CryptoJS.pad.Pkcs7
}
);
// Convert decrypted data to UTF-8 string
result = result.toString(CryptoJS.enc.Utf8);
result = decodeURIComponent(escape(atob(result)));//很重要,中文防止乱码
console.log('Decrypted and Decoded Result:', JSON.parse(result));//因为的我数据用了json加密,所以这里json解密一下
} catch (error) {
console.error('Error during decryption:', error);
}
},
}
};
</script>