如何在python3中解码base64
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38683439/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to decode base64 in python3
提问by Tspm1eca
I have a base64 encrypt code, and I can't decode in python3.5
我有一个base64加密代码,在python3.5中无法解码
import base64
code = "YWRtaW46MjAyY2I5NjJhYzU5MDc1Yjk2NGIwNzE1MmQyMzRiNzA" # Unencrypt is 202cb962ac59075b964b07152d234b70
base64.b64decode(code)
Result:
结果:
binascii.Error: Incorrect padding
But same website(base64decode) can decode it,
但是同一个网站(base64decode)可以解码它,
Please anybody can tell me why, and how to use python3.5 decode it?
请谁能告诉我为什么,以及如何使用python3.5解码它?
Thanks
谢谢
回答by Daniel
Base64 needs a string with length multiple of 4. If the string is short, it is padded with 1 to 3 =
.
Base64 需要长度为 4 倍的字符串。如果字符串很短,则用 1 到 3 填充=
。
import base64
code = "YWRtaW46MjAyY2I5NjJhYzU5MDc1Yjk2NGIwNzE1MmQyMzRiNzA="
base64.b64decode(code)
# b'admin:202cb962ac59075b964b07152d234b70'
回答by Saurav Gupta
回答by user2853437
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=
现在您可以看到正确的填充。 b'MjAyY2I5NjJhYzU5MDc1Yjk2NGIwNzE1MmQyMzRiNzA=