views:

78

answers:

4

Hey,

I have a couple different bits of code but the short story is I insert some passwords into a MySQL database using SHA1 and also compute SHA1 hashes into .NET and they are not matching. I think this is a problem with my encoding code in .NET.

SQL Code:

INSERT INTO user_credentials (Password) VALUES (SHA1('password'));

password hashes to 5baa61e4c9b93f3f0682250b6cf8331b7ee68fd8

.NET Code:

public static string GetPasswordHash(string password)
{
    // problem here with encoding?
    byte[] byteArray = Encoding.ASCII.GetBytes(password);

    SHA1 sha = new SHA1CryptoServiceProvider();
    byte[] hashedPasswordBytes = sha.ComputeHash(byteArray);

    return Encoding.ASCII.GetString(hashedPasswordBytes);
}

password hashes to [?a??????%l?3~???

Thanks for any help!

+7  A: 

In the MySQL example you are encoding to a hexadecimal string, in the .NET example you are encoding in ASCII. The two encodings are not the same.

If you convert to hexadecimal in the .NET version you get the correct result:

string hex = BitConverter.ToString(hashedPasswordBytes);

Result:

5B-AA-61-E4-C9-B9-3F-3F-06-82-25-0B-6C-F8-33-1B-7E-E6-8F-D8
Mark Byers
perfect. needed to convert to lower and remove the -'s.
nextgenneo
+3  A: 

You need to put [?a??????%l?3~??? in HEX representation. What you are printing is probably in binary form (hence the multiple ? chars).

Try doing this:

string hexstring = BitConverter.ToString(hashedPasswordBytes);

And see if hexstring and MySQL hash match.

Pablo Santa Cruz
A: 

How is your MySQL table/database encoded? Try setting both to UTF-8 (therefore using Encoding.UTF8.GetBytes)

Andrew Sledge
A: 

The SHA1 hashes should be equal, but the representation is not. MySql outputs a hex-string, so you will need to do the same in .NET:

return String.Join(String.Empty, hashedPasswordBytes.Select(b => b.ToString("x2")))
driis
A couple of points - this works in .NET 4.0 but you will need to add a call to ToArray for .NET 3.5 or older. Also you can use `String.Concat(...)` instead of `String.Join(String.Empty, ...)`.
Mark Byers