Edit and Encrypt Web.Config Sections Using C# 2.0


Application Security Testing: An Integral Part of DevOps


ASP.NET 1.x allowed configurations in web.config file to be read from a .NET application. But, there were no options to manipulate Web.Config contents programatically. To achieve this, you had to consider the Web.Config file as a normal file or an XML file. .NET 2.0 fills this gap and also provides many other useful operations to be carried out on a Web.Config file, such as editing and encrypting sections of the Web.Config file. This articles illustrates these functionalities via a sample ASP.NET application.

Using the Code

The classes and methods to take control of the Web.Config file span across two namespaces:

  • System.Configuration
  • System.Web.Configuration

Each section in the Web.Config file has a corresponding class in either of the namespaces. These classes allow modification of the corresponding sections. The classes for sections within the "system.web" section are found in System.Web.Configuration. Classes for other sections that are not specific to Web.Config are found in System.Configuration.

Modifying a section in Web.Config

  1. Open Web.Config for editing by using the WebConfigurationManager class.
  2. Use the respective Configuration class to make the necessary changes.
  3. Save the changes to the physical file by using the Configuration class.
private void UpdateConfig(string strKey, string strValue)
   Configuration objConfig =
   AppSettingsSection objAppsettings =
   if (objAppsettings != null)
      objAppsettings.Settings[strKey].Value = strValue;

In the above piece of code, the OpenWebConfiguration() method of the WebConfigurationManager class opens the Web.Config file in the root directory and returns it as a Configuration object. The GetSection() method of the Configuration class accepts the path to a specific section as an argument. The path is the relative path from the root node "configuration". You can refer to deeper nodes (sections, in this context) by their names separated by '/'. For example, to get access to the "authentication" section, provide "system.web/authentication" as the parameter to the GetSection() method. It returns a generic ConfigurationSecton object that can be typecast to the proper configuration section class. In this example, you get hold of the "appSettings" section with the help of the AppSettingsSection class. The AppSettingsSection class instance has a Settings collection property that contains the application setting from the configuration section as key-value pairs. The Settings property can be indexed using key to get the corresponding value. You also can set the value property and call the Save() method of the Configuration object to write configurations in the Configuration instance to the config file.

Deleting an entry in the Web.config file

The Remove() method of the Settings collection deletes an entry from the Configuration instance. The Remove() method accepts the key of the entry to be deleted.

Note: Please do not forget to call the Save() method of the Configuration instance to get the chnages reflected in the physical file.

To iterate through all the key-value pairs in a configuration section, access the string array of keys via the AllKeys property of the Settings collection.

foreach (string strKey in objAppsettings.Settings.AllKeys)
   DataRow dr  = dt.NewRow();
   dr["Key"]   = strKey;
   dr["Value"] = objConfig.AppSettings.Settings[strKey].Value;

Encrypting sections in Web.Config file

Now come the security issues. At times, the necessity for protecting sections the of config file arises. In .NET 2.0, there are options available to encrypt sections the of Web.config file programatically. The following method encrypts the "appSettings" section in the Web.config file.

private void EncryptAppSettings()
   Configuration objConfig = WebConfigurationManager.
   AppSettingsSection objAppsettings =
   if (!objAppsettings.SectionInformation.IsProtected)
      objAppsettings.SectionInformation.ForceSave = true;

The code above opens the Web.Config file for modification. It then retrieves the "appSettings" section. The ProtectSection() method of the SectionInformation class marks the configuration section for protection. It accepts the name of the protection provider to be used for the encryption. The ForceSave property indicates whether the specified configuration section will be saved even if it has not been modified. Finally, the Save() of the Configuration object writes the configuration settings to the Web.config file. The argument to the Save() method indicates the only properties modified needed to be written to the physical file.

Below is a listing of the "appSettings" section before encryption:

The encrypted "appSettings" section is listed below:

Decrypting sections of web.config file through code is practically identical. The UnprotectSection() method of the SectionInformation class removes the encryption from the configuration section.

private void DecryptAppSettings()
   Configuration objConfig = WebConfigurationManager.
   AppSettingsSection objAppsettings =
   if (objAppsettings.SectionInformation.IsProtected)
      objAppsettings.SectionInformation.ForceSave = true;

This encrytion and decryption functionality can be applied to other sections of web.config file also. It comes into use mostly for the "connectionStrings" section where the user name and password usually would be specified. This can done by creating a ConfigurationSection object. An example for the "connectionStrings" section is listed below.

ConfigurationSection objConfigSection = objConfig.ConnectionStrings;

The ConfigurationSection class represents a section within the configuration file. The Configuration class has propertes for each configuration section. This property can be used to get the respective ConfigurationSection objects. This is an alternative to the usage of the GetSection() method of the Configuration class.

About the Author

Mohammed Habeeb

Mohammed Habeeb works as a software developer for an IT company in Dubai. He holds a bachelors in Computer Science Engineering from MES College, Calicut University. He is also a Microsoft Certified Application Developer (MCAD) in .NET Framework. He has a strong inclination towards Microsoft technologies especially the .NET Platform. He has been an active member of Cochin and Bangalore Microsoft user groups. He has a strong passion for science and technology. His interests span through travelling, driving, photography, stamps and coin collection. You can find more about him @ http://www.habeebonline.com



  • BUT, IIS displayes the encrypted content!!!

    Posted by anwarsayeed on 07/05/2007 03:17am

    After encrypting, if you go to the website in IIS and properties, Edit configuration in ASP.NET section, will bring you all the encrypted values decrypted!!!!!! Any idea how to protect the data from displaying like this????

  • You must have javascript enabled in order to post comments.

Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • As all sorts of data becomes available for storage, analysis and retrieval - so called 'Big Data' - there are potentially huge benefits, but equally huge challenges...
  • The agile organization needs knowledge to act on, quickly and effectively. Though many organizations are clamouring for "Big Data", not nearly as many know what to do with it...
  • Cloud-based integration solutions can be confusing. Adding to the confusion are the multiple ways IT departments can deliver such integration...

Most Popular Programming Stories

More for Developers

RSS Feeds

Thanks for your registration, follow us on our social networks to keep up-to-date
We have made updates to our Privacy Policy to reflect the implementation of the General Data Protection Regulation.