35

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

Tspm1eca
  • 393
  • 1
  • 3
  • 7

4 Answers4

60

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'
Daniel
  • 42,087
  • 4
  • 55
  • 81
11

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'
Community
  • 1
  • 1
Saurav Gupta
  • 535
  • 3
  • 11
  • 1
    The answer I gave adds the appropriate padding based on length of the encoded string. Please accept the answer if you found it helpful. – Saurav Gupta Jul 31 '16 at 12:58
1

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=

user2853437
  • 750
  • 8
  • 27
0

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'

janbrohl
  • 2,626
  • 1
  • 17
  • 15