I have an ASP.NET web project with web form. for my log in, I need to store user password in hashed format. And also retrieve the password when logging in.
My table has columns
username varchar(50) Primary key,
mobile varchar(50),
pass varchar(50)
My C# code is
try
{
Console.WriteLine("inside try");
SqlConnection con = new SqlConnection(strcon);
con.Open();
SqlCommand cmd = new SqlCommand("INSERT INTO signinup ([username], [mobile], [pass])
VALUES (@username, @mobile, @pass)", con);
cmd.Parameters.AddWithValue("@username", usernametextbox.Text.Trim());
cmd.Parameters.AddWithValue("@mobile", mobiletextbox.Text.Trim());
cmd.Parameters.AddWithValue("@pass", passwordtextbox.Text.Trim());
cmd.ExecuteNonQuery();
con.Close();
Response.Redirect("~/login.aspx");
}
catch (Exception ex)
{
Response.Write("<script>alert('Error: " + ex.Message + "');</script>");
}
I tried this
string plainPassword = passwordtextbox.Text.Trim();
byte[] hashedPasswordBytes;
using (SHA256 sha256 = SHA256.Create())
{
hashedPasswordBytes = sha256.ComputeHash(Encoding.UTF8.GetBytes(plainPassword));
}
string hashedPassword = BitConverter.ToString(hashedPasswordBytes).Replace("-", string.Empty);
cmd.Parameters.AddWithValue("@pass", hashedPassword );
And also this
string password = passwordtextbox.Text.Trim();
string hashedPassword = HashPassword(password);
cmd.Parameters.AddWithValue("@pass", hashedPassword);
private string HashPassword(string password)
{
using (SHA256 sha256 = SHA256.Create())
{
byte[] passwordBytes = Encoding.UTF8.GetBytes(password);
byte[] hashBytes = sha256.ComputeHash(passwordBytes);
string hashedPassword = BitConverter.ToString(hashBytes).Replace("-", "").ToLower();
return hashedPassword;
}
}
But it's not working