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