gpt4 book ai didi

c# - 尝试在登录表单中实现哈希和加盐密码

转载 作者:行者123 更新时间:2023-11-30 23:31:01 26 4
gpt4 key购买 nike

我正在尝试在登录表单中实现哈希和加盐密码,其中我有简单的 mysql 连接数据库,其中包含 id-Int、用户名-VarChar、密码-VarChar 和 salt-VarChar。当我尝试调试程序并输入正确的数据时,我仍然得到

wrong details

展示框。看看下面的代码,您是否知道我的错误在哪里以及如何解决问题。

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!");
}

最佳答案

我已尝试重现您的问题。 (只是哈希算法)这条线好像不太对

plainTextBytes.CopyTo(plainTextWithSaltBytes, salt.Length);  

相反你应该使用

plainTextBytes.CopyTo(plainTextWithSaltBytes, saltBytes.Length);  

然而,这给了我一个异常(exception),而不是 reader.Read 上的错误。
因此,问题可能有所不同。您应该尝试在调试中先于读者停止程序。读取并检查@username 和@password 的值。
有了这些信息,使用您首选的 MySql 管理器,检查用户表是否包含参数中的值。

关于c# - 尝试在登录表单中实现哈希和加盐密码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10647880/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com