S
S
Senture2018-04-28 14:27:02
C++ / C#
Senture, 2018-04-28 14:27:02

How to store hashed passwords in a database?

There is a C# code for hashing passwords:

// Генератор соли
 private int GenerateSaltForPassword()
    {
        RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
        byte[] saltBytes = new byte[4];
        rng.GetNonZeroBytes(saltBytes);
        return (((int)saltBytes[0]) << 24) + (((int)saltBytes[1]) << 16) + (((int)saltBytes[2]) << 8) + ((int)saltBytes[3]);
    }

// хеширование
    private byte[] ComputePasswordHash(string password, int salt)
    {
        byte[] saltBytes = new byte[4];
        saltBytes[0] = (byte)(salt >> 24);
        saltBytes[1] = (byte)(salt >> 16);
        saltBytes[2] = (byte)(salt >> 8);
        saltBytes[3] = (byte)(salt);

        byte[] passwordBytes = UTF8Encoding.UTF8.GetBytes(password);

        byte[] preHashed = new byte[saltBytes.Length + passwordBytes.Length];
        System.Buffer.BlockCopy(passwordBytes, 0, preHashed, 0, passwordBytes.Length);
        System.Buffer.BlockCopy(saltBytes, 0, preHashed, passwordBytes.Length, saltBytes.Length);

        SHA1 sha1 = SHA1.Create();
        return sha1.ComputeHash(preHashed);
    }

// проверка хешированного пароля и введенного для авторизации
    private bool IsPasswordValid(string passwordToValidate, int salt, byte[] correctPasswordHash)
    {
        byte[] hashedPassword = ComputePasswordHash(passwordToValidate, salt);

        return hashedPassword.SequenceEqual(correctPasswordHash);
    }

And the question is to check if the passwords match, you need to know the salt of the hashed password, how to store the password in the database? Like this: password field, salt field? I thought that it is possible to store the password and salt in one field, but how then to get the salt during authorization? PS Sorry for the possibly stupid question.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
P
Pavel Karinin, 2018-04-28
@Senture

The password should not be stored anywhere either on the server or in the database, and in the simplest case, you should only store the Salt and the Hash sum of the password.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question