尝试在登录表单中实现哈希和加盐密码
本文关键字:哈希 密码 实现 登录 表单 | 更新日期: 2023-09-27 18:34:37
我正在尝试将哈希和盐渍密码实现到登录表单中,其中我有简单的mysql连接数据库,其中包含id-Int,用户名-VarChar,password-VarChar和salt-VarChar。当我尝试调试程序并输入正确的数据时,我仍然得到
错误的细节
显示框。偶然查看下面的代码,您知道我的错误在哪里以及如何解决问题。
PS:请注意,对于数据库中的"盐"字段,我尝试插入与密码相同的数据,试图将其保留为白色,尝试将其从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!");
}
我试图重现您的问题。(只是哈希算法(看来这条线不对
plainTextBytes.CopyTo(plainTextWithSaltBytes, salt.Length);
相反,您应该使用
plainTextBytes.CopyTo(plainTextWithSaltBytes, saltBytes.Length);
然而,这给了我一个例外,而不是错误的读者。读。
因此,问题可能是不同的。您应该尝试在调试中在读取器之前停止程序。读取并检查@username和@password的值。
使用该信息,使用首选的MySql管理器检查用户表是否完全包含参数中的值。