the*_*glu 5 javascript local-storage initialization-vector typed-arrays typescript
我有 16 字节数据存储在 Uint8Array 中。我需要将这些数据存储在浏览器中,并且必须在其他类中获取它。
所以我的代码如下所示:
const ivBytes = window.crypto.getRandomValues(new Uint8Array(16));
localStorage.setItem("iv",JSON.stringify(ivBytes))
console.log("content of ivBytes:" + ivBytes)
Run Code Online (Sandbox Code Playgroud)
在其他课程中,我尝试获取这样的数据,但它不起作用
let array = JSON.parse(localStorage.getItem("iv"))
console.log("the iv value we get is: " + ivBytes)
Run Code Online (Sandbox Code Playgroud)
但是当我尝试获取数组的内容时,它并没有准确地给出 ivBytes 的内容。输出如下:

如何在浏览器中存储 Uint8array 并使用 localStorage 在其他类中以相同的方式获取它?提前致谢。
它太硬...
Uint8Array 只是 ArrayBuffer 的视图,ArrayBuffer 是内存中保存的二进制数据。
所以我通常的建议是不要在 localStorage 中存储二进制数据,因为 localStorage 只能存储字符串,并且还有其他存储 API 可以处理二进制数据,例如 IndexedDB。
但是,这里您想要存储的似乎只是从加密 API 获得的随机生成的数字,并且由于我们正在讨论的是一个非常小的 ArrayBuffer,那么...
要对 TypedArray 进行字符串化,以便将其存储在 localStorage 中,您需要一一提取所有值并将它们移动到数组中,或者,如果可用,只需调用 Array.from(yourTypedArray) ,然后对该数组进行字符串化:
const typedArray = new Uint8Array(16);
crypto.getRandomValues(typedArray);
const arr = Array.from // if available
? Array.from(typedArray) // use Array#from
: [].map.call(typedArray, (v => v)); // otherwise map()
// now stringify
const str = JSON.stringify(arr);
console.log(str);
// localStorage.setItem('foo', str);
// and to retrieve it...
// const str = localStorage.getItem('foo');
const retrievedArr = JSON.parse(str);
const retrievedTypedArray = new Uint8Array(retrievedArr);
console.log(retrievedTypedArray.byteLength);Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7052 次 |
| 最近记录: |