react-native-base64 icon indicating copy to clipboard operation
react-native-base64 copied to clipboard

Output causes JSON.parse to choke

Open hermanbanken opened this issue 3 years ago • 3 comments

This library outputs nil bytes (0) at the end which cause JSON.parse to choke.

Example:

import base64 from 'react-native-base64';

test("JWT parsing did not work: proving that I am not crazy", () => {
  const [payload] = ["eyJpYSI6MTY0Mzk5NjQ3NSwiZXhwIjoxNjQ3NjIxNjc0fQ"]
    .map(base64.decode);
  expect(() => JSON.parse(payload as string)).toThrow();

  const bufferAgain = Buffer.from(payload as string, "utf8");
  // Somehow the last 2 bytes are NIL bytes, which do not show up visually but cause JSON.parse to fail
  expect(bufferAgain.slice(-2)).toEqual(Buffer.from([0, 0]));
});

Looking at the output of Buffer.from("eyJpYSI6MTY0Mzk5NjQ3NSwiZXhwIjoxNjQ3NjIxNjc0fQ", "base64") you can see that it does not end in nil bytes:

> Buffer.from("eyJpYSI6MTY0Mzk5NjQ3NSwiZXhwIjoxNjQ3NjIxNjc0fQ", "base64").slice(-10)
<Buffer 36 34 37 36 32 31 36 37 34 7d>

I think the library should strip the trailing 0's.

hermanbanken avatar Feb 04 '22 18:02 hermanbanken

Workaround:

payload = payload.split("").filter((v) => v !== '\x00').join("")

or

const payloadLength = rawPayload.indexOf('\x00') || rawPayload.length;
const payload = rawPayload.substring(0, payloadLength);

hermanbanken avatar Feb 04 '22 18:02 hermanbanken

I know it's laaaaaate response, sorry for that. I have a Q: is JSON.parse is part of the RN VS engine or is it exists only when debugging in dev tools? Thanks, Eran

eranbo avatar Aug 20 '22 18:08 eranbo

Sorry to resurrect this old issue, but I just ran into the same problem in my project. The null-byte filter solution proposed by @hermanbanken was introduced in PR #15 @eranbo if you're okay with that approach, it would be awesome if we could publish that fix :)

henriquecfreitas avatar Oct 20 '23 20:10 henriquecfreitas