How to convert to string and back again with CryptoJs

做~自己de王妃 提交于 2019-12-10 19:21:51

问题


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?


回答1:


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));


来源:https://stackoverflow.com/questions/21291279/how-to-convert-to-string-and-back-again-with-cryptojs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!