使用base64 lib

时间:2018-12-23 19:54:33

标签: python base32

在尝试使用base64 lib解码base32字符串时,我需要一种忽略“不正确填充”异常的方法。

我看过这篇文章Python: Ignore 'Incorrect padding' error when base64 decoding,该文章解决了base64(b64decode)解码的问题。我试图做同样的事情(添加可接受的最大填充数,如果我不是msitaken的话,base32则为6)

b32decode(str(decoding) + "======", True, None)

但是无论如何都会引发异常。

预期结果是即使没有正确的填充也要解码base32字符串:

decoding = JBSWY3DPEBZXIYLDNMQG65TFOJTGY33XEE== #this string should have 6 '=' as padding
print(b32decode(str(decoding) + "======", True, None))
>> Hello stack overflow! 

2 个答案:

答案 0 :(得分:1)

据我测试。这行代码将使其起作用。

pad_length = math.ceil(len(b32_string) / 8) * 8 - len(b32_string)
bytes_data = base64.b32decode(b32_string.encode('ascii') + b'=' * pad_length)

答案 1 :(得分:0)

您不应添加整个6个'='字符,您需要填充后缀以具有6个相等的字符:

> base64.b32decode("JBSWY3DPEBZXIYLDNMQG65TFOJTGY33XEE======")
'Hello stack overflow!'

要正确填充邮件,您应该遵循https://tools.ietf.org/html/rfc4648#section-6