How to encrypt localStorage data in Angular?

Introduction

How to use and What to use?

then npm i crypto-js
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;}});}
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();}}
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

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store