G
G
graf452312020-02-15 16:11:46
MySQL
graf45231, 2020-02-15 16:11:46

How to store password hash in MySQL DB?

Hello, I need to save account passwords in the database, I read about it and realized that it is necessary to store in the database not the passwords themselves, but the keys. Tried to implement something, here is the code:

public static void SetPassword(string userName, string userPassword)
        {
            string sql = "";
            byte[] salt = new byte[20], key = new byte[20];
            using (var deriveBytes = new Rfc2898DeriveBytes(userPassword, 20))
            {
                salt = deriveBytes.Salt;
                key = deriveBytes.GetBytes(20);
 
                sql = $"UPDATE `accounts` SET `password_key`= '?key', `password_salt`= '?salt' WHERE `username` = '{userName}'";
            }
            using (var cmd = new MySqlCommand(sql, conn))
            {
                cmd.Parameters.Add(new MySqlParameter("?key", key));
                cmd.Parameters.Add(new MySqlParameter("?salt", salt));
                cmd.ExecuteNonQuery();
            }
        }]

But for some reason, not a 20-byte key is stored in the database, but 4. What could be the problem?
And before the line cmd.ExecuteNonQuery(); I check the size of salt and key, the size is 20 bytes. But 4 and 5 bytes are stored in the database.
I tried to change the signs ? on @, still the problem remains.

5e47edf9bc26b316537697.png

Answer the question

In order to leave comments, you need to log in

2 answer(s)
T
twobomb, 2020-02-15
@graf45231

In general, everything is clear, you write there the value ?key equal to 4 bytes (one byte per character) and ?salt equal to 5 bytes. Change your SQL to

sql = @"UPDATE `accounts` SET `password_key`= ?key, `password_salt`= ?salt WHERE `username` = '{userName}'";

Removed quotes

B
byreoil, 2020-02-15
@byreoil

What type of data in the database are these fields?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question