Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

My CryptoJS encryption/decryption is not working

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?

like image 405
Viktor Avatar asked Sep 24 '12 23:09

Viktor


People also ask

What is secret passphrase in CryptoJS?

It means that the key (secret passphrase) used to encrypt and decrypt is the same. So, it's security relies mostly in keeping the key secure. If someone obtains the key, they will be able to decrypt anything encrypted with that passphrase.

Is CryptoJS secure?

CryptoJS is a growing collection of standard and secure cryptographic algorithms implemented in JavaScript using best practices and patterns. They are fast, and they have a consistent and simple interface.


1 Answers

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.
like image 85
Jeff M Avatar answered Sep 19 '22 14:09

Jeff M