为什么我的密码哈希函数使用相同的盐值会产生不同的哈希值?

我的数据库中存储的密码是这样加密的:

byte[] salt = NewSalt();
string hashedPassword = HashPassword("passwordInTheclear",salt);
// Add/update the admin-user with hashed password and salt.

哈希函数:

public static string HashPassword(string password,byte[] salt)
{
    // derive a 256-bit subkey (use HMACSHA1 with 10,000 iterations)
    return Convert.ToBase64String(KeyDerivation.Pbkdf2(
        password: password,salt: salt,prf: KeyDerivationPrf.HMACSHA1,iterationCount: 10000,numBytesRequested: 256 / 8));
}

制盐机:

public static byte[] NewSalt()
{
    // generate a 128-bit salt using a secure PRNG
    byte[] salt = new byte[128 / 8];
    using (var rng = RandomNumberGenerator.Create())
    {
        rng.GetBytes(salt);
    }
    return salt;
}

当用户尝试登录系统时,我使用相同的哈希函数和相同的盐对登录表单中输入的密码进行哈希处理,并将其与存储在数据库中的哈希密码进行比较:>

// (I have separated out the password check from the linq query just for debugging purposes)
AdminUser au = await db.AdminUsers
    .Where(u =>
        u.Email1 == loginForm.username)
    .FirstOrDefaultAsync().ConfigureAwait(false);
byte[] salt = Encoding.ASCII.GetBytes(au.PasswordSalt);
string hashedEnteredPassword = HashPassword(loginForm.Password,salt);
if (au.Password == hashedEnteredPassword)
{
    // Success!
}

但是存储的密码和输入的密码不匹配。

示例:

In the database:
Unhashed password: 1234
Salt: Cda6ZgNVluChtzseyq9uMQ==
Hashed password: PKzE3rr9CGGmVW3UJS1N7mqrXmzni3hsqyCtP8lrehE=

In the login form:
Entered,unhashed password: 1234
Salt: Cda6ZgNVluChtzseyq9uMQ==
Hashed password: WwYUZqV1GfuRKEitpRdKDjTMEGWy+1nYzpkWI+eZPB0=
zhang374793162 回答:为什么我的密码哈希函数使用相同的盐值会产生不同的哈希值?

您正在以ASCII格式从数据库中获取盐,而示例中的盐显然是Base64。您只需将Encoding.ASCII.GetBytes(au.PasswordSalt)替换为Convert.FromBase64String(au.PasswordSalt)并命名为一天。

byte[] salt = Encoding.ASCII.GetBytes("Cda6ZgNVluChtzseyq9uMQ==");
string encryptedPassword = EncryptPassword("1234",salt);
Console.WriteLine(encryptedPassword);

会给您WwYUZqV1GfuRKEitpRdKDjTMEGWy+1nYzpkWI+eZPB0=,而

byte[] salt = Convert.FromBase64String("Cda6ZgNVluChtzseyq9uMQ==");
string encryptedPassword = EncryptPassword("1234",salt);
Console.WriteLine(encryptedPassword);

给予PKzE3rr9CGGmVW3UJS1N7mqrXmzni3hsqyCtP8lrehE=

本文链接:https://www.f2er.com/2833215.html

大家都在问