如何在C#连接字符串中隐藏密码?

时间:2011-09-28 10:28:45

标签: c# dbconnection

我有以下连接字符串:

Data Source=Paul-HP\MYDB;Initial Catalog=MyMSDBSQL;Persist Security Info=True;User ID=sa;Password=password

(.net webservice) 显然,只需打开app.config文件并查看配置设置即可查看。

我需要的是一种让黑客无法看到密码的方法。但同时,保持可自定义,以便在部署到另一个数据库时可以更改它。

5 个答案:

答案 0 :(得分:13)

你有很多选择 - 我所知道的(按照优先顺序):

  1. 使用集成(SSPI)安全性,您无需在配置文件中包含密码
  2. 加密连接字符串(请参阅Encrypting Configuration Information Using Protected Configuration
  3. 分别存储用户名和密码,并使用字符串格式构建完整的连接字符串
  4. 例如,连接字符串可能如下所示:

    Data Source=Paul-HP\MYDB;Initial Catalog=MyMSDBSQL;Persist Security Info=True;User ID={0};Password={1}
    

    我会选择选项1,如果那不可能那么选项2.我已经提到了选项3的完整性。

    您是否阅读过Protecting Connection Information (ADO.NET)

答案 1 :(得分:6)

首先,不要使用“SA”帐户。如果有人获得密码,它会使您的数据库全开。使用仅允许在特定数据库上执行CRUD操作的自定义帐户。

获取web.config的唯一方法是破解您的服务器。如果他们这样做了,你还是被搞砸了。

答案 2 :(得分:3)

可能最容易加密web.config或app.config中的连接字符串

请参阅How To: Encrypt Configuration Sections in ASP.NET 2.0 Using DPAPI

答案 3 :(得分:1)

您可以加密连接字符串 - 然后在访问连接字符串时解密它。这不是万无一失的,因为你会遇到存储密钥来解密连接字符串的问题!

答案 4 :(得分:1)

我建议/解密连接字符串。因此,必须手动设置连接字符串。

对于加密,请看一下: http://dotnet-snippets.de/dns/encrypt-and-decrypt-strings-SID205.aspx

对于自定义设置,请查看: http://msdn.microsoft.com/en-us/library/8eyb2ct1.aspx

在运行时将Encrypted替换为正确的:

  public static void SetAppSettingValue(string Key, string Value)
   {

   System.Configuration.Configuration config == ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
// Add an Application Setting.

 config.AppSettings.Settings[Key].Value = Value;

  // Save the changes in App.config file.

   config.Save(ConfigurationSaveMode.Modified);

    ConfigurationManager.RefreshSection("appSettings");
  }