Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this a secure way to hash a password?

Tags:

c#

security

hash

Could you please tell me if the following is a good way to securely hash a password to be stored in a database:

    public string CreateStrongHash(string textToHash) {

        byte[] salt =System.Text.Encoding.ASCII.GetBytes("TeStSaLt");

        Rfc2898DeriveBytes k1 = new Rfc2898DeriveBytes(textToHash, salt, 1000);
        var encryptor = SHA512.Create();
        var hash = encryptor.ComputeHash(k1.GetBytes(16));

        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < hash.Length; i++) {
            sb.Append(hash[i].ToString("x2"));
        }

        return sb.ToString();

    }

Many Thanks in advance.

like image 360
ScubaSteve2012 Avatar asked Aug 31 '12 16:08

ScubaSteve2012


2 Answers

You use PBKDF2-SHA1, which is decent but not great. Bcrypt is a bit better, and scrypt is even stronger. But since .net already includes a built in PBKDF2 implementation, that's an acceptable choice.

Your biggest mistake is that you didn't get the point of a salt. A salt should be unique for each user. It's standard practice to simply create a random value of at least 64 bits. Store it together with the hash in the database.

If you want to, you can split the salt into two parts. One stored in the database alongside the user, which is different for each, and one shared part stored elsewhere. This gains the the advantages of both.

I also recommend using a higher workfactor than 1000. Figure out what performance is acceptable, and adjust accordingly. I wouldn't go below 10000, and in some situations(disk encryption) a million is acceptable too.

like image 167
CodesInChaos Avatar answered Oct 11 '22 01:10

CodesInChaos


It can be improved. First, you should use bcrypt instead. Traditional hashes like SHA-512 can be broken fairly easily with GPUs now-a-days. The problem is that these hashes are designed for speed, and this is the opposite of what you want in a password hash. Bcrypt is an example of an adaptive hash algorithm. It can be configured to take a "long" time (but still won't cause performance issues in your system) to make brute-forcing diffiult.

You also want to make the salts unique for each user.

For more information on how to securely hash passwords, see this question.

like image 34
Oleksi Avatar answered Oct 11 '22 01:10

Oleksi