【发布时间】:2019-03-05 14:02:13
【问题描述】:
由于某种原因,我不能让下面的 sn-p 出错,尽管它应该出错。
使用不可打印字符调用 python2 的 base64 解码函数decodestring,我希望会引发异常,但是:
In [1]: import base64
In [2]: base64.decodestring("\x01\x01\x01")
Out[2]: ''
为了比较,使用 string 类的方法会产生相同的结果:
In [7]: "\x01\x01\x01".decode("base64")
Out[7]: ''
但是,对十六进制执行等效操作确实会提供预期的行为(请注意,添加了一个附加字符以对齐 2 的倍数,正如十六进制解码器所预期的那样):
In [9]: "\x01\x01\x01\x01".decode("hex")
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-9-1e73b7069a1d> in <module>()
----> 1 "\x01\x01\x01\x01".decode("hex")
/usr/lib/python2.7/encodings/hex_codec.pyc in hex_decode(input, errors)
40 """
41 assert errors == 'strict'
---> 42 output = binascii.a2b_hex(input)
43 return (output, len(input))
44
TypeError: Non-hexadecimal digit found
其他几次尝试证明遇到的行为是 base64 解码器,具体来说,忽略任何无效字符而不是引发错误。尽管解码器被记录为仅支持默认的严格错误处理模式,但仍会遇到此行为:
In [11]: "\x01\x01\x01".decode("base64", errors="ignore")
---------------------------------------------------------------------------
AssertionError Traceback (most recent call last)
<ipython-input-11-e0b65726a302> in <module>()
----> 1 "\x01\x01\x01".decode("base64", errors="ignore")
/usr/lib/python2.7/encodings/base64_codec.pyc in base64_decode(input, errors)
39
40 """
---> 41 assert errors == 'strict'
42 output = base64.decodestring(input)
43 return (output, len(input))
AssertionError:
无论用于执行与 python2.7 捆绑的内置 base64 编解码器的方法如何,都会遇到这种行为。
此外,任何有效字符都将被正确处理,产生如下奇怪的结果:
In [6]: base64.decodestring("\x01\x01\x01\x01\x01AA==")
Out[6]: '\x00'
In [7]: base64.decodestring("\x01A\x01A\x01=\x01=\x01A")
Out[7]: '\x00'
In [8]: base64.decodestring("\x01Not\x01A\x01Base64\x01String\x01")
Out[8]: '6\x8b@\x05\xab\x1e\xeb\x84\xad\xae)\xe0'
我的问题有两个:
- 我对此行为的分析是否正确?
- 为什么要实现这种行为而不是与其他编解码器和
errors="strict"API 保持一致?
【问题讨论】:
标签: python python-2.7 base64