Reputation: 1859
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();
}
When 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 + "' AND PasswordHash = HASHBYTES('SHA1', '" + Login1.Password + "' + CONVERT(NVARCHAR(36), PasswordSalt))", loginCon);
The first code stores the passwordHash as this:
0xDAC9280F85B40C06314228876717E342432807DB
But in the query window, the HASHBYTES function with same value returns this:
0xA561FBD35713F922AD761594658C193F12B82791
UPDATE: Check this Image, The password Hash stored by the code is different than the password generated by the query (the password I gave is 'ee')
Upvotes: 2
Views: 1843
Reputation: 4630
You are passing Two different String to HASHBYTES thats why you are getting the different Result.
IN This Query:
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();
}
You are using userPassword.Text +fillerG.ToString()
as String
But
IN This Query:
Login1.Password.Replace("'", "''") + "' + CONVERT(NVARCHAR(36), PasswordSalt))", loginCon);
You are replacing the quotes
Login1.Password.Replace("'", "''")
Try like This: use parameterized Query
SqlCommand cmd = new SqlCommand("INSERT INTO App_Users (UserName, PasswordHash, PasswordSalt) VALUES (@username, HASHBYTES ( 'SHA1', CONVERT(NVARCHAR(100),@pass')),@salt), con)
cmd.Parameter.AddWithValue("@username",userNameTxt.Text);
cmd.Parameter.AddWithValue("@pass",userPassword.Text);
cmd.Parameter.AddWithValue("@salt",fillerG.ToString());
And
SqlCommand cmd = new SqlCommand("select COUNT(UserID) FROM App_Users WHERE UserName = @username AND PasswordHash = HASHBYTES ( 'SHA1', CONVERT(NVARCHAR(100),@salt)))), con)
cmd.Parameter.AddWithValue("@username",userNameTxt.Text);
cmd.Parameter.AddWithValue("@salt",Login1.Password);
Login1.Password and fillerG.ToString() must be Same
Upvotes: 5