Thursday, 21 February 2013

Encrypt and Decrypt Connection String Section in Web.Config


Encrypt and Decrypt Connection String Section in Web.Config


Sometime during Development of a Project we may need the help of other Developer to review or Modify our codes. As Such We dont want to give the developer the confidential Specification of the Project.. So The first thing which come to our mind is how to protect the connection string from the other developer..

So Here  is a technique to achieve the same:

In the Web.Config file we found <connectionStrings> section that enable us to add ConnectionStrings


<connectionStrings>
  <add name="ConnectionString" connectionString="Provider=SQLNCLI10.1;Data 
Source=My-pc\sqlexpress;Integrated Security=SSPI;Initial Catalog=Northwind"
   providerName="System.Data.OleDb" />
 </connectionStrings>

Next is the Encryption and Decryption of the above Section..You can Use the following code snippet to get the desired result:

Note: Dont Forget to add System.Web.Configuration Namespace...


protected void Encryption(bool EncryptoValue)
    {
        Configuration config = WebConfigurationManager.OpenWebConfiguration("~");
        ConfigurationSection sec = config.GetSection("connectionStrings");
        if (EncryptoValue == true)
        {
            sec.SectionInformation.ProtectSection("DataProtectionConfigurationProvider");
        }
        else
        {
            sec.SectionInformation.UnprotectSection();
        }
        config.Save();
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        Encryption(true);
    }
    protected void Button2_Click(object sender, EventArgs e)
    {
        Encryption(false);
    }

No comments:

Post a comment

Thank You for Your Comments. We will get back to you soon.

back to top