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

17

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;
}
mmx
  • 402,675
  • 87
  • 836
  • 780
  • How do I extend byte so it can use this? – JonasB Jun 12 '09 at 10:26
  • @JonasB: Can you elaborate on that? Why do you want to extend anything? Since you're on .NET 3.5, just use the SequenceEquals line instead of `result = hashedPassword.Equals(hash);`. Unless you have other problems too, this should solve the issue. – mmx Jun 12 '09 at 10:31
  • @Mehrdad: I have double checked the .NET FW version. Checking the intellisense shows no SequenceEquals and I get a compiler error saying it does not exist in the System.Array. – JonasB Jun 12 '09 at 10:42
  • @JonasB: Do you have `using System.Linq` on top of your source file? – mmx Jun 12 '09 at 10:42
  • @Mehrdad: Yes, does not compile – JonasB Jun 12 '09 at 10:50
  • @JonasB: My fault. It's `SequenceEqual` not `SequenceEquals`. – mmx Jun 12 '09 at 11:03
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
  • 48,513
  • 13
  • 117
  • 151
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