2008-11-23 24 views
3

爲了改進我的代碼,我正在尋找在.NET中創建和比較鹽漬密碼的最佳方法。在.NET中創建和比較鹽漬密碼的最簡單方法是什麼?

有沒有更好的或更安全的方法呢?

我當前的代碼如下:

public static string CreateSaltedPassword(string salt, string password) 
    { 
     SHA1CryptoServiceProvider SHA1 = null; 

     SHA1 = new SHA1CryptoServiceProvider(); 

     // Convert the string into an array of bytes 
     byte[] byteValue = System.Text.Encoding.UTF8.GetBytes(salt + password); 

     // Compute the hash value 
     byte[] byteHash = SHA1.ComputeHash(byteValue); 

     // Dispose the unmanaged cryptographic object 
     SHA1.Clear(); 

     return Convert.ToBase64String(byteHash); 
    } 

    public static bool ComparePasswords(string salt, string password, string storedPassword) 
    { 
     string passwordHash = string.Empty; 

     // Create the hashed password 
     passwordHash = PasswordProvider.CreateSaltedPassword(
      salt, password); 

     // Compare the passwords 
     return (string.Compare(storedPassword, passwordHash) == 0); 
    } 

回答

13

簡單地迭代散列函數是不夠的。你需要迭代,但是要保留密碼中存在的熵。 As suggested here,使用Rfc2898DeriveBytes更安全的方法。

您應該通過哈希執行幾千次迭代。做一些測試,看看你的目標機器需要多長時間:當你檢查他們的輸入時,10000次或更多的迭代不應該被用戶注意到,但是它會將攻擊者的時間要求從幾小時改變到幾年。

鹽源和大小沒有顯示;鹽不需要保密,只需要給定密碼的不可預知性。來自密碼RNG的8個字節是一種方便和安全的鹽。用戶名更方便,但可能不太安全。

PBKDF2爲今天的大多數應用程序提供了合理的安全性。安全的下一步將是加密或者恐怖。

你可能有興趣在我回答這些類似的問題:

+0

您應該在每次執行的迭代中添加一些信息,因爲僅重複哈希函數N次會稍微增加碰撞風險。請參閱http://en.wikipedia.org/wiki/Key_strengthening#Hash_based_key_stretching – ollb 2012-02-10 19:30:44

2

傑夫·阿特伍德code project article

這個類是大量記載, 串爲本,最重要的是, 簡單!它非常適合學習有關加密的更多 。

5

使用來自System.Security.CryptographyRfc2898DeriveBytes類。

它自2.0版以來內置到.NET框架中,它實現了PBKDF2-HMACSHA1,它提供了可靠的密碼salting和散列速度(這對於密碼散列而言至關重要)。

相關問題