Eul*_*367 9 c# sql-server hash bigint uint64
我正在尝试创建一个通用散列alogrithim,它将字符串散列为64位int.
我能够正确地散列字符串:sql:
select
convert
(
varchar(64),
HASHBYTES
(
'SHA1',
'google.com'
),
2
)
Run Code Online (Sandbox Code Playgroud)
回报 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();
Run Code Online (Sandbox Code Playgroud)
retruns BAEA954B95731C68AE6E45BD1E252EB4560CDC45
但是,当我转换为bigint/long时,值不匹配:sql:
select
convert
(
bigint,
HASHBYTES
(
'SHA1',
'google.com'
)
)
Run Code Online (Sandbox Code Playgroud)
回报 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);
Run Code Online (Sandbox Code Playgroud)
回报 7501998164347841210
有关如何使这些数字匹配的任何想法?
您的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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3445 次 |
| 最近记录: |