Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP>NET Identity: How to compare a password entered by the user with a hashed password?

I've created a table called PasswordHistory. Each time a user changes the password, the current password is supposed to be copied to PasswordHistory table. The policy is the most restrictive of the following 2:

  1. User cannot use any of the last 8 passwords
  2. or a password that it has used in the last 2 years

I'd like to know how to compare a newly entered password with an existing one but that is hashed?

Here's my code:

var _limitDate = DateTime.Now.AddYears(-2);
int n = db.PasswordsHistory.Where(pwd => pwd.UserId == userId &&  pwd.ChangeDate > _limitDate).Count();

var pwdList = new List<PasswordHistory>();
if(n >= 8)
{
   pwdList = db.PasswordsHistory
       .Where(pwd => pwd.ChangeDate > _limitDate)
       .ToList();
}
else
{
   pwdList = db.PasswordsHistory
      .OrderByDescending(pwd => pwd.ChangeDate)
      .Take(8)
      .ToList();
}

if (pwdList.Count == 0)
{
   return false;
}
else
{
   foreach (var pwd in pwdList)
   {
      //compare the password entered by the user with the password stored in the PasswordHistory table
   }
}

Thanks for helping

like image 921
Richard77 Avatar asked Sep 06 '25 21:09

Richard77


2 Answers

Please store only password hashes in history. And you can compare old hashes with the provided password by PasswordHasher.VerifyHashedPassword(string hashedPassword, string providedPassword) - that is part of Identity.

like image 197
trailmax Avatar answered Sep 11 '25 03:09

trailmax


Same way you check it for correctness - hash it using the same algorithm (and salt if you use salted hashes) and compare the 2 hash results.

Do you know what algorithm was used to hash them originally?

Save your old passwords as hashes as well. Do your best to never have passwords as clear text anywhere...

like image 37
ivanivan Avatar answered Sep 11 '25 03:09

ivanivan