Search code examples
javascripthtmlencodingsession-variablescryptojs

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


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?


Solution

  • 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.