我想驗證我的數據庫中已經用BCrypt哈希處理過的哈希密碼。BCrypt驗證數據庫中密碼的密碼
我有兩個Web表單,登錄頁面和註冊頁面。
在註冊頁面我創建的哈希值,驗證哈希並將其插入到數據庫中。工作正常。
在登錄頁面我從數據庫中選擇的哈希密碼,並與從文本框中提交的密碼進行比較。
我似乎在對提交的密碼數據庫校驗散列時遇到了問題,我不知道什麼錯誤。
這裏是註冊頁面代碼:
protected void registerbutton_Click(object sender, EventArgs e)
{
string myPassword = passwordtextbox.Text;
string mySalt = BCryptHelper.GenerateSalt();
string myHash = BCryptHelper.HashPassword(myPassword, mySalt);
bool doesPasswordMatch = BCryptHelper.CheckPassword(myPassword, myHash);
if (doesPasswordMatch == true)
{
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString))
using (SqlCommand cmd = new SqlCommand("INSERT INTO dbo.Users (Username, Password, FirstName, LastName) VALUES (@username, @password, @firstname, @lastname)", conn))
{
cmd.Parameters.Add("@username", SqlDbType.NVarChar).Value = usernametextbox.Text;
cmd.Parameters.Add("@password", SqlDbType.Char).Value = myHash;
cmd.Parameters.Add("@firstname", SqlDbType.NVarChar).Value = firstnametextbox.Text;
cmd.Parameters.Add("@lastname", SqlDbType.NVarChar).Value = lastnametextbox.Text;
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
registerlabel3.Text = myHash;
}
}
else
{
registerlabel3.Text = "Error";
}
}
這裏是登錄頁面的代碼:
protected void loginbutton_Click(object sender, EventArgs e)
{
const string query = "SELECT Username, Password FROM dbo.Users WHERE Username = @username";
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString))
using (SqlCommand cmd = new SqlCommand(query, conn))
{
cmd.Parameters.Add("@username", SqlDbType.NVarChar).Value = usernametextbox.Text;
conn.Open();
//string hashedPassword = BCrypt.Net.BCrypt.HashPassword(passwordtextbox.Text);
using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
var passwordInDb = reader.GetString(1);
Label3.Text = "submitted = " + passwordtextbox.Text;
Label4.Text = "database hash = " + passwordInDb;
if(BCryptHelper.CheckPassword(passwordtextbox.Text, reader.GetString(1)))
{
//login
loginlabel.Text = "Success";
}
else
{
loginlabel.Text = "Error";
}
}
}
}
}
幫助和反饋理解。
什麼是數據庫中保存的密碼和哈希值? [其他人有你三年前的確切問題](http://stackoverflow.com/questions/22833610/bcrypthelper-checkpassword-always-returns-false)。這似乎是[BcryptHelper](https://www.npmjs.com/package/bcrypt-helper)的錯誤(因爲絕對沒有理由讓它失敗)。 –