Python base64 decode incorrect padding error resolution

  • 2020-04-02 14:29:54
  • OfStack

Python base64. Decodestring method to do base64 decoding error:


Traceback (most recent call last):
  File "/export/www/outofmemory.cn/controllers/user.py", line 136, in decryptPassword
    encryptPwd = base64.b64decode(encryptPwd)
  File "/usr/lib/python2.7/base64.py", line 76, in b64decode
    raise TypeError(msg)
TypeError: Incorrect padding

This is also a pit of python, the solution to this problem is very simple, base64 decoded string complement equals, the following code:

        def decode_base64(data):
            """Decode base64, padding being optional.             :param data: Base64 data as an ASCII byte string
            :returns: The decoded byte string.             """
            missing_padding = 4 - len(data) % 4
            if missing_padding:
                data += b'='* missing_padding
            return base64.decodestring(data)


Related articles: