Search code examples
c#hashpasswords

HashPassword returns a different value each time


I wrote this code in c#, asp.net core. to compare the password entered by the user with the password stored in the DB.

But in each run (on the same values) a function returns a different value:

private bool CompareHashPassword(UserLogin userLogin, User currentUser)
{
    IdentityUser identityUser = new IdentityUser() { UserName = userLogin.Username }; 
    PasswordHasher<IdentityUser> hasher = new PasswordHasher<IdentityUser>();
    string hashPassword = hasher.HashPassword(identityUser, userLogin.Password);
    PasswordVerificationResult comparePassword = hasher.VerifyHashedPassword(identityUser, currentUser.Password, hashPassword);

    return comparePassword == PasswordVerificationResult.Success;
}

I don't understand why.

Thank You!


Solution

  • From a read of the docs, you can see that VerifyHashedPassword takes the hashed password from your data base, but then an unhashed password to compare against rather than another hashed password

    This would make the code look something like this...

    private bool CompareHashPassword(UserLogin userLogin, User currentUser)
    {
        IdentityUser identityUser = new IdentityUser() { UserName = userLogin.Username }; 
        PasswordHasher<IdentityUser> hasher = new PasswordHasher<IdentityUser>();
    
        PasswordVerificationResult comparePassword = hasher.VerifyHashedPassword(identityUser, currentUser.Password, userLogin.Password);
    
        return comparePassword == PasswordVerificationResult.Success;
    }