密碼雜湊
密碼永遠不應儲存為純文字! 應使用慢速密碼雜湊演算法對隨機生成的鹽進行雜湊(以抵禦彩虹表攻擊)。可以使用大量迭代(> 10k)來減緩暴力攻擊。登入的使用者可以接受~100ms 的延遲,但是難以破解長密碼。選擇多次迭代時,應使用應用程式的最大容許值,並隨著計算機效能的提高而增加。你還需要考慮停止可能用作 DoS 攻擊的重複請求。
當第一次雜湊時,可以為你生成 salt,然後可以將生成的雜湊和 salt 儲存到檔案中。
private void firstHash(string userName, string userPassword, int numberOfItterations)
{
Rfc2898DeriveBytes PBKDF2 = new Rfc2898DeriveBytes(userPassword, 8, numberOfItterations); //Hash the password with a 8 byte salt
byte[] hashedPassword = PBKDF2.GetBytes(20); //Returns a 20 byte hash
byte[] salt = PBKDF2.Salt;
writeHashToFile(userName, hashedPassword, salt, numberOfItterations); //Store the hashed password with the salt and number of itterations to check against future password entries
}
檢查現有使用者密碼,從檔案中讀取其雜湊值和 salt,並與輸入密碼的雜湊值進行比較
private bool checkPassword(string userName, string userPassword, int numberOfItterations)
{
byte[] usersHash = getUserHashFromFile(userName);
byte[] userSalt = getUserSaltFromFile(userName);
Rfc2898DeriveBytes PBKDF2 = new Rfc2898DeriveBytes(userPassword, userSalt, numberOfItterations); //Hash the password with the users salt
byte[] hashedPassword = PBKDF2.GetBytes(20); //Returns a 20 byte hash
bool passwordsMach = comparePasswords(usersHash, hashedPassword); //Compares byte arrays
return passwordsMach;
}