使用 Python 的 Base64 Incorrect padding 错误

Base64 Incorrect padding error using Python

我正在尝试将大约 200 个 Base64 数据的 Base64 解码为十六进制,但出现以下错误。它对其中的 60 个进行解码,然后停止。

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

来自 CSV 的一些原始 Base64 源代码

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

您的 CSV 文件中至少有一个字符串不是 Base64 字符串,是损坏(损坏)的 Base64 字符串,或者是缺少所需 = 填充的字符串。您的示例值 ABHPdSaxrhjAWA= 是短的 = 缺少另一个数据字符。

经过适当填充的 Base64 字符串的长度是 4 的倍数,因此您可以轻松地重新添加填充:

value = csvlines[0]
if len(value) % 4:
    # not a multiple of 4, add padding:
    value += '=' * (4 - len(value) % 4) 
csvlines[0] = value.decode("base64").encode("hex")

如果该值 仍然 无法解码,那么您的输入已损坏或无效的 Base64 开头。

对于示例错误 ABHPdSaxrhjAWA=,上面添加了一个 = 以使其可解码:

>>> value = 'ABHPdSaxrhjAWA='
>>> if len(value) % 4:
...     # not a multiple of 4, add padding:
...     value += '=' * (4 - len(value) % 4)
...
>>> value
'ABHPdSaxrhjAWA=='
>>> value.decode('base64')
'\x00\x11\xcfu&\xb1\xae\x18\xc0X'
>>> value.decode('base64').encode('hex')
'0011cf7526b1ae18c058'

我需要强调的是,您的数据可能只是损坏了。您的控制台输出包括一个有效的值和一个失败的值。有效的是一个字符长,这是唯一的区别:

ABHvPdSaxrhjAWA=
ABHPdSaxrhjAWA=

注意第4位的v;第二个示例中缺少此内容。这可能表明您的 CSV 数据发生了某些事情,导致该字符从第二个示例中删除。添加填充可以使第二个值再次解码,但结果将是错误。我们无法告诉您这两个选项中的哪一个是这里的原因。

简单演示:

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

精彩之处:

它忽略额外的填充。

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

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