Reputation: 21609
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:
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
Upvotes: 4
Views: 5327
Reputation: 35106
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.
Upvotes: 9
Reputation: 2215
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...
Upvotes: 2