I've 16 bytes data I'm storing in Uint8Array. I need to store this data in the browser and must get it in some other class.
so my code looks like this:
const ivBytes = window.crypto.getRandomValues(new Uint8Array(16));
localStorage.setItem("iv",JSON.stringify(ivBytes))
console.log("content of ivBytes:" + ivBytes)
and in other class I try to get data like this but it doesnt work
let array = JSON.parse(localStorage.getItem("iv"))
console.log("the iv value we get is: " + ivBytes)
but when I try to get the content of array, it doesnt give me exactly the content of the ivBytes. the output is as follows:
How can I store Uint8array in browser and get it the same way in other class using localStorage? thanks in advance.
It's tough...
An Uint8Array is just a view over an ArrayBuffer which is binary data held in memory.
So my normal advice would be don't store binary data in localStorage, because localStorage can only store strings and that there are other storage APIs that can handle binary data, such as IndexedDB.
But, here what you want to store seems to only be the randomly generated numbers you got from the crypto API, and since it's a really small ArrayBuffer we're talking about, then...
To stringify your TypedArray so that it can be stored in localStorage, you'll need to extract all the values one by one and move them to an Array, or, if available, simply call Array.from(yourTypedArray) and then stringify this Array:
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);