在Ruby中创建数字,字符串,数组或哈希值的md5哈希值 [英] Creating an md5 hash of a number, string, array, or hash in Ruby
问题描述
我需要在Ruby中为变量创建签名字符串,其中变量可以是数字,字符串,哈希或数组.哈希值和数组元素也可以是这些类型中的任何一种.
I need to create a signature string for a variable in Ruby, where the variable can be a number, a string, a hash, or an array. The hash values and array elements can also be any of these types.
该字符串将用于比较数据库中的值(在这种情况下为Mongo).
This string will be used to compare the values in a database (Mongo, in this case).
我的第一个想法是创建一个JSON编码值的MD5哈希,就像这样:(body是上面提到的变量)
My first thought was to create an MD5 hash of a JSON encoded value, like so: (body is the variable referred to above)
def createsig(body)
Digest::MD5.hexdigest(JSON.generate(body))
end
这几乎可行,但是JSON.generate不会每次都以相同的顺序对哈希键进行编码,因此createsig({:a=>'a',:b=>'b'})
并不总是等于createsig({:b=>'b',:a=>'a'})
.
This nearly works, but JSON.generate does not encode the keys of a hash in the same order each time, so createsig({:a=>'a',:b=>'b'})
does not always equal createsig({:b=>'b',:a=>'a'})
.
创建满足此需求的签名字符串的最佳方法是什么?
What is the best way to create a signature string to fit this need?
注意:对于我们中间的细节,我知道您不能JSON.generate()
数字或字符串.在这种情况下,我将直接致电MD5.hexdigest()
.
Note: For the detail oriented among us, I know that you can't JSON.generate()
a number or a string. In these cases, I would just call MD5.hexdigest()
directly.
推荐答案
我很快对以下内容进行了编码,并且没有时间在工作中真正对其进行测试,但是它应该可以完成工作.如果您有任何问题,请告诉我,我会看看.
I coding up the following pretty quickly and don't have time to really test it here at work, but it ought to do the job. Let me know if you find any issues with it and I'll take a look.
这应该适当地弄平并对数组和哈希进行排序,并且您需要使用一些看起来很奇怪的字符串,以免发生任何冲突.
This should properly flatten out and sort the arrays and hashes, and you'd need to have to some pretty strange looking strings for there to be any collisions.
def createsig(body)
Digest::MD5.hexdigest( sigflat body )
end
def sigflat(body)
if body.class == Hash
arr = []
body.each do |key, value|
arr << "#{sigflat key}=>#{sigflat value}"
end
body = arr
end
if body.class == Array
str = ''
body.map! do |value|
sigflat value
end.sort!.each do |value|
str << value
end
end
if body.class != String
body = body.to_s << body.class.to_s
end
body
end
> sigflat({:a => {:b => 'b', :c => 'c'}, :d => 'd'}) == sigflat({:d => 'd', :a => {:c => 'c', :b => 'b'}})
=> true
这篇关于在Ruby中创建数字,字符串,数组或哈希值的md5哈希值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!