Improve local storage

This commit is contained in:
Peter Maquiran
2021-07-18 20:20:30 +01:00
parent b6b95d929f
commit f5e65c1477
7 changed files with 61 additions and 34 deletions
+20 -8
View File
@@ -1,36 +1,48 @@
import { Injectable } from '@angular/core';
import { SHA1, SHA256, AES, enc } from 'crypto-js'
import { AES, enc, SHA1 } from 'crypto-js'
@Injectable({
providedIn: 'root'
})
export class LocalstoreService {
constructor() { }
private prefix = 'v0-'
constructor() { }
get( keyName, safe) {
keyName = this.prefix + keyName
const ciphertext = localStorage.getItem(keyName)
const hashKey = SHA1(keyName).toString()
if(ciphertext) {
const bytes = AES.decrypt(ciphertext, keyName)
var decryptedData = JSON.parse(bytes.toString(enc.Utf8));
const bytes = AES.decrypt(ciphertext, hashKey)
var decryptedData = bytes.toString(enc.Utf8);
if(typeof(decryptedData) != 'string') {
decryptedData = JSON.parse(decryptedData)
}
return decryptedData;
} else {
return safe;
}
}
set(key, value) {
set(keyName, value) {
keyName = this.prefix + keyName
if(typeof(value) != 'string') {
value = JSON.stringify(value)
}
}
const hashKey = SHA1(keyName).toString()
const data = value
const encoded = AES.encrypt( data, key).toString();
localStorage.setItem(key, encoded)
const encoded = AES.encrypt( data, hashKey).toString();
localStorage.setItem(keyName, encoded)
}
}