How to decode base64 in python3

Question:

I have a base64 encrypt code, and I can’t decode in python3.5

import base64
code = "YWRtaW46MjAyY2I5NjJhYzU5MDc1Yjk2NGIwNzE1MmQyMzRiNzA" # Unencrypt is 202cb962ac59075b964b07152d234b70
base64.b64decode(code)

Result:

binascii.Error: Incorrect padding

But same website(base64decode) can decode it,

Please anybody can tell me why, and how to use python3.5 decode it?

Thanks

Asked By: Tspm1eca

||

Answers:

According to this answer, you can just add the required padding.

code = "YWRtaW46MjAyY2I5NjJhYzU5MDc1Yjk2NGIwNzE1MmQyMzRiNzA"
b64_string = code
b64_string += "=" * ((4 - len(b64_string) % 4) % 4)
base64.b64decode(b64_string) #'admin:202cb962ac59075b964b07152d234b70'
Answered By: Saurav Gupta

It actually seems to just be that code is incorrectly padded (code is incomplete)

import base64
code = "YWRtaW46MjAyY2I5NjJhYzU5MDc1Yjk2NGIwNzE1MmQyMzRiNzA"
base64.b64decode(code+"=")

returns b'admin:202cb962ac59075b964b07152d234b70'

Answered By: janbrohl

Base64 needs a string with length multiple of 4. If the string is short, it is padded with 1 to 3 =.

import base64
code = "YWRtaW46MjAyY2I5NjJhYzU5MDc1Yjk2NGIwNzE1MmQyMzRiNzA="
base64.b64decode(code)
# b'admin:202cb962ac59075b964b07152d234b70'
Answered By: Daniel

I tried the other way around. If you know what the unencrypted value is:

>>> import base64
>>> unencoded = b'202cb962ac59075b964b07152d234b70'
>>> encoded = base64.b64encode(unencoded)
>>> print(encoded)
b'MjAyY2I5NjJhYzU5MDc1Yjk2NGIwNzE1MmQyMzRiNzA='
>>> decoded = base64.b64decode(encoded)
>>> print(decoded)
b'202cb962ac59075b964b07152d234b70'

Now you see the correct padding. b'MjAyY2I5NjJhYzU5MDc1Yjk2NGIwNzE1MmQyMzRiNzA=

Answered By: user2853437
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.