使用 JavaScript 加密本地存储的数据 [英] Encrypting locally stored data with JavaScript

查看:50
本文介绍了使用 JavaScript 加密本地存储的数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我学习 JavaScript 和 HTML5 的同时,我正在尝试构建一个基本的测验应用程序,该应用程序会询问一些适用于移动网络的多项选择题,以及作为使用 PhoneGap 的应用程序.当提出问题时,结果会存储在本地.

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.

我希望 PhoneGap 版本允许离线模式,所以数据在本地存储的能力是必须.我知道有一个通过 PhoneGap 提供的本地数据库 - 所以我想一种选择是使用 PhoneGap 为移动 Web 和本地数据库做客户端/服务器.但是,我现在宁愿避免走这条路,因为这意味着我必须管理移动网络和 PhoneGap 版本之间的更多变化.

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.

我最初尝试使用 HTML5 localstorage,但我很快意识到,至少按照我的做法,我可以通过使用 Chrome 开发者工具清楚地看到我存储的所有结果,只需单击即可轻松更改值.

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.

当我走上使用加密的道路时 (我很感兴趣地阅读了这篇 StackOverflow 帖子),看来对于这样的事情,我总是必须在代码中的某处定义一个密钥"以加密数据,然后使用相同的密钥来解密它.

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.

推荐答案

CryptoJS AES.感谢李

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 演示链接

这篇关于使用 JavaScript 加密本地存储的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆