Encrypting locally stored data with JavaScript

2019-05-04 18:59发布

问题:

While I'm learning JavaScript and HTML5, I am trying to build a basic quiz app that asks some multi-choice questions that will work on the mobile web, and also as an app using PhoneGap. As questions get asked, the results get stored locally.

I want the PhoneGap version to allow offline mode, so the ability for data to be stored locally is a must. I know there is a local DB offered through PhoneGap - so I guess one option is to do it client/server for Mobile Web and local DB with PhoneGap. However, I'd rather avoid going down that route for now, as that would mean I'd have to manage more variations between the mobile web and PhoneGap versions.

Obviously don't need internet bank level security, but I need the results to be stored locally that aren't able to be easily read, but most importantly manipulated.

I initially tried using HTML5 localstorage, but I quickly realised that at least the way I was doing it, I could visibly see all the results I was storing and through the use of Chrome Developer Tools, could easily just click to change values.

When I go down the path of using encryption (I was reading this StackOverflow post with interest), it appears that for something like this this I always have to define a 'key' somewhere in the code in order to encrypt the data and then use the same key to decrypt it.

Since all of the data is stored client side, it means all I would ever have to do is find this key and run it against the stored data to manipulate results.

回答1:

Would base64 encoding work? It's built-in to the browser and it looks encrypted. People do this all the time for cookies.

Resources (Mozilla specific):

  • btoa
  • atob

See this question for more info and links for non-Mozilla browsers: JSON encode/decode base64 encode/decode in JavaScript



回答2:

CryptoJS AES. Thanks to Leigh

var text = "#rawString#";
var key = CryptoJS.enc.Base64.parse("#base64Key#");
var iv  = CryptoJS.enc.Base64.parse("#base64IV#");

console.log("Initial String:: "+text);

var encrypted = CryptoJS.AES.encrypt(text, key, {iv: iv});
console.log("Encrypted String:: "+encrypted.toString());

var decrypted = CryptoJS.AES.decrypt(encrypted, key, {iv: iv});
console.log("Decrypted String:: "+decrypted.toString(CryptoJS.enc.Utf8));

Plnkr Demo Link