1

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

1
  • is this totally necessary? IIS will not serve your Web.config so no one can read it unless they compromise your server. If you're still worried about it, you could use some RijndaelManaged to encrypt the string in your config and then build a class to decrypt it before LINQ touches it. msdn.microsoft.com/en-us/library/… Commented May 31, 2010 at 4:49

2 Answers 2

3

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(); 
    } 
} 
Sign up to request clarification or add additional context in comments.

2 Comments

or use the built-in aspnet_regiis utility to encrypt/decrypt .NET config file sections....
encryption using DPAPI uses local machineKey which is specific to local machine. When you deploy your app on server you might not have access to aspnet_regiis tool on server, or you might need to provide machineKey section in your web.config/app.config. So I'd recommend you do it by code.
1

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:

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.