当我今天浏览Python模块源代码时,我发现它包含全局变量_secret_backdoor_key。然后检查此变量以中断对象初始化。
代码如下所示
# A unique object passed by HMAC.copy() to the HMAC constructor, in order
# that the latter return very quickly. HMAC("") in contrast is quite
# expensive.
_secret_backdoor_key = []
class HMAC:
"""RFC 2104 HMAC class. Also complies with RFC 4231.
This supports the API for Cryptographic Hash Functions (PEP 247).
"""
blocksize = 64 # 512-bit HMAC; can be changed in subclasses.
def __init__(self, key, msg = None, digestmod = None):
"""Create a new HMAC object.
key: key for the keyed hash object.
msg: Initial input for the hash, if provided.
digestmod: A module supporting PEP 247. *OR*
A hashlib constructor returning a new hash object.
Defaults to hashlib.md5.
"""
if key is _secret_backdoor_key: # cheap
return有人知道这个变量的原因吗?注释说,HMAC的返回速度比空字符串("")更快。但是为什么用户要将空密钥传递给HMAC函数呢?变量命名只是HMAC开发人员的一个笑话,还是真的是某种后门?
发布于 2016-07-12 09:11:57
要创建HMAC实例的副本,首先需要创建一个空实例。
_secret_backdoor_key对象被用作早期退出__init__的哨兵,而不是运行于__init__功能的其余部分。然后,copy方法直接设置实例属性:
def copy(self):
"""Return a separate copy of this hashing object.
An update to this copy won't affect the original object.
"""
other = self.__class__(_secret_backdoor_key)
other.digest_cons = self.digest_cons
other.digest_size = self.digest_size
other.inner = self.inner.copy()
other.outer = self.outer.copy()
return other您可以使用self.__class__('') (一个空字符串)获得同样的效果,但是HMAC.__init__做了许多不必要的工作,因为创建的实例上的属性无论如何都要被替换。注意,使用HMAC('')是创建实例的有效方法,在这种情况下,您不希望一个实例没有任何状态。通过传递哨兵,HMAC.copy()可以避免所有额外的工作。
您可以使用一个不同的“标志”值,比如False,但是由于您自己的代码中有一个bug,所以传递它太容易了。你会想得到这样的错误的通知,而不是。通过使用“秘密”内部哨兵对象,您可以避免这样的意外情况。
使用[]作为一个哨兵唯一的对象是一种古老的做法。现在你会用object()代替。其思想是,哨兵是一个唯一的、单一的对象,您可以使用is对其进行身份测试。您不能在其他地方重新创建该对象,只有在传递对完全相同的单个对象的引用时,is测试才能工作。
https://stackoverflow.com/questions/38324441
复制相似问题