简体   繁体   中英

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. results[0][1] has the BLOB data extracted from database query.

         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. 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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