'Base64 Incorrect padding error using Python

I am trying to decode Base64 into Hex for about 200 Base64 data and I am getting this following error. It does decoding for 60 of them then stops.

ABHvPdSaxrhjAWA=
0011ef3dd49ac6b8630160
ABHPdSaxrhjAWA=
Traceback (most recent call last):
  File "tt.py", line 36, in <module>
    csvlines[0] = csvlines[0].decode("base64").encode("hex")
  File "C:\Python27\lib\encodings\base64_codec.py", line 43, in base64_decode
    output = base64.decodestring(input)
  File "C:\Python27\lib\base64.py", line 325, in decodestring
    return binascii.a2b_base64(s)
binascii.Error: Incorrect padding

Some original Base64 source from CSV

ABHPdSaxrhjAWA=
ABDPdSaxrhjAWA=
ABDPdSaxrhjAWA=
ABDPdSaxrhjAWA=
ABDPdSaxrhjAWA=
ABDPdSaxrhjAWA=
ABDPdS4xriiAVQ=
ABDPdSqxrizAU4=
ABDPdSrxrjPAUo=


Solution 1:[1]

Simple demonstration:

In [1]: import base64

In [2]: data = 'demonstration yo'

In [3]: code = base64.b64encode(data)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Input In [3], in <cell line: 1>()
----> 1 code = base64.b64encode(data)

File ~/anaconda3/envs/dedup/lib/python3.8/base64.py:58, in b64encode(s, altchars)
     51 def b64encode(s, altchars=None):
     52     """Encode the bytes-like object s using Base64 and return a bytes object.
     53
     54     Optional altchars should be a byte string of length 2 which specifies an
     55     alternative alphabet for the '+' and '/' characters.  This allows an
     56     application to e.g. generate url or filesystem safe Base64 strings.
     57     """
---> 58     encoded = binascii.b2a_base64(s, newline=False)
     59     if altchars is not None:
     60         assert len(altchars) == 2, repr(altchars)

TypeError: a bytes-like object is required, not 'str'

In [4]: data = 'demonstration yo'.encode("ascii")

In [5]: code = base64.b64encode(data)

In [6]: code
Out[6]: b'ZGVtb25zdHJhdGlvbiB5bw=='

In [7]: base64.b64decode(code) == data
Out[7]: True

In [8]: base64.b64decode(code[0:18]) == data
---------------------------------------------------------------------------
Error                                     Traceback (most recent call last)
Input In [8], in <cell line: 1>()
----> 1 base64.b64decode(code[0:18]) == data

File ~/anaconda3/envs/dedup/lib/python3.8/base64.py:87, in b64decode(s, altchars, validate)
     85 if validate and not re.fullmatch(b'[A-Za-z0-9+/]*={0,2}', s):
     86     raise binascii.Error('Non-base64 digit found')
---> 87 return binascii.a2b_base64(s)

Error: Incorrect padding

What's cool:

It ignores extra padding.

In [13]: code
Out[13]: b'ZGVtb25zdHJhdGlvbiB5bw=='

In [14]: base64.b64decode(code + "=========".encode("ascii")) == data
Out[14]: True

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 aerin