使用T-SQL计算'nvarchar'字符串的SHA1哈希值 [英] Calculating SHA1 hash of a 'nvarchar' string using T-SQL

查看:320
本文介绍了使用T-SQL计算'nvarchar'字符串的SHA1哈希值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图用T-SQL来计算 SHA1 一个unicode字符串的散列值。下面的代码可以正常工作: ASCII 字符串:

  declare @input varchar (50)
set @input ='some text'
print'SHA1 Hash:'+ UPPER(master.dbo.fn_varbintohexsubstring(0,HashBytes('SHA1',@input),1,0) )

但是当我用替换第一行代码时,它会计算错误的散列declare计算散列(nvarchar):BBA91B680CE2685E9465DE24967E425CF055B10F
计算得出的散列值(nvarchar):BBA91B680CE2685E9465DE24967E425CF055B10F
计算得出的散列值(nvarchar):@input nvarchar(50)

如何计算 SHA1 $ c $> nvarchar



<编辑]:



在C#代码下面生成与我用于散列的工具相同的散列:

  //计算SHA1哈希值给定字符串
字符串ComputeHash(字符串输入)
{
字符串结果=字符串.Empty;
byte [] hash;
byte [] bytes = Encoding.GetBytes(input);

使用(var sha = SHA1Managed.Create())
hash = sha.ComputeHash(bytes);

foreach(散列中的变量b)
结果+ = b.ToString(X2);

返回结果;
}


解决方案

当您将它与SQL Server返回的结果进行比较时,您的工具返回的结果是使用 UTF16 或Unicode编码吗?... SHA1 (以及其他编码格式)取决于数据类型,因此当作为输入提供时它应该返回不同的值。看看这个链接的更详细的解释。


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;
}

解决方案

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.

这篇关于使用T-SQL计算'nvarchar'字符串的SHA1哈希值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆