我正在尝试在登录表单中实现哈希和加盐密码,其中我有简单的 mysql 连接数据库,其中包含 id-Int、username-VarChar、password-VarChar 和 salt-VarChar。当我尝试调试程序并输入正确的数据时,我仍然得到
错误的细节
展示盒。看看下面的代码,您是否知道我的错误在哪里以及如何解决问题。
PS:请注意,对于我数据库中的“salt”字段,我尝试插入与密码相同的数据,尝试将其保留为空白,尝试将其从 varchar 更改为 Sha1,但仍然遇到相同的错误。
static byte[] GenerateSaltedHash(string plainText, string salt)
{
HashAlgorithm algorithm = new SHA256Managed();
byte[] plainTextBytes = System.Text.Encoding.Unicode.GetBytes(plainText);
byte[] saltBytes = Convert.FromBase64String(salt);
byte[] plainTextWithSaltBytes = new byte[plainTextBytes.Length + saltBytes.Length];
saltBytes.CopyTo(plainTextWithSaltBytes, 0);
plainTextBytes.CopyTo(plainTextWithSaltBytes, salt.Length);
byte[] hash = algorithm.ComputeHash(plainTextWithSaltBytes);
return hash;
}
public bool tryLogin(string username , string password)
{
using (var con = new MySqlConnection("host=localhost;user=admin;password=password;database=sozopouk_test2;"))
{
con.Open();
var salt = string.Empty;
using (MySqlCommand cmd = new MySqlCommand("Select salt From niki where user_name = @username", con))
{
cmd.Parameters.AddWithValue("@username", username);
salt = cmd.ExecuteScalar() as string;
}
if (string.IsNullOrEmpty(salt)) return false;
var hashedPassword = GenerateSaltedHash(password, salt);
using (var cmd = new MySqlCommand("Select * FROM niki WHERE user_name = @username and user_password = @password", con))
{
cmd.Parameters.AddWithValue("@username", username);
cmd.Parameters.AddWithValue("@password", hashedPassword);
using (var reader = cmd.ExecuteReader())
{
return reader.Read();
}
}
}
}
private void button1_Click(object sender, EventArgs e)
{
if (tryLogin(user.Text, pass.Text) == true)
{
MainScreen F2 = new MainScreen();
F2.Show();
this.Hide();
}
else MessageBox.Show("Wrong details!");
}