9
var encrypted = CryptoJS.AES.encrypt(jsonStr, 'youngunicornsrunfree', { format: JsonFormatter });

//convert encrypted to a string for transfer
//convert string back to Crypto object so it can be decrypted.

var decrypted = CryptoJS.AES.decrypt(encrypted, "youngunicornsrunfree", { format: JsonFormatter });

The above two steps, work fine. But in between I need to convert encrypted to a string for transmitting over a network and then convert it back. How can I do this?

jAC
  • 5,195
  • 6
  • 40
  • 55
williamsandonz
  • 15,864
  • 23
  • 100
  • 186

1 Answers1

27

Let's simplify this to be able to get to the problem. Firs we start with something like this:

jsonStr = '{"something":"else"}';
var encrypted = CryptoJS.AES.encrypt(jsonStr, 'youngunicornsrunfree');
var decrypted = CryptoJS.AES.decrypt(encrypted, "youngunicornsrunfree");
console.log(decrypted.toString(CryptoJS.enc.Utf8));

This gives us our answer jsonStr after we encrypt it then decrypt it. But say we want to send it to the server. We can do this easily by pulling out the encrypted string with toString(). Sounds to simple right? Say we need to send the encrypted jsonStr to the server. Try this

jsonStr = '{"something":"else"}';
var encrypted = CryptoJS.AES.encrypt(jsonStr, 'youngunicornsrunfree');
console.log("We send this: "+encrypted.toString());

Now say we sent something earlier and we are getting it back. We can do something like this:

var messageFromServer = "U2FsdGVkX19kyHo1s8+EwNuo/LQdL3RnSoDHU2ovA88RtyOs+PvpQ1UZssMNfflTemaMAwHDbnWagA8lQki5kQ==";
var decrypted = CryptoJS.AES.decrypt(messageFromServer, "youngunicornsrunfree");
console.log(decrypted.toString(CryptoJS.enc.Utf8));
DutGRIFF
  • 5,103
  • 1
  • 33
  • 42
  • 2
    This isn't working unfortunately. I get a blank string. If I decrypt the encrypted without converting it to a string it works fine, it fails once I convert it to a string. (even using your simple example) – williamsandonz Jan 23 '14 at 00:31
  • @Baconbeastnz With blank results you are most likely not typing the password or the encrypted message right. Try running this in console on the page that contains the scripts `CryptoJS.AES.decrypt(CryptoJS.AES.encrypt('It works!!!', 'pass').toString(), 'pass').toString(CryptoJS.enc.Utf8)` If it works then you are probably manipulating the encrypted message before decrypting or using the wrong password. – DutGRIFF Jan 23 '14 at 01:36