ylbtech-Error-Javascript:Uncaught Error: Malformed UTF-8 data at Object.stringify (crypto-js.js:478) at WordArray.init.toString (crypto-js.js:215)
Generally speaking, encryption and decryption operations are rarely carried out on the front end, because there is not much necessity. The front-end code is easy to see. Even so, I think there is still something to deal with, at least not to let others see the information at a glance
I use localstorage to store the user name, nickname and other information. I use crypto JS to encrypt and decrypt. Here I use AES encryption algorithm to process the JSON object data
According to the official example, as follows
var CryptoJS = require("crypto-js");
var data = [{id: 1}, {id: 2}]
// Encrypt
var ciphertext = CryptoJS.AES.encrypt(JSON.stringify(data), 'secret key 123');
// Decrypt
var bytes = CryptoJS.AES.decrypt(ciphertext.toString(), 'secret key 123');
var decryptedData = JSON.parse(bytes.toString(CryptoJS.enc.Utf8));
console.log(decryptedData);
There is no problem with the above code running in chrome, but in Safari, malformed UTF-8 data
is reported
Maybe there are few scenarios of front-end encryption and decryption, and some errors are found, but there are few solutions. One of them says that the encrypted data is not an integral multiple of 8, and the above errors will be reported
solution: encrypt the data, and then process it with Base64
method
let newUserInfo = {nickname:'hello',email:'[email protected]'};
//Encrypting data
let encJson = cryptoJS.AES.encrypt(JSON.stringify(newUserInfo), 'aes').toString();
// base64 processing of encrypted data, the principle: is to first convert the string to an array of utf8 characters, and then converted to base64 data
let encData = cryptoJS.enc.Base64.stringify(cryptoJS.enc.Utf8.parse(encJson));
localStorage.setItem('userInfo', encData);
//restore the data to base64 first, then to utf8 data
let decData = cryptoJS.enc.Base64.parse(localStorage.getItem('userInfo')).toString(cryptoJS.enc.Utf8);
// Decrypt the data
let decJson = cryptoJS.AES.decrypt(decData, 'aes').toString(cryptoJS.enc.Utf8);
userInfo = JSON.parse(decJson);
console.log(userInfo);
Above, running in Safari, chrome and firebox is no problem
Similar Posts:
- Kingbasees supports column encryption
- How to Solve Error: Unexpected token o in JSON at position 1
- Laravel project login error: the MAC is invalid
- [Solved] exception is java.lang.NoClassDefFoundError: com.sun.crypto.provider.SunJCE
- Analysis of some records in the process of cracking rar password with hashcat and the error reported by separator unmatched
- Wechat applet decrypts encrypteddata error: pad block corrupted solution
- When parsing background JSON data with Ajax: unexpected token o in JSON at position 1
- IDEA sun.misc.BASE64Encoder
- Unexpected token ‘ in JSON at position 2 at JSON.parse