为什么Ruby String.hash在机器间不一致? [英] Why is Ruby String.hash inconsistent across machines?

查看:105
本文介绍了为什么Ruby String.hash在机器间不一致?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

今天在一个应用程序中,我们在许多服务器上部署了这个应用程序。我正在散列一些字符串以存储在共享密钥/值存储中。 String的.hash方法根据服务器返回不同的整数。任何想法为什么?请注意,我对为什么;



示例:

  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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆