Thursday, August 8, 2013

Encrypt or Decrypt Connection Strings in web.config.

Connection strings contain sensative informations like usernames and passwords.So as a good practice we should encrypt those connection strings.

First Methods -> Using "aspnet_regiis.exe" command line tool

1) Go to

Start ---> All Programs --> Microsoft visual studio 2008/2010 --> Visual Studio Tools --> 
Visual Studio 2008/2010 Command Prompt(Run as Administrator)

2)Type this command

To Encrypt

aspnet_regiis.exe -pef "connectionStrings" "C:\path_of_web_config_file"

To Decrypt

aspnet_regiis.exe -pdf "connectionStrings" "C:\path_of_web_config_file"

Second Method -> Using Coding

After asp.net 2.0, .net 2.0 provided a protected configuration method to encrypt or decrypt the Connection strings of a web.config file

use this namespaces in the header section of the page.

using System.Configuration;
using System.Web.Configuration;

Add a button to encrypt config file

Put this code inside the click event

Method 1 : RSAProtectedConfigurationProvider

   Configuration confg = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
            ConfigurationSection configSect = confg.GetSection(section);
            if (configSect != null)
            {
                configSect.SectionInformation.ProtectSection("RSAProtectedConfigurationProvider");
                confg.Save();
            }


Method 2: DataProtectionConfgurationProvider
     Configuration confg = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
            ConfigurationSection configSect = confg.GetSection(section);
            if (configSect != null)
            {
                configSect.SectionInformation.ProtectSection("DataProtectionConfgurationProvider");
                confg.Save();
            }



 Add a Decrypt button to decrypt a encrypted connection strings

Put this code inside the click event

Configuration config = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
   ConfigurationSection configSect = config.GetSection(section);
   if (configSect.SectionInformation.IsProtected)
   {
      configSect.SectionInformation.UnprotectSection();
      config.Save();
   }


No comments:

Post a Comment