2011-06-26 85 views
3

我有一些時間現在重新研究如何使用salt將密碼編碼到SHA1。SHA1與windows手機上的鹽7

這是我在我的web應用程序部分使用的代碼,但它不適用於電話環境。

public class Password 
{ 
    private string _password; 
    private int _salt; 

    public Password(string strPassword, int nSalt) 
    { 
     _password = strPassword; 
     _salt = nSalt; 
    } 

    public string ComputeSaltedHash() 
    { 
     // Create Byte array of password string 
     ASCIIEncoding encoder = new ASCIIEncoding(); 
     Byte[] _secretBytes = encoder.GetBytes(_password); 

     // Create a new salt 
     Byte[] _saltBytes = new Byte[4]; 
     _saltBytes[0] = (byte)(_salt >> 24); 
     _saltBytes[1] = (byte)(_salt >> 16); 
     _saltBytes[2] = (byte)(_salt >> 8); 
     _saltBytes[3] = (byte)(_salt); 

     // append the two arrays 
     Byte[] toHash = new Byte[_secretBytes.Length + _saltBytes.Length]; 
     Array.Copy(_secretBytes, 0, toHash, 0, _secretBytes.Length); 
     Array.Copy(_saltBytes, 0, toHash, _secretBytes.Length, _saltBytes.Length); 

     SHA1 sha1 = SHA1.Create(); 
     Byte[] computedHash = sha1.ComputeHash(toHash); 

     return encoder.GetString(computedHash); 
    } 

    public static int CreateRandomSalt() 
    { 
     Byte[] _saltBytes = new Byte[4]; 
     RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider(); 
     rng.GetBytes(_saltBytes); 

     return ((((int)_saltBytes[0]) << 24) + (((int)_saltBytes[1]) << 16) + 
      (((int)_saltBytes[2]) << 8) + ((int)_saltBytes[3])); 
    } 

    public static string CreateRandomPassword(int PasswordLength) 
    { 
     String _allowedChars = "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ23456789!\"#¤%&/()=?$+-_.,;'*"; 
     Byte[] randomBytes = new Byte[PasswordLength]; 
     RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider(); 
     rng.GetBytes(randomBytes); 
     char[] chars = new char[PasswordLength]; 
     int allowedCharCount = _allowedChars.Length; 

     for (int i = 0; i < PasswordLength; i++) 
     { 
      chars[i] = _allowedChars[(int)randomBytes[i] % allowedCharCount]; 
     } 

     return new string(chars); 
    } 
} 

回答

3

Silverlight和Windows Phone 7沒有ASCIIEncoding。我建議你改用UTF8Encoding。如果您確定您的密碼始終在ASCII範圍內,那麼此編碼的工作原理與ASCIIEncoding的工作原理相同。

如果在另一方面,你不能保證密碼總是ASCII範圍內,那麼你就需要確保雙方使用UTF8Encoding,以確保產生hashs是相同的哈希結束。

+0

SHA1仍然存在問題sha1 = SHA1.Create();並返回encoder.GetString(computedHash); – Androme

+0

@DoomStone:您可以使用'new SHA1()'創建'SHA1'類的實例,而對於字符串表示散列我傾向於在字節數組上使用'Convert.ToBase64String'而不是嘗試假設無論如何都是字節集表示字符串中文本字符的一些編碼。 – AnthonyWJones

+1

無法創建抽象類或接口的實例'System.Security.Cryptography.SHA1' – Androme