13

This might actually be more of a conceptual question. In Asp.Net Identity the PasswordHasher generates a different hash for the same string every time you do:

new PasswordHasher.HashPassword("myString");

Now if for some reason I need to manually compare a user's input to the password saved in the database, I will most probably get a different string when I hash the user's entered password, than the one that is stored in the database.

Can someone please explain this to me? Shouldn't hashing the same string result in the same hash and if not, how does Identity itself realize that two different hashes are in fact the same?

Behrooz
  • 1,895
  • 4
  • 31
  • 47

2 Answers2

23

PasswordHasher generates different hashes each time because it uses salting technique. This technique secure the hashed password against dictionary attacks. By the way you could use following code to manually verify the password:

if(PasswordHasher.VerifyHashedPassword("hashedPassword", "password") 
    != PasswordVerificationResult.Failed)
{
    // password is correct 
}
Sam FarajpourGhamari
  • 14,601
  • 4
  • 52
  • 56
  • Where is the salt passed into the method? in order for the password to be "hashed" properly it must use the same salt that was used to hash the original password. – webworm Jan 31 '17 at 18:50
  • 1
    @webworm salt included in `hashedPassword`. So by passing `hashedPassword` the salt also passed to method as well. – Sam FarajpourGhamari Jan 31 '17 at 19:45
6
var user = _userManager.Users.SingleOrDefault(p => p.PhoneNumber == model.PhoneNumber);
            if (user == null)
            {
                return RedirectToAction(nameof(Login));
            }

            var result1 = _userManager.PasswordHasher.VerifyHashedPassword(user, user.PasswordHash, model.Password);
            if (result1 != PasswordVerificationResult.Success)
            {
                ModelState.AddModelError(string.Empty, "Invalid login attempt.");
                return View(model);
            }
Mojtaba Karimi
  • 426
  • 7
  • 10