37

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

4 Answers 4

65

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' 
Sign up to request clarification or add additional context in comments.

2 Comments

the output object is a byte, how do I get it to be string?
@ScipioAfricanus: you have to decode it, with the correct encoding.
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' 

1 Comment

The answer I gave adds the appropriate padding based on length of the encoded string. Please accept the answer if you found it helpful.
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=

Comments

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'

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.