Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validate a salted hash

I am new to C# and this is my first question here so I apologize in advance for any faux pas.

Context:

When a user registers I call the CreateSaltedHash() method and pass it the user inputted password from the text field. This method salts and hashes the password before storing it in the Password column of my User table.

Question:

How should I validate the password when a user tries to log in?

If I call the CreateSaltedHash() method again it will not match because of the random salt.

Should I be storing the salts in a separate column? Should I be using a delimiter when generating the salted hash? What is the most secure way of validating the input password against the salted and hashed password?

Code: This is what I have so far.

public class PasswordHash
{
    public const int SALT_BYTES = 32;

    /*
     * Method to create a salted hash
     */
    public static byte[] CreateSaltedHash(string password)
    {
        RNGCryptoServiceProvider randromNumberGenerator = new RNGCryptoServiceProvider();
        byte[] salt = new byte[SALT_BYTES];
        randromNumberGenerator.GetBytes(salt);
        HashAlgorithm hashAlgorithm = new SHA256Managed();
        byte[] passwordByteArray = Encoding.UTF8.GetBytes(password);
        byte[] passwordAndSalt = new byte[passwordByteArray.Length + SALT_BYTES];
        for (int i = 0; i < passwordByteArray.Length; i++)
        {
            passwordAndSalt[i] = passwordByteArray[i];
        }
        for (int i = 0; i < salt.Length; i++)
        {
            passwordAndSalt[passwordByteArray.Length + i] = salt[i];
        }
        return hashAlgorithm.ComputeHash(passwordAndSalt);
    }

    public static bool OkPassword(string password)
    {
        //This is where I want to validate the password before logging in.
    }
}


Calling the method in the Register class.

User user= new User();
user.password = PasswordHash.CreateSaltedHash(TextBoxUserPassword.Text);
like image 511
Naomi Owens Avatar asked Nov 15 '12 13:11

Naomi Owens


1 Answers

You could use Bcrypt.Net; it has a lot of recommendations for being really secure, plus it is very easy to use. As I understand it, when you create the password it automatically generates a unique salt for you, which is then stored in the hashed password string; so you do not store the salt separately, but in the same field as the hashed password. The point is each password has it own salt, which makes it much more difficult (time consuming) for a hacker to crack multiple passwords. The algorithm Bcrypt uses is also CPU intensive, so it requires a lot of computational power (=money) to crack.

Jeff Atwood (stackoverflow moderator) recommends Bcrypt.

like image 51
Polyfun Avatar answered Sep 21 '22 14:09

Polyfun