我正在接管以前开发人员编写的系统。系统有管理员批准用户帐户,当他们这样做时,系统使用以下方法对密码进行哈希处理并将其保存到数据库中。它将未散列的密码发送给用户。当用户登录系统时,系统使用完全相同的方法对用户输入的内容进行哈希处理,并将其与数据库值进行比较。我们已经遇到过几次数据库条目与用户的条目不匹配的情况。因此,该方法似乎并不总是对相同的值进行哈希处理。有谁知道这种散列方法是否不可靠以及如何使其可靠?谢谢。
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;
}