简体   繁体   English

解码base64编码时出现错误的填充错误

[英]Incorrect Padding error while decoding base64 encoding

I have tried to decode a PDF I stored as BLOB and save it into a file with .pdf extension. 我试图解码作为BLOB存储的PDF,并将其保存到扩展名为.pdf的文件中。 results[0][1] has the BLOB data extracted from database query. results [0] [1]具有从数据库查询中提取的BLOB数据。

         blob_val=results[0][1]
         if len(blob_val) % 4 != 0:
            while len(blob_val) % 4 != 0:
              blob_val = blob_val + b"="
            decod_text = base64.b64decode(blob_val)
         else:
            decod_text = base64.b64decode(blob_val)

Eventhough i have added = at the end to correct padding errors, it is still showing incorrect padding error. 即使我在末尾添加了=来纠正填充错误,它仍然显示不正确的填充错误。 why does it still shows this error even when we corrected it by "="? 为什么即使我们通过“ =”进行了更正,它仍然显示此错误?

Each base64 char is encoding six bits. 每个base64字符都编码六个位。 For this to work, the total number of bytes should be divisible by three, not four. 为此,总字节数应被三整除,而不是四整。

This should work (and be a bit simplified): 这应该可以工作(并简化一下):

    blob_val = results[0][1]

    # If the length is divisible by 3, the 'while' will never
    # be entered, so no point in doing the additional 'if' above.
    while len(blob_val) % 3 != 0:
        blob_val += b"="

    decod_text = base64.b64decode(blob_val)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM