2013-03-22 144 views
9

我想创建一个通用哈希alogrithim哈希一个字符串作为64位int。SQL bigint哈希匹配c#int64哈希

我能够正确地散列字符串: SQL:

select 
    convert 
    (
     varchar(64), 
     HASHBYTES 
     (
      'SHA1', 
      'google.com' 
     ), 
     2 
    ) 

回报BAEA954B95731C68AE6E45BD1E252EB4560CDC45

C#

System.Security.Cryptography.SHA1 c = System.Security.Cryptography.SHA1.Create(); 
    System.Text.StringBuilder sb = new StringBuilder(); 
    byte[] b = c.ComputeHash(Encoding.UTF8.GetBytes("google.com")); 
    for (int i = 0; i < b.Length;i++) 
    { 
     byte by = b[i]; 
     sb.Append(by.ToString("x2").ToUpper()); 
    } 

    return sb.ToString(); 

retruns BAEA954B95731C68AE6E45BD1E252EB4560CDC45

然而,当我转换为BIGINT/LO NG的值不匹配: SQL:

select 
    convert 
    (
     bigint, 
     HASHBYTES 
     (
      'SHA1', 
      'google.com' 
     ) 
    ) 

回报2172193747348806725

C#:

System.Security.Cryptography.SHA1 c = System.Security.Cryptography.SHA1.Create(); 
    byte[] b = c.ComputeHash(Encoding.UTF8.GetBytes("google.com")); 
    return BitConverter.ToInt64(b, 0); 

回报7501998164347841210

如何得到这些数字匹配任何想法?

+0

在这里看到:http://stackoverflow.com/questions/8467072/sql-server-varbinary-bigint-with-bitconverter-toint64-values-are-different了可能的方案。 – 2013-03-22 21:27:23

+0

而不是在对象上生成自己的哈希,您应该只使用['GetHashCode'](http://msdn.microsoft.com/en-us/library/system.object.gethashcode.aspx),它比重新创建更有效轮子,具有相同字符的字符串将产生相同的“HashCode”。 – Killrawr 2013-03-22 21:37:53

+2

@Killrawr:GetHashCode只能用来平衡哈希表。我们没有证据表明原始海报试图平衡散列表;它看起来很像他们正在尝试密码强度散列。 **从不使用GetHashCode **加密哈希是非常非常重要的。它具有* none *您需要制作安全哈希的属性。同样,如果您调用GetHashCode,并且您现在不想平衡哈希表,那么您做错了什么。 – 2013-03-22 21:46:10

回答

8

您的SQL bigint需要最后8个字节,而c#实现需要前8个字节(并且因为它在小端上运行而反转它们)。

在C#中取出适当的数组范围并将其反转。那你应该没问题。

做了一些编码:

System.Security.Cryptography.SHA1 c = System.Security.Cryptography.SHA1.Create(); 
byte[] b = c.ComputeHash(Encoding.UTF8.GetBytes("google.com")); 
long value = BitConverter.ToInt64(b, 12); 
value = IPAddress.HostToNetworkOrder(value); 

Debug.WriteLine(value); 
// writes 2172193747348806725 
+0

你可以使用'var reversed = BitConverter.GetBytes(IPAddress.HostToNetworkOrder(longValue))'交换字节。 – 2013-03-22 21:31:46

+0

非常好的答案! – 2013-03-22 21:36:09

+1

@DasKrumelmonster:如果使用'BitConverter.GetBytes(IPAddress.HostToNetworkOrder(longValue))'而不是Linq,它将工作,不管客户端的字节顺序如何,因为HostToNetworkOrder()对它进行了说明。 – 2013-03-22 21:41:59