javascript - 如何检查浏览器的 Storage 对象是 localStorage 还是 sessionStorage 来管理客户端中的静态/动态密钥?
问题描述
我设计了一个可装饰的存储服务,其中一个示例类似于getExpirableStorage(getSecureStorage(getLocalStorage() | getSessionStorage()))
typescript/javascript。
为了实现getSecureStorage
,我使用硬编码的静态密码密钥并加密要添加到本地或会话存储的键/值对的每个值。
由于我们已经将密钥保存在客户端中,因此我决定在每次过期后动态生成密钥,以防止用户以某种方式从源获取密钥并与他人共享该密钥的情况。在这种情况下,我需要为每个不同的键/值存储每个新的 cipherKey。
createSecureStorage(storage: Storage): Storage {
var cipherKeyMap = this.keyMapping;
let privateState = function() {
let cipherKey;
this.encrypt = function(key: string, data: string): string {
let entry = cipherKeyMap.find(entry => entry.key === key);
if (entry) {
cipherKey = entry.cipherKey;
} else {
cipherKey = Array.from({length: 16}, () => Math.floor(Math.random() * 90));
cipherKeyMap.push({"key": key, "cipherKey": cipherKey});
//...
};
this.decrypt = function(key: string, data: string): string {
//...
};
}
let state = new privateState();
return {
setItem(key: string, value: string) {
//...
},
getItem(key: string) {
//...
},
//is triggered from expirableSecureStorage
removeItem(key: string) {
storage.removeItem(key);
cipherKeyMap.splice(cipherKeyMap.findIndex(r => r.key === key), 1);
}
}
}
上面的函数适用于两者localStorage
,sessionStorage
它们的类型为Storage
并且也导出为
//lib.dom.d.ts
declare var sessionStorage: Storage;
declare var localStorage: Storage;
此服务将用于来自多个客户端的多个案例,以获取将保存在这些存储中的值。
对于该createSecureStorage
功能,我意识到如果传递的存储是localStorage
,当用户关闭选项卡/窗口时,应用程序状态将消失,我将丢失密钥,但相关数据将保留在本地存储中,并使用这些密钥加密。
我想我必须做其中之一:
- 在 localStorage 的情况下管理随机生成的密码密钥的持久性或清除。
- 或者仅将使用硬编码静态密码密钥加密的值放入 localStorage,并将通过动态生成的密码密钥加密的值放入 sessionStorage
我选择 #2 是因为我不想在客户端中保留密码密钥,因为我们当前的状态也不是非常安全。
因此,要做到这一点,我认为我需要区分 localStorage 和 sessionStorage。
如何区分 sessionStorage 和 localStorage?
解决方案
要确定您传递的对象是否是localStorage
,或者sessionStorage
您可以只比较它们,因为对象是通过引用进行比较的。
function getStorage(storage){console.log(storage === localStorage)};
getStorage(localStorage);
getStorage(sessionStorage);
推荐阅读
- jquery - 窗口加载上的 JQuery FadeIn 不起作用
- google-apps-script - 调整谷歌幻灯片中图像的裁剪而不扭曲它
- c - 用C覆盖文件的内容
- python - 如何上传文件并使用其内容填充网站的某些部分?
- embedded-linux - 在 Yocto Recipe 中的 x86 主机上为 ARM 执行交叉编译的二进制文件
- c++ - 如何使 QWidget 自动垂直缩放到它的内容?
- json - Azure 数据工厂 v2 数据转换
- php - PHP:找出关联数组中具有相同值的所有键
- reactjs - 错误:缩小反应错误 #130
- google-analytics - Google Analytics(分析)数据保留政策 - 批量更改?