我正在使用SHA256获取哈希的十六进制字符串。使用常规字符时,它可以很好地工作,但是当要哈希的字符串包含重音符号/变音符号时,在C#和T-SQL中我得到的结果将有所不同。我希望在SQL Server端进行更改。
C#
using (SHA256 sha2 = SHA256.Create())
{
var hash = sha2.ComputeHash(Encoding.UTF8.GetBytes(fullAddress));
string hexString = string.Empty;
for (int i = 0; i < hash.Length; i++)
{
hexString += hash[i].ToString("X2"); //Convert the byte to Hexadecimal representation, Notice that we use "X2" instead of "X"
}
sha2.Dispose();
return hexString;
}
SQL
declare @fullAddress nvarchar(500)
set @fullAddress = 'MUÑOZ'
select CONVERT([varchar](256), HASHBYTES('SHA2_256', @fullAddress), 2)
答案 0 :(得分:4)
.NET,Windows和SQL Server使用UTF16,而不是UTF8。这两个代码段对不同的字节进行哈希处理。使用相同编码时,哈希字符串相同。
此:
using (var sha2 = System.Security.Cryptography.SHA256.Create())
{
var hash = sha2.ComputeHash(Encoding.Unicode.GetBytes("MUÑOZ"));
{
string hexString = string.Empty;
for (int i = 0; i < hash.Length; i++)
{
hexString += hash[i].ToString("X2");
}
Console.WriteLine(hexString);
}
}
产生:
276DB000BF524070F106A2C413942159AB5EF2F5CA5A5B91AB2F3B6FA48EE1ED
与SQL Server的哈希字符串相同