Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to decode base64 in python3

Tags:

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

like image 610
Tspm1eca Avatar asked Jul 31 '16 11:07

Tspm1eca


People also ask

How do I decode a base64 string in Python?

To decode an image using Python, we simply use the base64. b64decode(s) function. Python mentions the following regarding this function: Decode the Base64 encoded bytes-like object or ASCII string s and return the decoded bytes.

How do I encode base64 in Python 3?

Encoding Strings with Python Python 3 provides a base64 module that allows us to easily encode and decode information. We first convert the string into a bytes-like object. Once converted, we can use the base64 module to encode it.

How do I decode a base64 file?

To decode with base64 you need to use the --decode flag. With encoded string, you can pipe an echo command into base64 as you did to encode it. Using the example encoding shown above, let's decode it back into its original form. Provided your encoding was not corrupted the output should be your original string.

What is base64 b64decode in Python?

b64decode() in Python. The base64. b4() function in Python decodes strings or byte-like objects encoded in base64 and returns the decoded bytes.


2 Answers

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' 
like image 86
Daniel Avatar answered Oct 25 '22 05:10

Daniel


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' 
like image 29
Saurav Gupta Avatar answered Oct 25 '22 04:10

Saurav Gupta