Last active
August 3, 2023 05:08
-
-
Save mfcodeworks/39fa11af6e920d854efd851105816fb2 to your computer and use it in GitHub Desktop.
Encrypted storage with localstorage
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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) { | |
localStorage.removeItem(key); | |
} | |
function deleteAll() { | |
localStorage.clear(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment