Why is Ruby String.hash inconsistent across machines?

后端 未结 1 1390
眼角桃花
眼角桃花 2021-01-03 19:35

Came across this today on an app we are deploying across many servers. I was hashing some strings to store in a shared key/value store. The .hash method of String is returni

相关标签:
1条回答
  • 2021-01-03 20:08

    From a Ruby dev in the Ruby forum:

    It is intended. Ruby 1.9 explicitly use session local random seed to calculate a hash for strings (and some other objects).

    This is because the implementation of Object#hash is different between versions (like 1.9.1 and 1.9.2) and implementations (like JRuby, Rubinius, IronRuby, and so on). We want people to write portable code around Object#hash, so we did so.

    You should use Digest::SHA256 or some other digest routines when you want some hash value (message digest).

    And follow-up from another dev:

    Also, it helps to avoid some denial of service attacks, such as registering hundreds and thousands of users with usernames that have the same hash code.

    0 讨论(0)
提交回复
热议问题