我想创建一个通用哈希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
如何得到这些数字匹配任何想法?
在这里看到:http://stackoverflow.com/questions/8467072/sql-server-varbinary-bigint-with-bitconverter-toint64-values-are-different了可能的方案。 – 2013-03-22 21:27:23
而不是在对象上生成自己的哈希,您应该只使用['GetHashCode'](http://msdn.microsoft.com/en-us/library/system.object.gethashcode.aspx),它比重新创建更有效轮子,具有相同字符的字符串将产生相同的“HashCode”。 – Killrawr 2013-03-22 21:37:53
@Killrawr:GetHashCode只能用来平衡哈希表。我们没有证据表明原始海报试图平衡散列表;它看起来很像他们正在尝试密码强度散列。 **从不使用GetHashCode **加密哈希是非常非常重要的。它具有* none *您需要制作安全哈希的属性。同样,如果您调用GetHashCode,并且您现在不想平衡哈希表,那么您做错了什么。 – 2013-03-22 21:46:10