在MS SQL中使用HASHBYTES比较哈希密码

时间:2017-10-23 09:02:36

标签: sql-server hash

我有一个简单的问题:

print HASHBYTES('SHA1', 'az09123')

告诉我:

0xA00592FC3E531C5F7608110F73E8AE4B4F2EA4C3enter

我把它放在名为OwnerEn

的navchar字段中

然后我试试这个:

SELECT * FROM AspNetUsers WHERE OwnerEn =  HASHBYTES('SHA1', 'az09123');

没有结果,它是空的

但这给了我结果:

SELECT * FROM AspNetUsers WHERE OwnerEn = '0xA00592FC3E531C5F7608110F73E8AE4B4F2EA4C3';

第一个sql语句有什么问题?

2 个答案:

答案 0 :(得分:1)

正如Oscar在评论中提到的那样,您看不到任何结果,因为nvarchar0xA00592FC3E531C5F7608110F73E8AE4B4F2EA4C3与二进制值0xA00592FC3E531C5F7608110F73E8AE4B4F2EA4C3不同。

理想情况下,您可以将哈希值存储在适当的binaryvarbinary数据类型列中,但如果您无法在数据库中更改哈希值,则需要convert nvarchar值为binaryvarbinary(反之亦然),以便实际比较这两个值:

请注意1末尾的convert,以指定您希望在开头添加0x

nvarcharvarbinary

convert(varbinary(max),'0xA00592FC3E531C5F7608110F73E8AE4B4F2EA4C3',1)

varbinarynvarchar

convert(nvarchar(100),hashbytes('SHA1', 'az09123'),1)

以下脚本对此进行了演示:

select hashbytes('SHA1', 'az09123') as BinaryHash
      ,convert(varbinary(max),'0xA00592FC3E531C5F7608110F73E8AE4B4F2EA4C3',1) as NvarcharHash
      ,case when hashbytes('SHA1', 'az09123') = '0xA00592FC3E531C5F7608110F73E8AE4B4F2EA4C3'
            then 'Match'
            else 'No Match'
            end as UnconvertedMatchTest
      ,case when hashbytes('SHA1', 'az09123') = convert(varbinary(max),'0xA00592FC3E531C5F7608110F73E8AE4B4F2EA4C3',1)
            then 'Match'
            else 'No Match'
            end as ConvertedMatchTest

输出:

+--------------------------------------------+--------------------------------------------+----------------------+--------------------+
|                 BinaryHash                 |                NvarcharHash                | UnconvertedMatchTest | ConvertedMatchTest |
+--------------------------------------------+--------------------------------------------+----------------------+--------------------+
| 0xA00592FC3E531C5F7608110F73E8AE4B4F2EA4C3 | 0xA00592FC3E531C5F7608110F73E8AE4B4F2EA4C3 | No Match             | Match              |
+--------------------------------------------+--------------------------------------------+----------------------+--------------------+

答案 1 :(得分:0)

试试这个,它有效。

DECLARE @AspNetUsers TABLE (OwnerEn VARCHAR(50))

INSERT INTO @AspNetUsers VALUES ('0xA00592FC3E531C5F7608110F73E8AE4B4F2EA4C3')


SELECT *
FROM   @AspNetUsers
WHERE  OwnerEn  = master.dbo.Fn_varbintohexstr(HASHBYTES('SHA1', 'az09123'))

<强>输出:

enter image description here