0

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
            {
            }
        }
  • 4
    _"... but it just breaks the login's functionality?"_ - How? Does it throw an exception? Does it always fail? Does it always succeed? Does it randomly fail or succeed ... – Fildor Jan 17 '22 at 11:29
  • 6
    Please do not use SHA256 for password hashing. You should be using a secure hashing algorithm like BCrypt or Argon2 – phuzi Jan 17 '22 at 11:31
  • i think you should use exequtequery instead of scalar and get the count from the data reader, maybe there throws the exception – spzvtbg Jan 17 '22 at 11:34
  • @Fildor It doesn't recognise the user's credentials anymore and just gives me my own validation error of "Username or password is incorrect". No exception errors or program crashes just doesn't reach the database for validation anymore. – LearningCoder44 Jan 17 '22 at 11:38
  • 1
    Have you run the program through a debugger already and inspected the values? At which line does it start breaking, i.e. the variables contain unexpected values? – knittl Jan 17 '22 at 11:39
  • @spzvtbg When only one result is returned, `executeScalar` is perfectly fine .... – derpirscher Jan 17 '22 at 12:22
  • It might be an issue with `AddWithValue`. You mentioned you password column is `CHAR(64)` but `AddWithValue` *may* wrongly infer `NCHAR` which *may* produce wrong query results. That's why we should stop using `AddWithValue`. For details see https://blogs.msmvps.com/jcoehoorn/blog/2014/05/12/can-we-stop-using-addwithvalue-already/ – derpirscher Jan 17 '22 at 12:32
  • Furthermore you are saying *"It doesn't recognise the user's credentials anymore"* The "anymore" makes me suspicious. Did you store passwords in plaintext before? If yes, how did you update your password column to hashed values? Did you use the exact same `ToSHA256` method? Did you manually try comparing the result of `ToSHA256` to the passwordhash in the database. "*just doesn't reach the database for validation anymore*" doesn't seem to be the case. I suspect your `COUNT(*)` is returning `0` because there is no row meeting your condition ... – derpirscher Jan 17 '22 at 12:36
  • @derpirscher I've made changes to my code so it follows the syntax mentioned in that article - Thank you. I don't have any method to update my password column to hashed values. I just assumed the ToSHA256 method I currently have would do that for me by calling the method before the password field on the 2nd AddWithValue line for the password. Should I create another method to do that? – LearningCoder44 Jan 17 '22 at 13:57
  • 1
    So to make that clear: Your database *still* contains unhashed passwords? And now you are trying to find your logins with a query condition like `WHERE username='john' and password='5e884898da28047151d0e56f8dc6292773603d0d6aabbdd62a11ef721d1542d8'` when the data stored in your database is still `"john", "password"`? How do you expect this to work? Of course you have to hash your stored passwords as well. That's the whole point: Not storing cleartext passwords in the database ... – derpirscher Jan 17 '22 at 14:05
  • The password column on my database is stored in plaintext currently. I am trying to convert the passwords to be hashed using SHA256. I am using SQL Server Management Studio and as far as I know there is no built in function you can use to do this in a simple query. Like I said, I cannot wrap my head around this whatsoever. I'd really prefer if you just explained it to me like I was a kid because that would probably be the easiest for me to understand - Apologies. My program itself has the basic CRUD functionality for creating & deleting users along with the option to reset a password. – LearningCoder44 Jan 17 '22 at 14:09
  • There is [`HASHBYTES`](https://docs.microsoft.com/en-us/previous-versions/sql/sql-server-2012/ms174415(v=sql.110)?redirectedfrom=MSDN). But again: **DO NOT** use SHA256 to hash passwords. Especially if they are not even salted. Read https://stackoverflow.com/questions/1054022/best-way-to-store-password-in-database and the resources linked there to find a more suitable algorithm. When you found an algorithm, read your table in c#, and execute a `UPDATE login SET password=@hashedpassword WHERE username=@username` statement for each row, where `@hashedpassword` contains the hash of your plaintext – derpirscher Jan 17 '22 at 14:28

0 Answers0