15

I have an array of JSON arrays whose values I am trying to encrypt with CryptoJS and then print for use in another file, where these values should be decrypted using a user-given passphrase.

But I am doing something wrong and I am getting "Uncaught Error: Malformed UTF-8 data" when decrypting the URL's.

encrypt.js:

var encrypted = CryptoJS.AES.encrypt(item[key], pass);
json[j] += encrypted.ciphertext.toString(CryptoJS.enc.Base64);

decrypt.js:

var decrypted = CryptoJS.AES.decrypt(item[key], pass);
html += '<a href="' + decrypted.toString(CryptoJS.enc.Utf8) + '" target="_blank" class="socialico ' + key + '">' + icons[key] + '</a>';

I followed this example... Help, pretty please?

Viktor
  • 487
  • 2
  • 8
  • 26

1 Answers1

16

That error message usually means the data wasn't decrypted correctly, and the resulting plaintext bytes don't form valid UTF-8 characters.

A couple things to check:

  • First, make sure you're using the same password for both encryption and decryption. You may want to keep a hash of the correct password so that you can verify if the user gave the correct password before you use it for decryption.
  • Second, make sure that the value item[key] is a string before encrypting. CryptoJS can't encrypt JSON objects. You'll have to serialize it first.
Rajesh
  • 24,354
  • 5
  • 48
  • 79
Jeff M
  • 2,492
  • 3
  • 22
  • 38
  • Thank you for your interest. I used the same `var pass = 'something'` in both files and `console.log(typeof(item[key]) == 'string')` printed true for all items. – Viktor Sep 26 '12 at 23:27
  • 10
    Ahh. I noticed another likely problem. You need to use the same IV for decryption as was used during encryption. Normally the IV is serialized along with the ciphertext, but you're explicitly saving only the ciphertext, without the IV. Try changing `encrypted.ciphertext.toString(CryptoJS.enc.Base64)` to `encrypted.toString()` – Jeff M Sep 28 '12 at 10:11
  • Oh, thank you! I removed the `ciphertext` and `Base64` and now it seems to work. Now I got me a pretty secure webpage using just JavaScript! That's pretty, pretty cool. – Viktor Sep 29 '12 at 18:59