0

I base64 encoded bytes in python:

import base64
base64.b64encode(b"\xac\xd1%=\xdd\xe7\x18\x8f\xbcDrz\xa3\x8a\xac\x8dT\x88\t\xcf7\no\xfb\xa2\x97CI\x85\xe4:\xf2/\xd8a\xb5\xd2\x82\xa8\xce\x02Df\xd0?\x06re>\xb0\x94];~\xff\x00cV\xb5\xe3\xe8\xd1\xa0n").decode("utf-8")
# "rNElPd3nGI+8RHJ6o4qsjVSICc83Cm/7opdDSYXkOvIv2GG10oKozgJEZtA/BnJlPrCUXTt+/wBjVrXj6NGgbg=="

But when I am trying to decode it back to bytes in javascript:

atob("rNElPd3nGI+8RHJ6o4qsjVSICc83Cm/7opdDSYXkOvIv2GG10oKozgJEZtA/BnJlPrCUXTt+/wBjVrXj6NGgbg==")
// "¬Ñ%=Ýç\x18\x8F¼Drz£\x8A¬\x8DT\x88\tÏ7\noû¢\x97CI\x85ä:ò/ØaµÒ\x82¨Î\x02DfÐ?\x06re>°\x94];~ÿ\x00cVµãèÑ n"

I don't get the original bytes. How can I decode it with javascript and get the original bytes as a string?

Slomg
  • 45
  • 1
  • 8
  • 1
    I can't reproduce your output of `b64encode()`. – Olvin Roght Mar 26 '22 at 11:25
  • I accidently pasted the wrong thing, I fixed it – Slomg Mar 26 '22 at 11:28
  • 1
    Everything is okay with `atob()` output, it's equal to source you've encoded using python. – Olvin Roght Mar 26 '22 at 11:32
  • STRING "¬Ñ%=Ýç\x18\x8F¼Drz£\x8A¬\x8DT\x88\tÏ7\noû¢\x97CI\x85ä:ò/ØaµÒ\x82¨Î\x02DfÐ?\x06re>°\x94];~ÿ\x00cVµãèÑ" is not equal to STRING "\xac\xd1%=\xdd\xe7\x18\x8f\xbcDrz\xa3\x8a\xac\x8dT\x88\t\xcf7\no\xfb\xa2\x97CI\x85\xe4:\xf2/\xd8a\xb5\xd2\x82\xa8\xce\x02Df\xd0?\x06re>\xb0\x94];~\xff\x00cV\xb5\xe3\xe8\xd1\xa0n." It's the same bytes, but I don't want javascript to translate it to actual text, I need it to be the bytes as a string. – Slomg Mar 26 '22 at 11:35
  • You can't choose how built-in functions work, but you definitely can either make own implementation of base64 decode which will return array or convert return of `atob()` into array. – Olvin Roght Mar 26 '22 at 11:38
  • Does this answer your question? [Convert base64 string to ArrayBuffer](https://stackoverflow.com/questions/21797299/convert-base64-string-to-arraybuffer) – Olvin Roght Mar 26 '22 at 11:45

1 Answers1

3

atob will try decoding the bytes as text, instead of encoding the bytes into something like the b'...' in Python.

You asked: How can I decode it with javascript and get the original bytes as a string? But I believe, you should just use the bytes rather than convert it to a string.

So I tried my base-64 decoding tool. I think the byte array it returns meets your requirement (as ac does mean 172): [172, 209, 37, 61, 221, 231, 24, 143, 188, 68, 114, 122, 163, 138, 172, 141, 84, 136, 9, 207, 55, 10, 111, 251, 162, 151, 67, 73, 133, 228, 58, 242, 47, 216, 97, 181, 210, 130, 168, 206, 2, 68, 102, 208, 63, 6, 114, 101, 62, 176, 148, 93, 59, 126, 255, 0, 99, 86, 181, 227, 232, 209, 160, 110].

In the tool I used the package js-base64 to decode it. But it was developed years ago, I don't know whether there are better solutions now.

yueyinqiu
  • 369
  • 1
  • 7