2016-10-20 78 views
0

我創建了一個名爲PasswordHistory的表。每次用戶更改密碼時,都應將當前密碼複製到PasswordHistory表中。該政策是限制最多的下列2:ASP> NET身份:如何將用戶輸入的密碼與哈希密碼進行比較?

  1. 用戶不能使用任何的最後8個密碼,
  2. 或者說,它已經在過去的2年使用的密碼

我會想知道如何比較新輸入的密碼和現有的密碼,但該密碼是散列的?

這裏是我的代碼:

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 
    } 
} 

感謝您的幫助

+1

PasswordsHistory表包含舊密碼哈希? – tmg

回答

3

請只存儲歷史中的密碼哈希。您可以通過PasswordHasher.VerifyHashedPassword(string hashedPassword, string providedPassword)比較舊哈希與提供的密碼 - 這是身份的一部分。

+0

謝謝你的作品完美 –

2

你檢查它的正確性同樣的​​方式 - 使用相同的算法散列它(和鹽,如果你使用鹽漬哈希)和比較2哈希結果。

你知道最初使用什麼算法來散列它們嗎?

將舊密碼另存爲哈希值。盡你最大努力,永遠不要在任何地方的明文密碼...

+0

+1表示無密碼明文存儲。 Identity具有應該在歷史密碼上使用的'PasswordHasher'類。 – trailmax

相關問題