[英]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.