I'm using TextDecoder to store a random sequence of bytes as a string. Then I want to transform that string back to an ArrayBuffer to give it as an input to WebCrypto API functions.
The problem is that I don't get back the same buffer generated previously. Here's some code to explain it better:
const textEncoder = new TextEncoder();
const textDecoder = new TextDecoder();
const buffer = crypto.getRandomValues(new Uint8Array(12));
// I expect this to contains the same exact bytes of "buffer", but they are different
const recomputedBuffer = textEncoder.encode(textDecoder.decode(buffer));
// Print to see the differences
console.log(buffer);
console.log(recomputedBuffer);
Is it a charset mismatch problem or something similiar?
(I found this question but seems a different problem)
EDIT (solved):
I made a mistake using the **text* encoders to encode binary data, they are supposed to work with text and indeed they work with text.
To encode binaries as string btoa
and atob
are more appropriate.