2012-05-16 131 views
0

我是新的C#wpf編程,但我試圖連接到MySQL數據庫並哈希我的密碼。不幸的是當我執行algorith我得到的錯誤在此代碼:哈希密碼算法問題

byte[] plainTextWithSaltBytes = new byte[plainTextBytes.Length + saltBytes.Length]; 
salt.CopyTo(plainTextWithSaltBytes, 0); 
plainText.CopyTo(plainTextWithSaltBytes, salt.Length); 

的錯誤是:

Error: no overload for method 'Copy To' takes 2 arguments Exceptions: System.ArgumentNullException System.ArgumentOutOfRangeException 
enter code here 

以任何機會,你知道是什麼原因造成這樣的錯誤,以及如何解決它?

+0

plainText的類型是什麼?我懷疑這是一個字符串。您不能將字符串複製到字節數組。 –

回答

2

你需要複製plainTextBytes,不plainText

byte[] plainTextWithSaltBytes = new byte[plainTextBytes.Length + saltBytes.Length]; 
    salt.CopyTo(plainTextWithSaltBytes, 0); 
    plainTextBytes.CopyTo(plainTextWithSaltBytes, salt.Length); 
+0

......也是'saltBytes'。 – BeemerGuy

+0

@Thomas Levesque你真的解決了我的問題,但現在當我運行我的WPF並嘗試插入數據時,我得到這一行上的錯誤: '使用(var cmd = new MySqlCommand(「Select salt from niki where user_name = @username」 )) { cmd.Parameters.AddWithValue(「@ username」,username); salt = cmd.ExecuteScalar()as string; }' 錯誤是連接必須是有效的並且打開。你有什麼線索可以解決問題嗎? –

+0

@NikolayDyankov,這是一個完全不相關的問題,我們不能在評論中輕鬆討論它。你應該開一個新的問題。 –

1

如果你需要做簡單的哈希,這段代碼可以加密密碼:

String GetEncryptedPassword (String prmUser, String prmPassword) 
{ 
    // Concatenating the password and user name. 
    String encryptedPassword = prmUserName + prmPassword; 

    // Converting into the stream of bytes. 
    Byte[] passInBytes = Encoding.UTF8.GetBytes(encryptedPassword); 

    // Encrypting using SHA1 encryption algorithm. 
    passInBytes = SHA1.Create().ComputeHash(passInBytes); 

    // Formatting every byte into %03d to make a fixed length 60 string. 
    return passInBytes.Aggregate(String.Empty, (pass, iter) => pass += String.Format("{0:000}", iter)); 
} 

此代碼會給你一個很好的60個字符的加密哈希。但請記住,您無法從哈希中重新生成原始用戶名和密碼,因爲這是單向算法。您可以使用System.Security.Cryptography中的幾種加密算法。