[英]C# - MySQL Database, Check password is correct when it's encrypted?
我在程序中使用的是MySQL数据库,当我检查用户输入的密码是否正确时,它总是说它是无效的。 我对电子邮件也一样,但是可以。 我认为这是因为我的PHP脚本在页面上创建密码时会对其进行加密。 这是我的代码:
try
{
string command = "SELECT email FROM uc_users WHERE email = '@email';";
string command2 = "SELECT password FROM uc_users WHERE password = '@password';";
// CONNECTION DETAILS
connection = new MySqlConnection(connectionString);
connection.Open();
// COMMAND DETAILS
MySqlCommand email = new MySqlCommand(command, connection);
MySqlCommand passwordc = new MySqlCommand(command2, connection);
// PARAMETERS
email.Parameters.AddWithValue("@email", txtEmail.Text);
passwordc.Parameters.AddWithValue("@password", txtPassword.Text);
// READER DETAILS
MySqlDataReader dr;
MySqlDataReader dr2;
// CHECK DETAILS
dr = email.ExecuteReader();
string tempE = dr.Read() ? dr.GetString(0) : "Invalid Email";
dr.Close();
dr2 = passwordc.ExecuteReader();
string tempP = dr2.Read() ? dr.GetString(0) : "Invalid Password";
dr2.Close();
MessageBox.Show(tempE + " " + tempP);
if (tempE == txtEmail.Text && tempP == txtPassword.Text)
{
connection.Close();
tempE = "";
tempP = "";
string email2 = txtEmail.Text;
frmAppHub frm = new frmAppHub(email2);
frm.Show();
this.Hide();
}
else
{
MessageBox.Show("Invalid login details. Please try again.");
connection.Close();
tempE = "";
tempP = "";
}
}
catch(MySqlException ex)
{
MessageBox.Show("MySQL Error - Code AHx004: " +ex.Message);
connection.Close();
}
有什么想法怎么做? 任何帮助表示赞赏。
该查询从根本上被破坏了。 应该有一个查询,方法应该是这样的:
// No quotes around placeholder and only ONE query that does NOT select on the password.
// If the query selects on the password then it means that the password is either
// stored as plaitext (which is not good) or the database value can be computed without
// per-user information (which is also not good).
string command = "SELECT email, password FROM uc_users WHERE email = @email";
// Only look based on the user (the email column should have a Unique constraint)
// as (although a unique salt makes it very unlikely) passwords are not unique
// nor do they identify users.
email.Parameters.AddWithValue("@email", txtEmail.Text);
// Then read the password for the given user
dr = email.ExecuteReader();
if (!dr.Read()) {
// User not found - just stop.
return false;
}
string dbPassword = dr.GetString(1);
return IsPasswordMatch(dbPassword, txtPassword.Text);
现在, IsPasswordMatch
是一个函数,在给定数据库密码和纯文本密码的情况下,应该通过应用所有适当的哈希/盐/任何转换来确定它们是否匹配(请参阅我的第一条评论)。 无论如何,所有逻辑都可以安全地隐藏在其中。
它可能看起来像:
bool IsPasswordMatch (string dbPassword, string plaintext) {
var salt = GetSalt(dbPassword);
var dbHash = GetHash(dbPassword);
var ptHash = Hash(salt + plaintext);
return dbHash == ptHash;
}
我将这些方法保留为“高级操作”,这些方法需要首先适应于所使用的内容。 但是,基本操作现在应该显而易见。 只需重复开始时用于创建数据库值的相同过程-两种情况是否相同?
确保还阅读有关using
-这将使资源轻松清理而不会大惊小怪。
是的,您需要生成密码的哈希,该哈希必须与存储在数据库中的密码相同,然后使用该哈希查询命令,而不是纯文本密码。
如果您在DB和@passowrd中使用不同的字符串-您始终会有无效的结果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.