Connection String Encryption in Web.config using C#


Almost all ASP.NET web sites connect database and one of the best practices in ASP.NET is to store your database connection string outside your source code typically in web configuration file (web.config). This gives you benefit of changing your database related information such as the server name, user id or password without any modification or compilation of your source code. To provide additional security of important connection string information you should always encrypt your connection string in web.config file.

ASP.NET 2.0 allow you to encrypt and decrypt your connection string in web.config. In the following tutorial, I will show you how you can encrypt and decrypt connection strings in C# using .NET Framework built in classes available in System.Configuration and System.Web.Configuration namespaces.

To test the following code you should have your connection string in web.config file as following code shows:

<configuration>
    <connectionStrings>
      <add name="MyConnectionString" 
         connectionString="Server=TestServer; Database=TestDB; UID=test; PWD=test" 
         providerName="System.Data.SqlClient" />
    </connectionStrings>
</configuration>

Here is the C# code to encrypt and decrypt connection string. Make sure you have reference of System.Configuration and System.Web.Configuration available to test this code.

Encryption

try 
{ 
    Configuration config = WebConfigurationManager.OpenWebConfiguration("~"); 
    ConfigurationSection section = config.GetSection("connectionStrings"); 
    if (!section.SectionInformation.IsProtected) 
    { 
        section.SectionInformation.ProtectSection("RSAProtectedConfigurationProvider"); 
        config.Save(); 
    } 
} 
catch (Exception ex) 
{ }

Decryption

try 
{ 
    Configuration config = WebConfigurationManager.OpenWebConfiguration("~"); 
    ConfigurationSection section = config.GetSection("connectionStrings"); 
    if (section.SectionInformation.IsProtected) 
    { 
        section.SectionInformation.UnprotectSection(); 
        config.Save(); 
    } 
} 
catch (Exception ex) 
{ }

 

 

About author


User avatar

Waqas Anwar

Founder of EzzyLearning.com, Senior Consultant, Microsoft .NET and Web Technologies

Comments 7

Add Comment