I don't know if anyone finds this any useful, but I had a specific requirement to save the localStorage data encrypted. Using zustand I created this snippet to persist my data.
import { PersistStorage } from "zustand/middleware";
import CryptoJS from "crypto-js";
export class EncryptedStorage implements PersistStorage<any> {
getItem(key: string): any | undefined {
const value = localStorage.getItem(key);
if (value) {
const decryptedBytes = CryptoJS.AES.decrypt(value, <YOUR_NONCE>)
const decryptedValue = decryptedBytes.toString(CryptoJS.enc.Utf8);
return decryptedValue
}
return value
}
setItem(key: string, value: any): void {
const encrypted = CryptoJS.AES.encrypt(value, <YOUR_NONCE>).toString()
localStorage.setItem(key, encrypted);
}
removeItem(key: string): void {
localStorage.removeItem(key);
}
}
Top comments (3)
Could you pls explain the ysecase behind the implementation. As both encryption and decryption both happens in UI, isn't it possible to decrypt the value easily ?
Yeah sure, there is a certification that requires that even data saved to local/session storage is encrypted. Probably this is to avoid regular users to modify the local data. Though, advanced users can get access to it, by de-obfuscating the code, and getting the key, decrypting, modifying the value, encrypting again... I guess that's annoying for the "f12 hackers". As I mentioned, this is for a security certification requirement, not everyone needs this.
Thank you .. "f12 hackers" was a nice touch π