python_base64_binascii.Error: Incorrect padding解决

问题描述:

在使用b64decode对加密后的文件进行解密的时候报错,如下:

Traceback (most recent call last):
  File "E:/project/allow/zt/xx01_xyz.py", line 13, in 
    result = b64decode("aHR0cCUzQSUyRiUyRnZpZGVvLnlqZjEzOC5jb20lM0E4MDkxJTJGMjAxODEyMzElMkYyd3prQjRGbSUyRmluZGV4Lm0zdTg")
  File "E:\Anaconda3\lib\base64.py", line 87, in b64decode
    return binascii.a2b_base64(s)
binascii.Error: Incorrect padding

Incorrect padding:填充不正确

以下为base64.py文件中方法定义

def b64decode(s, altchars=None, validate=False):
    """Decode the Base64 encoded bytes-like object or ASCII string s.

    Optional altchars must be a bytes-like object or ASCII string of length 2
    which specifies the alternative alphabet used instead of the '+' and '/'
    characters.

    The result is returned as a bytes object.  A binascii.Error is raised if
    s is incorrectly padded.

    If validate is False (the default), characters that are neither in the
    normal base-64 alphabet nor the alternative alphabet are discarded prior
    to the padding check.  If validate is True, these non-alphabet characters
    in the input result in a binascii.Error.
    """
    s = _bytes_from_decode_data(s)
    if altchars is not None:
        altchars = _bytes_from_decode_data(altchars)
        assert len(altchars) == 2, repr(altchars)
        s = s.translate(bytes.maketrans(altchars, b'+/'))
    if validate and not re.match(b'^[A-Za-z0-9+/]*={0,2}$', s):
        raise binascii.Error('Non-base64 digit found')
    return binascii.a2b_base64(s)

原文:    

Optional altchars must be a bytes-like object or ASCII string of length 2 which specifies the alternative alphabet used instead of the '+' and '/' characters.

翻译:

可选altchars必须是长度为2的对象或ASCII字符串之类的字节它指定使用的替代字母表,而不是“+”和“/”字符。

原因分析:

传入的参数的长度不是2的对象,在参数最后加上等于号"="(一个或者两个)

修改后代码:

result = b64decode("aHR0cCUzQSUyRiUyRnZpZGVvLnlqZjEzOC5jb20lM0E4MDkxJTJGMjAxODEyMzElMkYyd3prQjRGbSUyRmluZGV4Lm0zdTg=")
print(type(result))
print(result)

运行成功!!!

执行结果:


b'http%3A%2F%2Fvideo.yjf138.com%3A8091%2F20181231%2F2wzkB4Fm%2Findex.m3u8'

你可能感兴趣的:(python,python问题及解决方案,爬虫问题,错误整理,base64)