gpt4 book ai didi

java - 将字符串的 MD5 哈希值的最高 8 个字节视为 long(在 Ruby 中)

转载 作者:行者123 更新时间:2023-12-01 16:05:24 24 4
gpt4 key购买 nike

嘿 friend 们,我正在尝试在 ruby​​ 中实现 java“哈希”函数。

这是java端:

import java.nio.charset.Charset;
import java.security.MessageDigest;

/**
* @return most significant 8 bytes of the MD5 hash of the string, as a long
*/
protected long hash(String value) {
byte[] md5hash;
md5hash = md5Digest.digest(value.getBytes(Charset.forName("UTF8")));
long hash = 0L;
for (int i = 0; i < 8; i++) {
hash = hash << 8 | md5hash[i] & 0x00000000000000FFL;
}
return hash;
}

到目前为止,我对 ruby​​ 的最佳猜测是:

# WRONG - doesn't work properly.
#!/usr/bin/env ruby -wKU

require 'digest/md5'
require 'pp'

md5hash = Digest::MD5.hexdigest("0").unpack("U*")
pp md5hash
hash = 0
0.upto(7) do |i|
hash = hash << 8 | md5hash[i] & 0x00000000000000FF
end
pp hash

问题是,这个 ruby​​ 代码与 java 输出不匹配。

作为引用,上面的java代码给定这些字符串返回相应的long:

"00038c53790ecedfeb2f83102e9115a522475d73" => -2059313900129568948
"0" => -3473083983811222033
"001211e8befc8ac22dd265ecaa77f8c227d0007f" => 3234260774580957018

想法:

  • 我在从 ruby​​ 字符串获取 UTF8 字节时遇到问题
  • 在 ruby​​ 中,我使用 hexdigest,我怀疑我应该只使用 digest
  • Java 代码采用 UTF8 字节的 md5,而我的 ruby​​ 代码采用 md5 的字节(十六进制)

关于如何在 ruby​​ 中获得完全相同的输出有什么建议吗?

最佳答案

require 'digest/md5'

class String
def my_hash
hi1, hi2, mid, lo = *Digest::MD5.digest(self).unpack('cCnN')
hi1 << 56 | hi2 << 48 | mid << 32 | lo
end
end

require 'test/unit'
class TestMyHash < Test::Unit::TestCase
def test_that_my_hash_hashes_the_string_0_to_negative_3473083983811222033
assert_equal -3473083983811222033, '0'.my_hash
end
end

关于java - 将字符串的 MD5 哈希值的最高 8 个字节视为 long(在 Ruby 中),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2738249/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com