【发布时间】:2020-02-17 07:49:38
【问题描述】:
大家好,
我有一个问题。我已经能够使用 user_ID、用户名和密码字段创建用户帐户。
密码经过哈希处理和加盐处理,工作正常。 现在我想创建一个登录表单,用户需要使用用户名和密码进行身份验证。
我想验证提供的密码和用户名是否正确。此密码必须先进行哈希处理,然后与数据库中的密码进行比较。
下面是我的代码,但它总是带来密码错误的错误。
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;
}
【问题讨论】:
-
盐存放在哪里?这不是在这里丢失,还是您的密码哈希器的一部分?
-
另外,我假设它是存储在数据库中的散列密码。如果是这样,您的
hash变量应该只是var hash = mypassword没有额外的哈希调用(计算哈希的哈希)。 -
@KurtHamilton,盐是哈希器的一部分。我将添加哈希算法进行编辑
-
@erdomke 我也看到了。正在进行双重哈希
-
@erdomke,哇,谢谢。我仍然在再次散列它。我的错。你能把这个作为答案让我打勾吗?效果很好