计算“nvarchar”的 SHA1 哈希值使用 T-SQL 的字符串
我正在尝试使用 T-SQL 计算 unicode 字符串的 SHA1
哈希值。下面的代码可以很好地处理 ASCII
字符串:
declare @input varchar(50)
set @input = 'some text'
print 'SHA1 Hash: ' + UPPER(master.dbo.fn_varbintohexsubstring(0, HashBytes('SHA1', @input), 1, 0))
但是当我用 declare @input nvarchar(50)
替换第一行代码时,它计算出错误的哈希值。
Calculated hash (nvarchar): BBA91B680CE2685E9465DE24967E425CF055B10F
Calculated hash by a tool : 37AA63C77398D954473262E1A0057C1E632EDA77
如何计算 nvarchar
的 SHA1
哈希值?
[编辑]:
下面的 C# 代码生成与我用于散列的工具相同的散列:
// Computes SHA1 hash of a given string
string ComputeHash(string input)
{
string result = string.Empty;
byte[] hash;
byte[] bytes = Encoding.GetBytes(input);
using (var sha = SHA1Managed.Create())
hash = sha.ComputeHash(bytes);
foreach (var b in hash)
result += b.ToString("X2");
return result;
}
I'm trying to calculate SHA1
hash of a unicode string using T-SQL. The below code works fine with ASCII
strings:
declare @input varchar(50)
set @input = 'some text'
print 'SHA1 Hash: ' + UPPER(master.dbo.fn_varbintohexsubstring(0, HashBytes('SHA1', @input), 1, 0))
but it calculates wrong hash when I replace first line of code with declare @input nvarchar(50)
.
Calculated hash (nvarchar): BBA91B680CE2685E9465DE24967E425CF055B10F
Calculated hash by a tool : 37AA63C77398D954473262E1A0057C1E632EDA77
How can I calculate SHA1
hash of a nvarchar
?
[EDIT]:
Below C# code generate same hash as the tool I use for hashing:
// Computes SHA1 hash of a given string
string ComputeHash(string input)
{
string result = string.Empty;
byte[] hash;
byte[] bytes = Encoding.GetBytes(input);
using (var sha = SHA1Managed.Create())
hash = sha.ComputeHash(bytes);
foreach (var b in hash)
result += b.ToString("X2");
return result;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当您将工具返回的哈希值与 SQL Server 返回的哈希值进行比较时,您确定该工具返回的哈希值使用的是
UTF16
或 Unicode 编码吗?...SHA1
(以及其他编码)格式)取决于数据类型,因此当作为输入给出时它应该返回不同的值。看一下 此链接可获取更详细的说明。Are you sure that the hash returned by your tool is using
UTF16
or Unicode encoding when you compare it with the one returned by SQL Server?...SHA1
(and other encoding formats) depends on the data type, so it should return different values when given as an input. Take a look at this link for a more detailed explanation.