1

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.

raxell
  • 677
  • 6
  • 19
  • What do you mean under ***equal***? In case of objects, `==` and `===` use reference equality, which (quite obviously) won't work in your case. For compare by value, search for '*Object value equality*' or something similar. – FZs Jun 09 '19 at 09:54
  • With equal I mean they should contain the same bytes, but after the trasformations "recomputedBuffer" has different bytes, try to execute the code and print the buffers to check it – raxell Jun 09 '19 at 10:05
  • Ok, then I don't know... – FZs Jun 09 '19 at 10:06
  • 1
    Don't you think that perhaps the fact they're called *Text*Encoder and *Text*Decoder hint at the underlying implementation (and reasonable expectations) I wouldn't expect someone sending a binary file while in text-mode to receive what they sent either. :wink: – enhzflep Jun 09 '19 at 10:35
  • Oh you are right, my mistake, thanks! – raxell Jun 09 '19 at 11:11
  • Possible duplicate of [Converting ArrayBuffer to String then back to ArrayBuffer using TextDecoder/TextEncoder returning a different result](https://stackoverflow.com/questions/50198017/converting-arraybuffer-to-string-then-back-to-arraybuffer-using-textdecoder-text) – zag2art Jun 28 '19 at 16:11

0 Answers0