0

I encountered a weird issue when using Python's base64.b64decode function on strings with b'...' in them. This is a snippet of the code illustrating the issue.

>>> base64.b64encode(b"AAAA")
b'QUFBQQ=='
>>> s1 = "b'QUFBQQ=='"
>>> s2 = "QUFBQQ=="
>>> base64.b64decode(s1)
b'm\x05\x05\x05\x04'
>>> base64.b64decode(s2)
b'AAAA'

The result from base64.b64encode(b"AAAA") is copied and saved as a string s1. I also copy just the bytes (i.e. the characters inside b'...') and save it as a string s2. When calling base64.b64decode with s1 I get nonsense, while calling it with s2 gives the expected result. I suspect the ' symbol is causing some issues since it's not a valid base 64 symbol.

What is happening in base64.b64decode(s1) that gives the weird result?

1
  • 3
    b'QUFBQQ==' is not the same as "b'QUFBQQ=='". Commented Apr 25, 2020 at 13:45

2 Answers 2

2

When you set

s1 = "b'QUFBQQ=='"

Then the string includes the b and both single tics. Just get rid of the double quotes:

s1 = b'QUFBQQ=='

The ‘b’ outside the single quote means to interpret it as a byte literal.

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

Comments

-2

I hit the same issue. Found below solution. You need to again decode the base64 decoded string to ASCII format. It can be done in following way.

>>> s1 = base64.b64encode(b"AAAA")
>>> base64.b64decode(s1)
b'AAAA'
>>> base64.b64decode(s1).decode('ascii')
'AAAA'

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.