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);
}
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;
}
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 .
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?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.