I am trying to verify a hashed password in my database which has been hashed with BCrypt.
I have two web forms, a login page and registration page.
In the registration page i create the hash, verify the hash and insert it into the database. Works fine.
In the login page i select the hashed password from the database and compare it with the submitted password from the text box.
I seem to be having trouble when verifying the hash in the database against the submitted password, i don't know what is going wrong.
Here is the registration page code:
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";
}
}
Here is the login page code:
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";
}
}
}
}
}
Help and Feedback is appreciated.