Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Will a SHA1 Hash in C# always and forever return the same value for a given string?

Tags:

c#

hash

sha1

I am considering changing the method whereby we encrypt passwords to use a one-way hash rather than an encryption. I considered using a simple "GetHashCode" on the password string but MS warns that this function may change in the future and is different on 32 and 64-bit OSs. I don't want the result to ever be different as this would result in all the passwords in the database no longer matching when I have the entered value (e.g. when we all move to .NET 9.0 or something).

So, does a SHA1 Hash eliminate this problem? For example, if I use this C# code:

        var data = System.Text.Encoding.ASCII.GetBytes(value);
        data = System.Security.Cryptography.SHA1.Create().ComputeHash(data);
        return Convert.ToBase64String(data);

will the value always and forever be the same result? I am not too worried about a collision in a space this big but is there any other reason to consider a wider hash? Thanks in advance!

like image 385
Mark Brittingham Avatar asked Jul 23 '11 04:07

Mark Brittingham


2 Answers

Yes.

Unlike GetHashCode, SHA-1 is a fixed algorithm, just like MD5 and SHA-256, all of which have been "standardized".

like image 66
Peter O. Avatar answered Dec 02 '22 14:12

Peter O.


Yes. SHA1 is a standard, and the C# implementation must conform to the standard and produce the same results.

For your information, SHA1 is not a very good way to hash passwords, although it's certainly a big improvement over reversible encryption. SHA1, like MD5, is designed to hash a lot of data very fast, so it's very amenable to brute-force password cracking. The best hash functions for passwords are designed to be (relatively) slow or have adjustable speed and are hard to accelerate with hardware. One which is built into the .NET framework is PBKDF2, which essentially implements "stretched" SHA1 (applying SHA1 over and over to the same input so that it takes longer.) It's implemented in this framework class.

like image 44
mqp Avatar answered Dec 02 '22 15:12

mqp