By default, the hash() values of str, bytes and datetime objects are “salted” with an unpredictable random value. Although they remain constant within an individual Python process, they are not predictable between repeated invocations of Python.
Note: By default, the __hash__() values of str, bytes and datetime objects are “salted” with an unpredictable random value. Although they remain constant within an individual Python process, they are not predictable between repeated invocations of Python.
This is intended to provide protection against a denial-of-service caused by carefully-chosen inputs that exploit the worst case performance of a dict insertion, O(n^2) complexity. See http://www.ocert.org/advisories/ocert-2011-003.html for details.
Changing hash values affects the iteration order of dicts, sets and other mappings. Python has never made guarantees about this ordering (and it typically varies between 32-bit and 64-bit builds).
See also PYTHONHASHSEED.
Hash randomization is intended to provide protection against a denial-of-service caused by carefully-chosen inputs that exploit the worst case performance of a dict construction
hash()是一个Python内置函数,用于计算对象的哈希值,而不是字符串或num
您可以在本页中看到详细信息:https://docs.python.org/3.3/library/functions.html#hash。
hash()值来自对象的hash方法。 医生说:
这就是为什么在不同的控制台中对同一字符串有不同的散列值。
你实施的不是一个好办法。
当您想计算字符串哈希值时,只需使用hashlib
hash()的目的是获取对象哈希值,而不是stirng。
Python使用一个随机散列种子,通过向您发送设计用于冲突的密钥来防止攻击者攻击您的应用程序。请参阅original vulnerability disclosure。通过使用随机种子(在启动时设置一次)抵消散列,攻击者无法再预测将碰撞哪些密钥。
可以通过设置^{} environment variable 设置固定种子或禁用该功能;默认值为
random
,但可以将其设置为固定正整数值,同时0
完全禁用该功能。Python版本2.7和3.2在默认情况下禁用了该特性(使用
-R
开关或设置PYTHONHASHSEED=random
来启用它);在Python 3.3及更高版本中默认启用该特性。如果您依赖于Python字典或集合中键的顺序,那么不要这样做。Python使用哈希表来实现这些类型及其顺序depends on the insertion and deletion history以及随机哈希种子。
另请参见^{} special method documentation :
如果您需要一个稳定的散列实现,您可能需要查看^{} module ;它实现了加密散列函数。这是pybloom project uses this approach。
由于偏移量由前缀和后缀(分别是起始值和最终XORed值)组成,很遗憾,您不能只存储偏移量。另一方面,这也意味着攻击者也不能很容易地确定定时攻击的偏移量。
散列随机化是turned on by default in Python 3。这是一个安全功能:
在2.6.8的早期版本中,可以在命令行中使用-R或PYTHONHASHSEED环境选项打开它。
您可以通过将
PYTHONHASHSEED
设置为零来关闭它。相关问题 更多 >
编程相关推荐