DEV Community

Cristhian Leon
Cristhian Leon

Posted on

5

Encrypted localStorage with Zustand

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);
  }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (3)

Collapse
 
prakashm88 profile image
Prakash β€’

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 ?

Collapse
 
cristhianleonli profile image
Cristhian Leon β€’

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.

Collapse
 
prakashm88 profile image
Prakash β€’

Thank you .. "f12 hackers" was a nice touch πŸ˜‚

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

πŸ‘‹ Kindness is contagious

Please leave a ❀️ or a friendly comment on this post if you found it helpful!

Okay