Connection String Encryption in Web.config using C#

You are currently viewing 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) 
{ }
READ ALSO:  Export ASP.NET GridView to Excel

This Post Has 5 Comments

  1. khushbu

    how can we use this encrypted connection string in the page code ?

    1. Waqas Anwar

      You can read connection string like this

      string constr = ConfigurationManager.ConnectionStrings[“YourConStrName”].connectionString;

  2. Fahad Siddiqui

    please also include tutorial , how to encrypt & decrypt a xml document.

  3. Gentleman

    good……….

  4. Gentleman

    Very informative tutorial. sir please tell me how to do this for desktop applications’ configuration file.

Leave a Reply