How to pass encrypted data via browser (HTML5) session variable

£可爱£侵袭症+ 提交于 2019-12-24 00:07:20

问题


I am trying to pass encrypted data via a browser/client session variable - not to be confused with server-side session variable:

encrypt:

var encrypted_user_id = CryptoJS.AES.encrypt(user_id, cipher_pass);
var encrypted_user_password = CryptoJS.AES.encrypt(password, cipher_pass);

sessionStorage.setItem('user_id', encrypted_user_id);
sessionStorage.setItem('user_password', encrypted_user_password);

decrypt:

var encrypted_user_id = sessionStorage.getItem('user_id');
var encrypted_user_password = sessionStorage.getItem('user_password');

var plaintext_user_id = CryptoJS.AES.decrypt(encrypted_user_id, cipher_pass).toString(CryptoJS.enc.Utf8);
var plaintext_user_password = CryptoJS.AES.decrypt(encrypted_user_password, cipher_pass).toString(CryptoJS.enc.Utf8);

There is no error, but the plaintext is empty string.

If I perform the exact same encryption/decryption using variables instead of sessionStorage it works fine.

What am I not understanding? Is there something about session variables that is different than a local variable?


回答1:


So I've made a fiddle to test it out. And I think the problem (although in fairness your original code seemed to work for me too) is that for the encryption you should do this instead:

var encrypted_user_id = CryptoJS.AES.encrypt(user_id, cipher_pass).toString();

Why? Without the to string, you're storing an object that JSON can't serialize, so when you're getting your object back from session storage you're getting back something different than you intended.



来源:https://stackoverflow.com/questions/36874335/how-to-pass-encrypted-data-via-browser-html5-session-variable

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