如何在winform应用程序中保存登录?

时间:2009-08-01 10:06:50

标签: c# winforms web-services authentication

我有一个winform应用程序和一些Web服务的登录列表。检查'记住我'后,我将字典序列化为一个文件以及加密密码,但我想知道这是否是做这种事情的最佳做法。 这是我的代码

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);
}

3 个答案:

答案 0 :(得分:3)

您可能需要考虑使用DPAPI来管理密钥。

答案 1 :(得分:1)

如果您尝试跨应用程序实例保留特定于用户的设置,则应检查.NET内置的Application Settings Architecture。这为您提供了持久性和重新加载功能(需要一些配置)。还有Isolated Storage用于提供额外的安全性和功能。无论您使用什么继续加密密码。

答案 2 :(得分:0)

管理密码等敏感信息时,最好使用SecureString类 存储您的凭据。