react-native-base64
react-native-base64 copied to clipboard
Output causes JSON.parse to choke
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.
Workaround:
payload = payload.split("").filter((v) => v !== '\x00').join("")
or
const payloadLength = rawPayload.indexOf('\x00') || rawPayload.length;
const payload = rawPayload.substring(0, payloadLength);
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
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 :)