Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Encrypted storage with localstorage
// Constants
const passphrase = 'password',
key = 'data',
object = { foo: 'bar' };
// Log original item
console.log('Original object', object);
// Store item with encryption
setItem(key, object, passphrase);
// Get item
let rObject = getItem(key, passphrase);
// Log retrieved item
console.log('Decrypted object', JSON.parse(rObject));
function setItem(key, data, passphrase) {
const ciphertext = CryptoJS.AES.encrypt(JSON.stringify(data), passphrase);
localStorage.setItem(key, ciphertext);
function getItem(key, passphrase) {
const encryptedData = localStorage.getItem(key);
const decryptedDataBytes = CryptoJS.AES.decrypt(encryptedData, passphrase);
return decryptedDataBytes.toString(CryptoJS.enc.Utf8);
function deleteItem(key) {
function deleteAll() {
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.