Encrypt Connection Strings when using Linq To SQL

2019-07-27 02:09发布

问题:

What is the best practice for encrypting the connectionStrings section in the web.config file when using LINQ TO SQL?

回答1:

First of all, encrypting section in web.config/app.config is not specific to just Linq2Sql. .Net framework comes with special set of classes that lets you independantly encrypt/decrypt parts of web.config/app.config.

You can encrypt sections of your web.config using DPAPI provider. Nothing else need to change in your application. you still keep reading appsettings and conn. strings as usual. Use this code below to encrypt/decrypt parts of your config file.

//call: ProtectSection("connectionStrings","DataProtectionConfigurationProvider"); 
private void ProtectSection(string sectionName, string provider) 
{ 
    Configuration config = 
        WebConfigurationManager. 
            OpenWebConfiguration(Request.ApplicationPath); 

    ConfigurationSection section = config.GetSection(sectionName); 

    if (section != null && !section.SectionInformation.IsProtected) 
    { 
        section.SectionInformation.ProtectSection(provider); 
        config.Save(); 
    } 
} 

//call: UnProtectSection("connectionStrings"); 
private void UnProtectSection(string sectionName) 
{ 
    Configuration config = 
        WebConfigurationManager. 
            OpenWebConfiguration(Request.ApplicationPath); 

    ConfigurationSection section = config.GetSection(sectionName); 

    if (section != null && section.SectionInformation.IsProtected) 
    { 
        section.SectionInformation.UnprotectSection(); 
        config.Save(); 
    } 
} 


回答2:

If you feel the need to do so, you can just simply encrypt the <connectionStrings> section of your web.config file - it's a standard .NET procedure, all .NET code can deal with it - no problems:

  • Encrypting the connection string in your web.config

or Google or Bing for it - you'll get thousands of hits.....