0

我想知道是否有人可以帮助我将此方法转换为 ruby​​,这可能吗?

public static string getSHA512(string str){
    UnicodeEncoding UE = new UnicodeEncoding();
    byte[] HashValue = null;
    byte[] MessageBytes = UE.GetBytes(str);
    System.Security.Cryptography.SHA512Managed SHhash = new System.Security.Cryptography.SHA512Managed();
    string strHex = "";
    HashValue = SHhash.ComputeHash(MessageBytes);
    foreach (byte b in HashValue){
        strHex += string.Format("{0:x2}", b);
    }
    return strHex;
}

提前致谢


更新:

我只是想澄清一下,不幸的是,它的方法不仅适用于 SHA512 生成,而且是一种自定义方法。我相信 Digest::SHA512.hexdigest 只是 SHHast 实例,但是如果您仔细寻找该方法,您会发现它与简单的哈希生成有点不同。遵循两个函数的结果。

# in C#
getSHA512("hello") => "5165d592a6afe59f80d07436e35bd513b3055429916400a16c1adfa499c5a8ce03a370acdd4dc787d04350473bea71ea8345748578fc63ac91f8f95b6c140b93"

# in Ruby
Digest::SHA512.hexdigest("hello") || Digest::SHA2 => "9b71d224bd62f3785d96d46ad3ea3d73319bfbc2890caadae2dff72519673ca72323c3d99ba5c11d7c7acc6e14b8c5da0c4663475c2e5c3adef46f73bcdec043" 
4

2 回答 2

3
require 'digest/sha2'

class String
  def sha512
    Digest::SHA2.new(512).hexdigest(encode('UTF-16LE'))
  end
end

'hello'.sha512 # => '5165d592a6afe59f80d07436e35bd…5748578fc63ac91f8f95b6c140b93'

与我在 StackOverflow 上的所有代码片段一样,我总是假设使用的是最新版本的 Ruby。这里有一个也适用于 Ruby 1.8:

require 'iconv'
require 'digest/sha2'

class String
  def sha512(src_enc='UTF-8')
    Digest::SHA2.new(512).hexdigest(Iconv.conv(src_enc, 'UTF-16LE', self))
  end
end

'hello'.sha512 # => '5165d592a6afe59f80d07436e35bd…5748578fc63ac91f8f95b6c140b93'

请注意,在这种情况下,您必须明确地知道并告诉 Ruby 字符串的编码。在 Ruby 1.9 中,Ruby 始终知道字符串的编码方式,并会在需要时进行相应的转换。我选择 UTF-8 作为默认编码,因为它向后兼容 ASCII,是 Internet 上的标准编码,并且在其他方​​面也被广泛使用。但是,例如 .NET 和 Java 都使用 UTF-16LE,而不是 UTF-8。如果您的字符串不是 UTF-8 或 ASCII 编码,则必须将编码名称传递给sha512方法。


题外话:9 行代码减少到 1 行。我爱 Ruby!

嗯,实际上这有点不公平。你可以这样写:

var messageBytes = new UnicodeEncoding().GetBytes(str);
var hashValue = new System.Security.Cryptography.SHA512Managed().
    ComputeHash(messageBytes);
return hashValue.Aggregate<byte, string>("",
    (s, b) => s += string.Format("{0:x2}", b)
);

这实际上只有 3 行(StackOverflow 的布局分为 5 行),最重要的是摆脱了 1950 年代丑陋的显式for循环,实现了 1960 年代风格的折叠(又名。reduce又名。inject又名。Aggregate又名inject:into:。......都是一样的)。

可能有一种更优雅的方式来写这个,但是a)我实际上并不了解C#和.NET,b)这个问题是关于Ruby的。专注,约尔格,专注!:-)

Aaand ...找到它:

return string.Join("", from b in hashValue select string.Format("{0:x2}", b));

知道在某个地方必须有一个与 Ruby 相当的东西Enumerable#join,我只是找错了地方。

于 2010-06-23T13:44:45.790 回答
0

使用Digest::SHA2类。

于 2010-06-23T13:23:53.540 回答