Python 3.3中的hash函数在会话之间返回不同的结果

2024-05-19 00:42:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我在python 3.3中实现了一个BloomFilter,每次会话都得到不同的结果。深入研究这种奇怪的行为让我找到了内部hash()函数-它在每个会话中为同一字符串返回不同的散列值。

示例:

>>> hash("235")
-310569535015251310

----打开一个新的python控制台---

>>> hash("235")
-1900164331622581997

为什么会这样? 为什么这个有用?


Tags: 函数字符串示例hash深入研究bloomfilter散列值
3条回答

hash()是一个Python内置函数,用于计算对象的哈希值,而不是字符串或num

您可以在本页中看到详细信息:https://docs.python.org/3.3/library/functions.html#hash

hash()值来自对象的hash方法。 医生说:

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.

这就是为什么在不同的控制台中对同一字符串有不同的散列值。

你实施的不是一个好办法。

当您想计算字符串哈希值时,只需使用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

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.

如果您需要一个稳定的散列实现,您可能需要查看^{} module;它实现了加密散列函数。这是pybloom project uses this approach

由于偏移量由前缀和后缀(分别是起始值和最终XORed值)组成,很遗憾,您不能只存储偏移量。另一方面,这也意味着攻击者也不能很容易地确定定时攻击的偏移量。

散列随机化是turned on by default in Python 3。这是一个安全功能:

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

在2.6.8的早期版本中,可以在命令行中使用-R或PYTHONHASHSEED环境选项打开它。

您可以通过将PYTHONHASHSEED设置为零来关闭它。

相关问题 更多 >

    热门问题