SQL HASHBYTES返回不同的值 [英] SQL HASHBYTES returns different value

查看:74
本文介绍了SQL HASHBYTES返回不同的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用程序中,HASHBYTES SQL函数为同一个字符串返回不同的值。

以下是我的用户创建代码。

In my Application, the HASHBYTES SQL function returns different values for same string.
Below is my user creation code.

Guid fillerG = Guid.NewGuid(); 
using (SqlCommand com = new SqlCommand("INSERT INTO App_Users (UserName, PasswordHash, PasswordSalt) VALUES ('" + userNameTxt.Text + "', HASHBYTES ( 'SHA1', CONVERT(NVARCHAR(100), '" + userPassword.Text + fillerG.ToString() + "') ),  '" + fillerG.ToString() + "'; ", con))
{
    com.ExecuteNonQuery();
}



如果我在登录页面中比较上面插入的行,则不匹配。

这是我的比较脚本。


If I compare the above inserted row in my Login Page, It doesn't match.
This is my comparing script.

SqlCommand loginCom = new SqlCommand("select COUNT(UserID) FROM App_Users WHERE UserName = '" + Login1.UserName.Replace("'", "''") + "' AND PasswordHash = HASHBYTES('SHA1', '" + Login1.Password.Replace("'", "''") + "' + CONVERT(NVARCHAR(36), PasswordSalt))", loginCon);





第一个代码将passwordHash存储为:



The first code stores the passwordHash as this:

0xDAC9280F85B40C06314228876717E342432807DB



但是在查询窗口中,具有相同值的HASHBYTES函数返回:


But in the query window, the HASHBYTES function with same value returns this:

0xA561FBD35713F922AD761594658C193F12B82791

推荐答案

这可能是因为在这两种情况下HASH有不同的字符串...

在第一种情况下,您使用HASH密码+填充,但在第二种情况下,您首先在HASH之前将单引号替换为两个单引号!
That's maybe because in the two cases you have different strings to HASH...
In the first case you HASH password + filler, but in the second case you first replace single quote to two single quotes before HASH!!!


人们必须为SQL语句使用字符串吗?难怪OP无法弄清楚HASH功能发生了什么......我花了更长时间阅读代码而不是弄清楚Kornfeld Eliyahu Peter认为该功能传入/返回错误且不同的结果。 。



为了安全起见(阅读SQL注入)并为了下一个开发人员的理智,使用SQLParameters传递值而不是使用一堆字符串......
Must people use strings for SQL statements? No wonder the OP couldn't figure out what was happening with the HASH function... It took me longer to read the code than to figure out as Kornfeld Eliyahu Peter had that the function was passing in/back incorrect and different results...

For the sake of security (Read up on SQL injection) and for the sake of the next developer's sanity, use SQLParameters to pass values instead of working with a bunch of strings...


这篇关于SQL HASHBYTES返回不同的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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