0

我正在尝试在 C# 中实现计算的哈希值,它应该与 Perl 模块生成的哈希值相匹配

perl代码如下

#!/user/bin/perl
#
use Digest::MD5 'md5_hex';

my $rawvalue = "HelloWorld";
my $salt = "12345678";
my $md5 = Digest::MD5->new;
$md5->add($rawvalue,$salt);

my $md5Digest = $md5->hexdigest;
print $md5Digest;
print "\n";

输出为:a4584f550a133a7f47cc9bafd84c9870

我在 C# 中尝试了以下方法 - 但无法获得相同的结果。

    string salt = "12345678";
    string data = "HelloWorld";

    byte[] saltbyte = System.Text.Encoding.UTF8.GetBytes(salt);
    byte[] databyte = System.Text.Encoding.UTF8.GetBytes(data);

    //HMACMD5
    HMACMD5 hmacmd5 = new HMACMD5(saltbyte);
    byte[] hmacmd5hash = hmacmd5.ComputeHash(databyte);
    StringBuilder sBuilder = new StringBuilder();
    for (int i = 0; i < hmacmd5hash.Length; i++)
    {
        sBuilder.Append(hmacmd5hash[i].ToString("x2"));
    }
    Console.WriteLine(sBuilder.ToString()); //outputs 2035a1ff1bf3a5ddec8445ada2e4883c



    //HMACSHA1
    HMACSHA1 hmacsha1 = new HMACSHA1(saltbyte);
    byte[] hmacsha1hash = hmacsha1.ComputeHash(databyte);
    sBuilder = new StringBuilder();
    for (int i = 0; i < hmacsha1hash.Length; i++)
    {
        sBuilder.Append(hmacsha1hash[i].ToString("x2"));
    }
    Console.WriteLine(sBuilder.ToString()); //outputs a8beb5b2f63c9574fea28f4c1d9e59306a007924

作为最后的手段,我可​​能会求助于启用 perl cgi 来计算遗留哈希..但我想尽可能避免这种情况!

谢谢!

4

1 回答 1

1

看起来您的 perl 代码只是将数据与盐连接起来,然后散列 -a4584f550a133a7f47cc9bafd84c9870只是"HelloWorld" + "12345678".

而不是使用 HMACMD5,您只需要使用MD5执行以下操作:

using (MD5 a = MD5.Create()) {
    byte[] bytes = Encoding.UTF8.GetBytes(data + salt);
    byte[] hashed = a.ComputeHash(bytes);

    var sb = new StringBuilder();        
    for (int i = 0; i < hashed.Length; i++) {
       sb.Append(hashed[i].ToString("x2"));
    }
    Console.WriteLine(sb.ToString()); // a4584f550a133a7f47cc9bafd84c9870
}
于 2013-05-30T06:10:03.730 回答