为什么Ruby String.hash在机器间不一致? [英] Why is Ruby String.hash inconsistent across machines?
问题描述
示例:
server1 $ ruby - v
ruby 1.9.2p180(2011-02-18 revision 30909)[x86_64-linux]
server1 $ irb
irb(main):001:0> test.hash
=> 4146582576695053125
server2 $ ruby -v
ruby 1.9.2p180(2011-02-18 revision 30909)[x86_64-linux]
server2 $ irb
test.hash
=> 3479379392688537032
这些机器是具有相同规格和版本的EC2实例。
从 Ruby论坛:
它是有意的。 Ruby 1.9显式使用会话本地随机种子
计算字符串(和其他一些对象)的哈希。
这是因为Object#hash的实现是不同的
版本(如1.9.1和1.9.2)和实现(如JRuby,
Rubinius,IronRuby等)。我们希望人们在Object#hash上编写可移植代码
,所以我们这样做了。
当您使用Digest :: SHA256或其他一些摘要例程时
需要一些散列值(消息摘要)。
另一个开发者的后续工作:
此外,它还有助于避免一些拒绝服务攻击,例如
注册成千上万名用户名与
相同的用户哈希码。
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 returning different integers depending on the server. Any ideas why? Note that I am interested in why; not possible work arounds.
Example:
server1 $ ruby -v
ruby 1.9.2p180 (2011-02-18 revision 30909) [x86_64-linux]
server1 $ irb
irb(main):001:0> "test".hash
=> 4146582576695053125
server2 $ ruby -v
ruby 1.9.2p180 (2011-02-18 revision 30909) [x86_64-linux]
server2 $ irb
"test".hash
=> 3479379392688537032
These machines are EC2 instances with the same specs and build.
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.
这篇关于为什么Ruby String.hash在机器间不一致?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!