DEV Community

Code Craft-Fun with Javascript
Code Craft-Fun with Javascript

Posted on

Encrypt your Local Storage data!

Encrypt Local Storage in the Browser

Before going further I would suggest you first check out my article on the prototypes. Yes, we will be using the prototype concept to add our custom encryption functions to the local storage API. Let's see how we can achieve this.

The localStorage function is available globally on the browser's window object. And if you have ever noticed, this function has the type Storage.

example

If you check the function definition you will notice that this Storage is an interface.

example

Now, we got to know that the localStorage has a type of Storage interface, we can manipulate the prototype object of the Storage interface and add our encryption/decryption custom functions to it.

Adding custom functions in the Storage Interface

We will use the crypto-js library for encrypting/decrypting our data. We will be using a node package manager (npm) to download this library so make sure your project is initialised by npm first.

Now install the library using the command npm install crypto-js. It will be added to the node_modules folder. We will be adding two functions named encrypt and decrypt which will handle the encryption and decryption of data.

example

Here we have taken a secret key which is passed to the functions of the crypto-js library to encrypt and decrypt the data. This secret key can be anything but it should be stored in a safe place for security.

Now, we will be adding our two custom functions to the prototype object of the Storage interface.

example

setEncryptedItem and getDecryptedItem is added to the Storage interface and will be available to our native function localStorage once our code will be executed.

Note that, before using our added custom functions, we have to first store it in the prototype of the Storage interface and therefore as per our code we are required to call manipulateLocalStorage function first.

Our whole code will look like the following -

import * as CryptoJS from 'crypto-js';

function storageEncryption() {
    /**
  * secret key should be stored in a safe place. This is only for a demo purpose.
  */
    let _key = "secret_key"

    function encrypt(txt) {
        return CryptoJS.AES.encrypt(txt, _key).toString();
    }

    function decrypt(txtToDecrypt) {
        return CryptoJS.AES.decrypt(txtToDecrypt, _key).toString(CryptoJS.enc.Utf8);
    }

    function manipulateLocalStorage() {
        Storage.prototype.setEncryptedItem = (key, value) => {
            localStorage.setItem(key, encrypt(value));
        };

        Storage.prototype.getDecryptedItem = (key) => {
            let data = localStorage.getItem(key) || "";
            return decrypt(data) || null;
        }
    }
 /**
  * First call this function to add our custom functions to the Storage interface
  * 
  */
    manipulateLocalStorage();
    /**
     * you can use the setEncryptedItem and getDecryptedItem functions
     * to encrypt and decrypt the data
     * */ 

    localStorage.setEncryptedItem("token", "12345");
    const token = localStorage.getDecryptedItem("token");
    console.log(token);
}
storageEncryption();

Enter fullscreen mode Exit fullscreen mode

Let me show you how our data got stored in the browser's local storage.

example

You can see our token 12345 is unreadable. Now let's check the decrypted value that we have printed in our console.

example

Yes! it's our decrypted token. 😃

Top comments (6)

Collapse
 
j4k0xb profile image
Info Comment hidden by post author - thread only accessible via permalink
j4k0xb

This secret key can be anything but it should be stored in a safe place for security

Where? Your functions need access to it which means an attacker (XSS) can access it as well
It's the same security level as saving plain text data in localStorage

Collapse
 
codecraftjs profile image
Code Craft-Fun with Javascript

The secret key can be generated dynamically using the environment variables configured on the server. The example above is just for a demo purpose.

Collapse
 
sonyarianto profile image
Sony AK

this is interesting, it means the key from server will be transmited to client and put on that _key var?

Collapse
 
codecraftjs profile image
Code Craft-Fun with Javascript

May be you are correct in your sense. But this was a requirement in one of the project that I was working on. So I decided to share this with all.The use case was to encrypt the business related infornation.

Collapse
 
crayoncode profile image
crayoncode

That doesn't necessarily make it a "good" requirement. As it is with most cryptographic systems the really tricky part is the key management in terms of secure generation, transmission, persistence and access management. Not knowing the exact requirement, it makes me wonder what kind of business data it is that needs to be stored on a non-trusted client in an encrypted manner that leaves open the crucial part of key management. Is the connection between client and server less trusted than the browser (a non-trusted client)?

Thread Thread
 
codecraftjs profile image
Code Craft-Fun with Javascript

Don't worry. Those were not the sensitive data. It is obvious we do not store such data in local storage. But the thing was , anything we store in the Local Storage be it a branding details or any small stuff that should also be encrypted. The secret key was generated dynamically using some discussed pattern from the data that was fetched using the authenticated APIs.

Some comments have been hidden by the post's author - find out more