2009-08-01 66 views
0

我有一個winform應用程序和一些web服務登錄列表。在檢查「記住我」我序列一本字典與加密密碼沿文件,但我不知道這是做這樣的事情還是不是最好的做法.. 這裏是我的代碼如何將登錄保存在winform應用程序中?

public void LoginsInit() 
{ 
    FileStream file = new FileStream(loginsFilePath, FileMode.OpenOrCreate); 
    try 
    { 
    BinaryFormatter formatter = new BinaryFormatter(); 
    loginsDictionary = (Dictionary<string, string>)formatter.Deserialize(file); 
    string[] allusers = loginsDictionary.Keys.ToArray(); 
    int usersCount = allusers.Length; 
    userNameTextBox.Text = allusers[usersCount - 1]; 
    } 
    catch (SerializationException ex) 
    { 
    loginsDictionary = new Dictionary<string, string>(); 
    Console.WriteLine("Failed to open file: " + ex.Message); 
    } 
    finally 
    { 
    file.Close(); 
    } 
} 

private void login_Click(object sender, EventArgs e) 
{ 
    //LoginToService(); 
    string username; 
    string password; 
    username = serviceClientReference.UserLogin = userNameTextBox.Text; 
    password = serviceClientReference.Password = EncryptDecrypt.Encrypt(this.passwordTextBox.Text, EncryptDecrypt.c_strEncryptkey1, EncryptDecrypt.c_strEncryptkey2); 

    if (rememberMe.Checked) 
    { 
    if (loginsDictionary.ContainsKey(username)) 
     loginsDictionary[username] = password; 
    else 
     loginsDictionary.Add(username, password); 
    } 
    FileStream file = new FileStream(loginsFilePath, FileMode.Create); 
    try 
    { 
    BinaryFormatter formatter = new BinaryFormatter(); 
    formatter.Serialize(file, loginsDictionary); 
    file.Flush(); 
    } 
    catch (SerializationException ex) 
    { 
    Console.WriteLine("Failed to open file: " + ex.Message); 
    } 
    finally 
    { 
    file.Close(); 
    } 

    string errorStr; 
    int errorNo; 
    try 
    { 
    bool res = serviceClientReference.EstablishConnection(out errorStr, out errorNo); 
    if (!res) 
    { 
     MessageBox.Show(errorStr); 
    } 
    } 
    catch (Exception exception) 
    { 
    Logger.Log(TraceLevel.Error, "", exception); 
    MessageBox.Show("Fatal Error Unable to login to MU"); 
    } 
} 

private void usernameTextBox_TextChanged(object sender, EventArgs e) 
{ 
    if (loginsDictionary.ContainsKey(userNameTextBox.Text)) 
    passwordTextBox.Text = EncryptDecrypt.Decrypt(loginsDictionary[userNameTextBox.Text], EncryptDecrypt.c_strEncryptkey1, EncryptDecrypt.c_strEncryptkey2); 
} 
+0

記住我的功能是否隨時間變化良好(應用程序關閉並重新打開)還是僅適用於當前的應用程序? – CertifiedCrazy 2009-08-01 10:27:57

回答

1

如果您嘗試跨應用程序實例保留用戶特定的設置,那麼您應該檢查內置於.NET中的Application Settings Architecture。這給你持久和重新加載能力(需要一些配置)。另外還有Isolated Storage用於提供額外的安全性和功能。無論你使用什麼繼續加密密碼。

3

你可能想要考慮使用DPAPI來管理您的密鑰。

0

管理敏感信息(如密碼)時,最好使用SecureString類 來存儲您的憑證。

相關問題