How to encrypt localStorage data in Angular?

We are going to learn how to encrypt local storage data and how to create a proper service for it.

Introduction

There is a method where you can encrypt your local storage data.

Prerequisite

Angular and Node.js should be installed on your system and you should have little knowledge of Angular and Angular services.

Folder Structure

services —
-storage.services.ts
-local.service.ts

How to use and What to use?

First, run npm install secure-web-storage and

then npm i crypto-js

Now add this code to storage.service.ts.

import { Injectable } from '@angular/core';import SecureStorage from 'secure-web-storage';const SECRET_KEY = 'secret_key';import CryptoJS from 'crypto-js';
@Injectable({
providedIn: 'root'
})
export class StorageService {constructor() { }public secureStorage = new SecureStorage(localStorage, {hash: function hash(key): any {
key = CryptoJS.SHA256(key, SECRET_KEY);
return key.toString();
},
// Encrypt the localstorage dataencrypt: function encrypt(data) {
data = CryptoJS.AES.encrypt(data, SECRET_KEY);
data = data.toString(); return data;},// Decrypt the encrypted datadecrypt: function decrypt(data) { data = CryptoJS.AES.decrypt(data, SECRET_KEY); data = data.toString(CryptoJS.enc.Utf8); return data;}});}

and this one to local.service.ts

import { Injectable } from ‘@angular/core’;import { StorageService } from ‘./storage.service’;@Injectable({providedIn: ‘root’})export class LocalService {constructor(private storageService: StorageService) { }// Set the json data to local storagesetJsonValue(key: string, value: any) {    this.storageService.secureStorage.setItem(key, value);}// Get the json value from local storagegetJsonValue(key: string) {    return this.storageService.secureStorage.getItem(key);}// Clear the local storageclearToken() {    return this.storageService.secureStorage.clear();}}

Now you only have to use the LocalService file in your component.

Let you are working in home.component.ts, So inside the HomeComponent import the LocalService file.

import { LocalService } from 'path_of local.service.ts';constructor(private localService: LocalService) {}setLocalStorage() {
// Set the User data
this.localService.setJsonValue('user', JSON_DATA_OF_USER);
}
getLocalStorage() {
// Get the user data
const user = this.localService.getJsonValue('user');
}
logoutUser() {
// Clear the localStorage
this.localService.clearToken();
}

Conclusion

Thank you for your time.

Full Stack Developer || Javascript Developer