Hi I have a program where I request a username and password from a user through WPF, I then send the data to a database where it is stored.
private void btnRegister_Click(object sender, RoutedEventArgs e)
{
try
{
using (SqlConnection connection = new SqlConnection(ConnectionSQL.conn))
{
SqlCommand command = new SqlCommand("INSERT INTO USERTABLE " +
"VALUES(@Username, @Password);" +
"Select SCOPE_IDENTITY();", connection);
command.Parameters.AddWithValue("@Username", txtbUsername.Text);
command.Parameters.AddWithValue("@Password", Utils.hashPassword(txtbPassword.Text));
connection.Open();
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.InsertCommand = command;
int id = Convert.ToInt32(adapter.InsertCommand.ExecuteScalar());
MessageBox.Show("User Registered! User has been added to the database: " + id);
adapter.Dispose();
String Username = txtbUsername.Text;
String Password = txtbPassword.Text;
Users temp = new Users(id, Username, Password);
Login L = new Login();
arrUsers.Add(temp);
Hide();
L.ShowDialog();
}
}
catch (SqlException ex)
{
MessageBox.Show("Error Connecting to the Database", "Connection Error" + ex.ToString());
}
}
I created a function to store the password as a hash in the database.
public class Utils
{
public static string hashPassword(String password)
{
SHA1CryptoServiceProvider sha1 = new SHA1CryptoServiceProvider();
byte[] password_bytes = Encoding.ASCII.GetBytes(password);
byte[] encrypted_bytes = sha1.ComputeHash(password_bytes);
return Convert.ToBase64String(encrypted_bytes);
}
}
When I try log in and validate password when its stored as a hash it doesnt work.
private void btnLogin_Click(object sender, RoutedEventArgs e)
{
try
{
using (SqlConnection connection = new SqlConnection(ConnectionSQL.conn))
{
connection.Open();
String Username = Convert.ToString(txtbUsername.Text);
String Password = Convert.ToString(txtbPassword.Text);
String sql = "SELECT * FROM USERTABLE where Username = '" + Username + "' " +
"AND Password = '" + Password + "' ;";
SqlCommand command = new SqlCommand(sql, connection);
SqlDataReader reader = command.ExecuteReader();
if (reader.HasRows)
{
MessageBox.Show("You Have Successfully Logged In");
MainWindow Main = new MainWindow();
txtbUsername.Text = "";
txtbPassword.Text = "";
this.Hide();
Main.ShowDialog();
this.Show();
}
else
{
MessageBox.Show("Invalid Credentials");
}
reader.Close();
command.Dispose();
}
}
catch (SqlException ex)
{
Console.WriteLine(ex.ToString());
}
Console.ReadLine();
}
Although when i dont hash the password in the database it works. Any tips on solving this?