Skip to content

Instantly share code, notes, and snippets.

@alisafariir
Created March 4, 2024 17:15
Show Gist options
  • Save alisafariir/7ccb4ddb3169f02de935dfa19bed0ed2 to your computer and use it in GitHub Desktop.
Save alisafariir/7ccb4ddb3169f02de935dfa19bed0ed2 to your computer and use it in GitHub Desktop.
Angular LocalStorage Service With Encryption
import { Injectable } from '@angular/core';
import * as CryptoJS from 'crypto-js';
const SECRET_KEY = 'ooG7ImX5GKl6MQBX7GQU1Swi';
@Injectable({
providedIn: 'root',
})
export class StorageService {
set(key: string, value: unknown) {
const encrypted = CryptoJS.AES.encrypt(
JSON.stringify(value),
SECRET_KEY
).toString();
return localStorage.setItem(key, encrypted);
}
get(key: string) {
const encrypted = localStorage.getItem(key) || '';
const decrypted = CryptoJS.AES.decrypt(encrypted, SECRET_KEY).toString(
CryptoJS.enc.Utf8
);
return encrypted ? JSON.parse(decrypted) : {};
}
remove(key: string) {
return localStorage.removeItem(key);
}
clear() {
return localStorage.clear();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment