Tag Archives: Error-Javascript

[Solved] Error-Javascript: Uncaught Error: Malformed UTF-8 data at Object.stringify (crypto-js.js:478) at W…

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