I have a JSON object that I generate from serializeArray on a form which I would like to encrypt. The application I am working on is intended to run only as a local file. What would be the best option for encrypting the data?
Javascript encryption for JSON object
Asked Answered
Just an idea. Use cryptoJS as suggested in this sample:
var secret = "My Secret Passphrase";
var plainText = "the brown fox jumped over the lazy dog";
var encrypted = CryptoJS.AES.encrypt(plainText, secret);
var decrypted = CryptoJS.AES.decrypt(encrypted, secret);
document.getElementById("m1").innerHTML = encrypted;
document.getElementById("m2").innerHTML = decrypted;
document.getElementById("m3").innerHTML = decrypted.toString(CryptoJS.enc.Utf8);
<script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.2/rollups/aes.js"></script>
<label>encrypted</label>
<div id="m1"></div>
<br>
<label>decrypted</label>
<div id="m2"></div>
<br>
<label>Original message</label>
<div id="m3"></div>
and encrypt all your data before placing it in localstorage. I do not see how you can implement this beside asking some sort of password from the user.
Is CryptoJS still under development? Should I consider WebCrypto instead? –
Schmo
Use what you are comfortable with. –
Stannum
Try out this. This worked out for me well for dynamic json data as well as normal text.
var key = CryptoJS.enc.Utf8.parse("93wj660t8fok9jws");
// Please parse the your secret key
var iv = CryptoJS.enc.Utf8.parse(CryptoJS.lib.WordArray.random(128 / 8));
function encrypt(plainText) {
return CryptoJS.AES.encrypt(
plainText, key,{ iv: iv,padding:CryptoJS.pad.Pkcs7,
mode:CryptoJS.mode.CBC }).ciphertext.toString(CryptoJS.enc.Base64);
}
function decrypt(encryptedText) {
var cipherParams = CryptoJS.lib.CipherParams.create(
{
ciphertext: CryptoJS.enc.Base64.parse(encryptedText)
});
return CryptoJS.AES.decrypt(cipherParams, key, { iv: iv,
padding: CryptoJS.pad.Pkcs7,
mode: CryptoJS.mode.CBC
}).toString(CryptoJS.enc.Utf8);
}
var start = new Date().getTime();
var encrypted = encrypt(
'{\"name\": \"Sushant\", \"loves\": \"cats\"}'
);
var end = new Date().getTime();
console.log(end - start);
document.getElementById('enc').innerHTML = encrypted;
document.getElementById('dec').innerHTML = decrypt(encrypted);
© 2022 - 2024 — McMap. All rights reserved.
btoa
andatob
to convert to and from base64. This is no encryption but will prevent most users from messing up with the files and does not require an external library. – Juba