CODe
CODe

Reputation: 2301

SHA1 Hash algorithm issues

I'm attempting to store a user's password in my program, but I don't want to store it in plain text. Therefore, I'm hashing it and storing that instead, and when the user needs to enter his password upon the program start (to protect against unauthorized users), I'm hashing the entered password and comparing the two hashes.

However, the following code is generating the same hash for almost any password entered. Can anyone either tell me how to fix the following code, or direct me to a better hash function?

public static string getSHA1(string userPassword)
{
    return BitConverter.ToString(SHA1Managed.Create().ComputeHash(Encoding.Default.GetBytes(userPassword))).Replace("-", "");
}

Thanks for any assistance.

Upvotes: 1

Views: 1957

Answers (2)

Jay
Jay

Reputation: 2141

Use somehting like this

    private static string GetSHA1(string text)
    {
        UnicodeEncoding UE = new UnicodeEncoding();
        byte[] hashValue;
        byte[] message = UE.GetBytes(text);

        SHA1Managed hashString = new SHA1Managed();
        string hex = "";

        hashValue = hashString.ComputeHash(message);
        foreach (byte x in hashValue)
        {
            hex += String.Format("{0:x2}", x);
        }
        return hex;
    }

Upvotes: 1

geofftnz
geofftnz

Reputation: 10102

I plugged your function into a new project and it seemed to be working OK, so check how the password is being supplied to the function. I'd be wary of using Encoding.Default instead of an explicit coding, as it says it's system-dependent.

Here's the one I made:

    public static string getSHA1(string userPassword)
    {
        return Convert.ToBase64String(new SHA1Managed().ComputeHash(Encoding.Unicode.GetBytes(userPassword)));
    }

Note: as pointed out in the comments, doing password storage/matching this way is bad:

  • you are using a fast hashing algorithm. You want password hashing to be slow to mitigate brute-force attacks. Bcrypt does a good job of this.
  • you are not salting your hash. Salting means adding some random data to the password prior to hashing, then storing the random data along with the hash. This makes rainbow tables (huge hash to password maps) useless.

Upvotes: 0

Related Questions