Sunday, January 20, 2013

Encrypt Connection String in Web.config

There are two methods are available to provide security for the connection string in web.cofig.

1) RSAProtectedConfigurationProvider
2) DataProtectionConfigurationProvider

Include the namespace in class file
using System.Web.Configuration;
using System.Web.Security;
using System.Configuration;

 //If you want to use RSA Protection just replace "DataProtectionConfigurationProvider" to //"RSAProtectedConfigurationProvider"
       
        SqlConnection conStr = new SqlConnection(ConfigurationManager.ConnectionStrings["CMSConnectionString"].ConnectionString);

protected void btnEncrypt_Click(object sender, EventArgs e)
        {
            Configuration config = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
            ConfigurationSection section = config.GetSection("connectionStrings");
            if (!section.SectionInformation.IsProtected)
            {
                section.SectionInformation.ProtectSection("DataProtectionConfigurationProvider");
                config.Save();
            }
        }

        protected void btnDecrypt_Click(object sender, EventArgs e)
        {
            Configuration config = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
            ConfigurationSection section = config.GetSection("connectionStrings");
            if (section.SectionInformation.IsProtected)
            {
                section.SectionInformation.UnprotectSection();
                config.Save();
            }
        }
    }


No comments :

Post a Comment