August 28, 2012

Encrypt / Decrypt web.config ConnectionString

I am using RSA Protected Configuration Provider Model to encrypt and decrypt
<connectionstring> section
in web.config file.

Create a method in class library to encrypt decrypt on button click event.

protected void btnEncrypt_OnClick(object sender, EventArgs e)
{
    EncryptDecrypt(true);
}

protected void btnDecrypt_OnClick(object sender, EventArgs e)
{
    EncryptDecrypt(false);
}

protected void EncryptDecrypt(bool statusValue)
{
   var configuration = WebConfigurationManager.OpenWebConfiguration("~");
   var section = configuration.GetSection("connectionStrings");

   if (statusValue == true)
   {
      if (!section.SectionInformation.IsProtected)
      {
          section.SectionInformation.ProtectSection
                 ("DataProtectionConfigurationProvider");
      }
   }
   else
   {
      if (section.SectionInformation.IsProtected)
      {
         section.SectionInformation.UnprotectSection();
      }
   }

   config.Save();
}

No comments:

Post a Comment