3

I am puzzled at this base64 decoding issue, and it seems that python and node.js does this differently. Node does this correctly I believe. Could anyone help point out why python does not work here?

Thank you.

Node

> console.log(Buffer.from('Im3Osc6_z4HPgc-J==', 'base64').toString());
"mαορρω

Python

>>> from base64 import decodestring
>>> print decodestring('Im3Osc6_z4HPgc-J==')
"mαγ?s?p
8
  • 2
    Base64 has nothing to do with this; the bytes are probably decided correctly, the problem is what character encoding has been used to prepare the bytes buffer in first place (and what python and node are using). Commented Apr 17, 2018 at 18:33
  • OK, so how to change python to get the same results then? Commented Apr 17, 2018 at 18:34
  • 1
    By decoding the string using the same codec as that which was using to encode it. How did you create that string? Commented Apr 17, 2018 at 18:35
  • @Robᵩ I am given this string as an input, no choice to change it. Commented Apr 17, 2018 at 18:39
  • 1
    OK. How did the person who gave it to you construct it? Commented Apr 17, 2018 at 18:41

1 Answer 1

3

What you provided is actually not a standard base64, but a URL-safe base64

which substitutes - instead of + and _ instead of / in the standard Base64 alphabet"

To decode it in Python you need to use base64.urlsafe_b64decode.

>>> import base64
>>> base64.urlsafe_b64decode('Im3Osc6_z4HPgc-J==')
'"m\xce\xb1\xce\xbf\xcf\x81\xcf\x81\xcf\x89'

Then, the byte string that is encoded in that base64 is in UTF-8; to get a Unicode string, you have to decode it:

>>> print base64.urlsafe_b64decode('Im3Osc6_z4HPgc-J==').decode('utf-8')
"mαορρω

With base64.decodestring you got weird results because it just drops any character that is not part of the standard base64 alphabet, so it decoded incorrect bytes.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.