伙计们,
我有一个问题。我已经能够使用user_ID,Username和Password字段创建用户帐户。
密码已加密且已加密,可以正常使用。 现在,我想创建一个登录表单,其中需要使用用户名和密码对用户进行身份验证。
我想验证提供的密码和用户名是否正确。此密码必须首先是哈希,然后再与数据库中的密码进行比较。
下面是我的代码,但是它不断带来错误的密码错误。
try
{
string connString = CommonVariables.ConnectionString;
// Hashing the password field first for it to be
string sql = "SELECT * FROM tbl_Users WHERE (Username = @Username) ";
using (SqlConnection cnn = new SqlConnection(connString))
{
cnn.Open();
using (SqlCommand cmd = new SqlCommand(sql, cnn))
{
//cmd.Parameters.AddWithValue("@Password", SqlDbType.NVarChar).Value = txt_Password.Text.Trim();
cmd.Parameters.AddWithValue("@Username", SqlDbType.NVarChar).Value = txt_Username.Text.Trim();
SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
if (reader.HasRows)
{
while (reader.Read())
{
// string vsibility = reader["Visibility"].ToString(); //Getting the value of the visibility to determine if the user can logon or not
// string user_role = reader["User_Role"].ToString(); // Getting the User_role of the person login on
string mypassword = reader["password"].ToString();
var hash = PasswordHashing.SecurePasswordHasher.Hash(mypassword);
var hashverify = PasswordHashing.SecurePasswordHasher.Verify(txt_Password.Text.Trim(), hash);
if (hashverify == true)
{
this.Hide();
new Mainmenu().Show(); ;
}
else
{
MessageBox.Show("incorrect password" + mypassword);
}
}
}
else
{
MessageBox.Show("Invalid Username, Please Confirm", "Login Error", MessageBoxButtons.OK, MessageBoxIcon.Warning);
txt_Username.Focus();
return;
}
}
}
}
catch (Exception c)
{
MessageBox.Show(c.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
答案 0 :(得分:1)
假设您将密码的哈希存储在数据库中,则似乎是在对它进行两次哈希处理。特别是该行
var hash = PasswordHashing.SecurePasswordHasher.Hash(mypassword);
似乎正在计算已散列密码的散列。将其更改为var hash = mypassword;
可以帮助比较密码。