Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sanity Check: Salt and hashed passwords

I had an idea about hashed passwords and salt values. Since I'm rather new to hashing and encryption, I thought I'd post this to you. Would it be more secure to generate a unique salt for each user account, then store the salt and hashed values in the database? Or, keep a single salt value securely stored and re-use that each time I hashed a password?

For example, A user would use the password:

"secret"

My code would generate a salt value of:

"d1d0e3d4b3d1ed1598a4e77bb614750a2a175e"

Then hash the result to get:

"e8187dcbe8e2eabd4675f3a345fe21c98affb
 5544a9278461535cb67265b6fe09a11dbef572
 ce3a4a8f2275839927625cf0bc7bc46fc45d51
 12d7c0713bb4a3"

The hashed result and salt would then be stored in the database in the users profile when their account was created. Then, each time the user logged on, a new salt would be generated, the password and salt rehashed and stored in the database.

Any thoughts? Like I said, this is a sanity check on an idea I had.

like image 764
Andy Evans Avatar asked Jul 28 '10 15:07

Andy Evans


1 Answers

Storing a unique salt per user is a good idea in my opinion. Re-generating the salt/hash combination every time the user logs in is a bit pointless unless you've got CPU cycles to burn. I'd recommend using something like the Rfc2898DeriveBytes class to generate a secure salt/hash combo:

Simple example of generating a hash from a password:

string password = GetPasswordFromInput();

using (var deriveBytes = new Rfc2898DeriveBytes(password, 32))  // 32-byte salt
{
    byte[] salt = deriveBytes.Salt;
    byte[] hash = deriveBytes.GetBytes(32);  // 32-byte hash
    SaveToDatabase(salt, hash);
}

And the corresponding checking of a password:

string password = GetPasswordFromInput();
byte[] salt = GetSaltFromDatabase();
byte[] hash = GetHashFromDatabase();

using (var deriveBytes = new Rfc2898DeriveBytes(password, salt))
{
    if (deriveBytes.GetBytes(32).SequenceEqual(hash))
        Console.WriteLine("Password matches");
    else
        throw new Exception("Bad password");
}
like image 116
LukeH Avatar answered Oct 27 '22 22:10

LukeH