1

I'm using .net 3.5. The problem here is that I cant seem to get the passwords to match. I have tried using the ComputeHash method on both, but it generates a different hash. As they are now the arrays are different sizes. (Obviously they are based on the same string). What have I done wrong? ("password" is byte[] param by user input)

object dataPassword = database.ExecuteScalar("GetUserPassword", new object[] {userName});
if(dataPassword != null && !(dataPassword is DBNull))
{
    SHA1Managed hashProvider = new SHA1Managed();
    byte[] hashedPassword = (byte[])dataPassword;                    
    byte[] hash = hashProvider.ComputeHash(password);
    result = hashedPassword.Equals(hash);

}
JonasB
  • 270
  • 3
  • 11

3 Answers3

18

You can't compare a byte[] like that. It just compares references. You should use a loop or use IEnumerable<T>.SequenceEqual extension method:

result = hashedPassword.SequenceEqual(hash);

Old way (pre-LINQ):

static bool ArrayEquals<T>(T[] first, T[] second) {
    if (first == null && second == null) return true;
    if (first == null || second == null) return false;
    if (first.Length != second.Length) return false;
    for (int i = 0; i < first.Length; ++i)
       if (first[i] != second[i]) return false;
    return true;
}
Mehrdad Afshari
  • 414,610
  • 91
  • 852
  • 789
0

It might have something to do with encoding. Try using the UTF8Encoding class and encoding the string with the GetBytes method.

You can also have a look at a set of hashing classes I made for password verification at Google Code.

Blixt
  • 49,547
  • 13
  • 120
  • 153
0

Print the content of the input of the hash in both cases. I mean to print the byte[], not the strings. If they match, so should the hash. I know nothing about .net but maybe there's a different encoding for the strings, like one using ASCII and another UTF-8?

Ron
  • 840
  • 2
  • 8
  • 15