Encrypt or Decrypt the connection string in Web.Config


Connection string holds very sensible data like credentials of database. So, protecting the connectionstrings section in web.config is good to avoid unauthorized persons to access the database. You can do this using the following code.
using System.Configuration;
using System.Web.Configuration;
Encrypt the ConnectionStrings section


// Get the configuration file.
Configuration config = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
// Get the ConnectionStrings Section.
ConfigurationSection section = config.GetSection("connectionStrings");
//If the connectionStrings section is not in protected mode
 if (!section.SectionInformation.IsProtected)
 {
   section.SectionInformation.ProtectSection("RsaProtectedConfigurationProvider");
   config.Save();
   lblMsg.Text = "ConnectionString Successfully Encrypted.";

 }
 else
 {
   lblMsg.Text = "ConnectionString already in Encrypted Mode.";
  }

Decrypt the  ConnectionStrings section

// Get the configuration file.

Configuration config = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
// Get the ConnectionStrings Section.
ConfigurationSection section = config.GetSection("connectionStrings");
//If the connectionStrings section is already in protected mode
if (section.SectionInformation.IsProtected)
{
   section.SectionInformation.UnprotectSection();
   config.Save();
   lblMsg.Text = "ConnectionString Successfully Decrypted.";
 }
 else
 {
 lblMsg.Text = "ConnectionString already in Decrypted Mode.";
 }





Gopikrishna

    Blogger Comment
    Facebook Comment

0 comments:

Post a Comment