hashing password giving different results
Posted
by geoff
on Stack Overflow
See other posts from Stack Overflow
or by geoff
Published on 2010-03-19T14:41:22Z
Indexed on
2010/03/19
15:11 UTC
Read the original article
Hit count: 213
hash
|hashalgorithm
I am taking over a system that a previous developer wrote. The system has an administrator approve a user account and when they do that the system uses the following method to hash a password and save it to the database. It sends the unhashed password to the user. When the user logs in the system uses the exact same method to hash what the user enters and compares it to the database value. We've run into a couple of times when the database entry doesn't match the user's entry whey they should. So it appears that the method isn't always hashing the value the same. Does anyone know if this method of hashing isn't reliable and how to make it reliable? Thanks.
private string HashPassword(string password)
{
string hashedPassword = string.Empty;
// Convert plain text into a byte array.
byte[] plainTextBytes = Encoding.UTF8.GetBytes(password);
// Allocate array, which will hold plain text and salt.
byte[] plainTextWithSaltBytes =
new byte[plainTextBytes.Length + SALT.Length];
// Copy plain text bytes into resulting array.
for(int i = 0; i < plainTextBytes.Length; i++)
plainTextWithSaltBytes[i] = plainTextBytes[i];
// Append salt bytes to the resulting array.
for(int i = 0; i < SALT.Length; i++)
plainTextWithSaltBytes[plainTextBytes.Length + i] = SALT[i];
// Because we support multiple hashing algorithms, we must define
// hash object as a common (abstract) base class. We will specify the
// actual hashing algorithm class later during object creation.
HashAlgorithm hash = new SHA256Managed();
// Compute hash value of our plain text with appended salt.
byte[] hashBytes = hash.ComputeHash(plainTextWithSaltBytes);
// Create array which will hold hash and original salt bytes.
byte[] hashWithSaltBytes = new byte[hashBytes.Length +
SALT.Length];
// Copy hash bytes into resulting array.
for(int i = 0; i < hashBytes.Length; i++)
hashWithSaltBytes[i] = hashBytes[i];
// Append salt bytes to the result.
for(int i = 0; i < SALT.Length; i++)
hashWithSaltBytes[hashBytes.Length + i] = SALT[i];
// Convert result into a base64-encoded string.
hashedPassword = Convert.ToBase64String(hashWithSaltBytes);
return hashedPassword;
}
© Stack Overflow or respective owner