I'm trying to hash the password fields for the users on my program with SHA 256 but I'm having trouble trying to wrap my head around it. The datatype for my password field on my database is CHAR(64). Any help or tips would be greatly appreciated.
Here is my hash function
public static string ToSHA256(string s)
{
var sha256 = SHA256.Create();
byte[] bytes = sha256.ComputeHash(Encoding.UTF8.GetBytes(s));
var sb = new StringBuilder();
for (int i = 0; i < bytes.Length; i++)
{
sb.Append(bytes[i].ToString("x2"));
}
return sb.ToString();
}
Im trying to call this SHA256 function on my login function but it just breaks the login's functionality? No error exceptions are thrown just gives me my own validation error of "Username or password is incorrect". The error is related to the line with "ToSHA256(txtPassword.Password));"
Login Function
private void btnLogin_Click(object sender, RoutedEventArgs e)
{
SqlConnection sqlcon = new SqlConnection(@"Data Source=.\SQLEXPRESS2016;Initial Catalog=wpfCrud;Integrated Security=True");
try
{
if (sqlcon.State == ConnectionState.Closed)
sqlcon.Open();
String query = "SELECT COUNT(1) FROM Login WHERE Username=@Username AND Password=@Password";
SqlCommand sqlCmd = new SqlCommand(query, sqlcon);
sqlCmd.CommandType = CommandType.Text;
sqlCmd.Parameters.AddWithValue("@Username", txtUsername.Text);
sqlCmd.Parameters.AddWithValue("@Password", ToSHA256(txtPassword.Password));
int count = Convert.ToInt32(sqlCmd.ExecuteScalar());
if (count == 1)
{
UserMan dashboard = new UserMan();
dashboard.Visibility = Visibility.Visible;
}
else
{
MessageBox.Show("Username or password is incorrect.");
}
}
finally
{
}
}