V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
nullboy
V2EX  ›  Python

Python 中同一个字符串的 hash 值在不同机器上为啥不一样?

  •  
  •   nullboy · 2021-07-05 16:24:16 +08:00 · 2395 次点击
    这是一个创建于 997 天前的主题,其中的信息可能已经有所发展或是发生改变。
    8 条回复    2021-07-05 19:06:18 +08:00
    lithiumii
        1
    lithiumii  
       2021-07-05 16:25:59 +08:00
    代码贴一贴,运行环境贴一贴,你这样问,我只能说为啥我这儿不同机器上值一样
    Rush9999
        3
    Rush9999  
       2021-07-05 16:29:14 +08:00   ❤️ 2
    用 hashlib,你用自带的 hash 肯定不一样
    md5 = hashlib.md5()
    md5.update('how to use md5 in python hashlib?'.encode('utf-8'))
    print(md5.hexdigest())
    Alias4ck
        4
    Alias4ck  
       2021-07-05 16:30:28 +08:00   ❤️ 1
    准确来说在同一台机器上的不同 session 下的同一个字符 hash 值也不一样 详情可看上面 stackoverflow 解释
    knightdf
        5
    knightdf  
       2021-07-05 16:31:10 +08:00
    本来就不保证相同,你同一个机器开 2 个 python 运行出来的 hash 值都不同,build-in 的 hash 加了随机数,只是用来快速比较 dict 的 key 的
    Trim21
        6
    Trim21  
       2021-07-05 16:35:32 +08:00   ❤️ 1
    内置的 hash 函数并不保证不同机器中相同的值得到相同 hash 结果,要夸机器比较哈希值是否相等应该用 hashlib 里面提供的算法。
    fengjianxinghun
        7
    fengjianxinghun  
       2021-07-05 18:24:39 +08:00
    主要是防止 hash 碰撞 ddos 攻击
    JeffGe
        8
    JeffGe  
       2021-07-05 19:06:18 +08:00 via Android   ❤️ 1
    这事 Python 官方文档就有说明
    https://docs.python.org/zh-cn/3/reference/datamodel.html#object.__hash__

    > 注解 在默认情况下,str 和 bytes 对象的 __hash__() 值会使用一个不可预知的随机值“加盐”。 虽然它们在一个单独 Python 进程中会保持不变,但它们的值在重复运行的 Python 间是不可预测的。
    这种做法是为了防止以下形式的拒绝服务攻击:通过仔细选择输入来利用字典插入操作在最坏情况下的执行效率即 O(n^2) 复杂度。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3252 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 32ms · UTC 11:44 · PVG 19:44 · LAX 04:44 · JFK 07:44
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.