How can I hide my password in my C# Connection string?

后端 未结 5 1954
时光取名叫无心
时光取名叫无心 2020-12-03 11:11

I have the following connection string:

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


        
相关标签:
5条回答
  • 2020-12-03 11:37

    Probably easiest to encrypt the connection strings within the web.config or app.config

    See How To: Encrypt Configuration Sections in ASP.NET 2.0 Using DPAPI

    0 讨论(0)
  • 2020-12-03 11:40

    First of all, don't use the "SA" account. It leaves your database wide open if someone gets the password. Use a custom account which only is allowed to do CRUD operations on a specific database.

    The only way to get web.config is to hack your server. And if they have done that, you're screwed anyway.

    0 讨论(0)
  • 2020-12-03 11:42

    I Suggest en/decrypting the connection string. Therefore the connection string has to be set manually.

    For encryption take a look at: http://dotnet-snippets.de/dns/encrypt-and-decrypt-strings-SID205.aspx

    For Custom Settings take a look at: http://msdn.microsoft.com/en-us/library/8eyb2ct1.aspx

    Replace the Encrypted with the correct one at runtime:

      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");
      }
    
    0 讨论(0)
  • 2020-12-03 11:48

    You have a number of options - the ones that I am aware of (in order of preference):

    1. Use integrated (SSPI) security where you don't need to include a password in the config file
    2. Encrypt the connection string (see Encrypting Configuration Information Using Protected Configuration)
    3. Store the username and password separately and use string formatting to construct the full connection string,

    So for example the connection string might look like this:

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

    I'd go for option 1, if thats not possible then option 2. I've mentioned option 3 for completeness.

    Have you read Protecting Connection Information (ADO.NET)?

    0 讨论(0)
  • 2020-12-03 11:59

    You could encrypt the connection string - then when you access the connection string, decrypt it. This isn't fool proof though as you're then stuck with the problem of where to store the key to decrypt the connection string!

    0 讨论(0)
提交回复
热议问题