使用角2.我在執行一個本地存儲服務(與加密)。目前,這只是我使用它的一個模塊,但我想確保它是可重用的。localStorage的作爲服務
這是我的頁面的.ts:
我提供了一個存儲前綴。我假設它應該有哪個應用它與相關的指示,所以它的預前綴myApp-,其次是一個前綴,這將是獨此模塊(Frequentclients)。
export class SwitchClientComponent implements OnInit {
storagePrefix = 'myApp-Frequentclients';
getFrequentClients() {
return this.encryptionService.getLocalStorage(this.storagePrefix);
};
}
我的加密存儲服務:
import * as CryptoJS from "crypto-js";
@Injectable()
export class EncryptionService {
constructor() {
}
secretKey: string = "fnord";
setLocalStorage(storagePrefix: string, jsonObj) {
localStorage.setItem(storagePrefix, this.encrypt(jsonObj));
}
getLocalStorage(storagePrefix: string) {
var recentClients = [],
data: string = localStorage.getItem(storagePrefix);
if (data !== null && data.length > 0) {
data = this.decrypt(data);
if (data !== null && data.length > 0) {
recentClients = JSON.parse(data) || [];
}
}
return recentClients;
}
encrypt(jsonObj) {
return CryptoJS.AES.encrypt(JSON.stringify(jsonObj), this.secretKey);
}
decrypt(data) {
if (data !== null && data.length > 0) {
var bytes = CryptoJS.AES.decrypt(data.toString(), this.secretKey);
return bytes.toString(CryptoJS.enc.Utf8);
} else {
return "";
}
}
如果每次使用本地存儲模塊只是用相同的前綴,他們就要揍對方,對吧?
所以每次使用都會有它自己的,因此:
myApp-DavesModuleData : [{data:'foo'}]
myApp-OtherModuleData : [{data:'bar'}]
或者,我應該避開了數不勝數的本地存儲文件亂扔用戶的存儲,並且只使用一個?
myApp : [{DavesModule:{data:'foo'}},{OtherModule:{data:'bar'}}]
然後我不得不每次讀取本地存儲讀取整個事情,然後分析它找到我要找的部分 - 並再次寫了這一切。
(也就是說,如果任何模塊弄亂其數據,它潛在地帶來了每一個其他使用本地存儲的一個急剎車 - 包括失存儲數據)。
順便說一句,我使用的角2原生的本地存儲。現在我遇到了這些挑戰,我開始懷疑是否有人已經編寫了一個插件來完成複雜的本地存儲管理。
這個答案完全錯過了加密中的安全錯誤。 – zaph
我真的找不到有關安全錯誤的問題,請問您能爲我指出嗎? – Bolza
我不知道答案,只是注意到在OP的示例代碼中也存在安全錯誤。 – zaph