Click here to Skip to main content
6,595,444 members and growing! (19,649 online)
Email Password   helpLost your password?
Web Development » ASP.NET » General     Intermediate

Edit and Encrypt Web.Config sections using C# 2.0

By Mohammed Habeeb

An article to illustrate editing and encrypting of sections of Web.Config file programatically.
C# 2.0, Windows, .NET 2.0, ASP.NET, WebForms, IIS 6, VS2005, Dev
Posted:3 May 2007
Views:35,356
Bookmarked:35 times
Unedited contribution
Announcements
Loading...
 
Search    
Advanced Search
Add to IE Search
printPrint   add Share
      Discuss Discuss   Broken Article?Report  
20 votes for this article.
Popularity: 4.73 Rating: 3.64 out of 5
1 vote, 5.0%
1

2
3 votes, 15.0%
3
7 votes, 35.0%
4
9 votes, 45.0%
5
Screenshot - WebConfigApp.jpg

Introduction

ASP.NET 1.x allowed configurations in Web.Config file to be read from .NET application. But there were no options to manipulate Web.Config contents in programatically. To achieve this we had to consider 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 Web.Config file; like editing and encrypting sections of 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 2 namespaces.

  1. System.Configuration
  2. System.Web.Configuration

Each section in the Web.Config file has a corresponding class in either of the namespace. These classes allow modification of 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.

Steps to modify a section in Web.Config

  1. Open Web.Config for editing using WebConfigurationManager class.
  2. Using respective Configuration class, bring about the necessary changes.
  3. Save changes to the physical file using Configuration class.
private void UpdateConfig(string strKey, string strValue)
{
    Configuration objConfig = WebConfigurationManager.OpenWebConfiguration("~");
    AppSettingsSection objAppsettings = (AppSettingsSection)objConfig.GetSection("appSettings");
    if (objAppsettings != null)
    {
        objAppsettings.Settings[strKey].Value = strValue;
        objConfig.Save();
    }
}

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

To delete an entry in the Web.config file: The Remove() method of Settings collection deletes an entry from the Configuration instance. Remove() method accepts key of the entry to be deleted.

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

objAppsettings.Settings.Remove("Location");
To iterate through all the key-value pairs in a configuration section, access the string array of keys via AllKeys property of Settings collection.
foreach (string strKey in objAppsettings.Settings.AllKeys)
{
    DataRow dr = dt.NewRow();
    dr["Key"] = strKey;
    dr["Value"] = objConfig.AppSettings.Settings[strKey].Value;
    dt.Rows.Add(dr);
}

Encrypting sections in Web.Config file

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

private void EncryptAppSettings()  
{
    Configuration objConfig = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
    AppSettingsSection objAppsettings = (AppSettingsSection)objConfig.GetSection("appSettings");
    if (!objAppsettings.SectionInformation.IsProtected)
    {
        objAppsettings.SectionInformation.ProtectSection("RsaProtectedConfigurationProvider");
        objAppsettings.SectionInformation.ForceSave = true;
        objConfig.Save(ConfigurationSaveMode.Modified);
    }
}

The code above opens Web.Config file for modification. It then retrieves the "appSettings" section. The ProtectSection() method of 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 if 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 need to be written to the physical file.

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

Screenshot - WebConfig.jpg

The encrypted "appSettings" section is listed below:

Screenshot - WebConfigEncrypted.jpg

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

private void DecryptAppSettings()
{
    Configuration objConfig = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
    AppSettingsSection objAppsettings = (AppSettingsSection)objConfig.GetSection("appSettings");
    if (objAppsettings.SectionInformation.IsProtected)
    {
        objAppsettings.SectionInformation.UnprotectSection();
        objAppsettings.SectionInformation.ForceSave = true;
        objConfig.Save(ConfigurationSaveMode.Modified);
    }
}
This encrytion and decryption functionality can be applied to other sections of web.config file also. It comes in use mostly for "connectionStrings" section where usually the user name and password would be specified. This can done by creating a ConfigurationSection object. An example for "connectionStrings" section is listed below.
ConfigurationSection objConfigSection = objConfig.ConnectionStrings;
ConfigurationSection class represents a section within the configuration file. Configuration class has propertes for each configuration section. This property can be used to get respective ConfigurationSection objects. This is an alternative to the usage of GetSection() method of Configuration class.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

Mohammed Habeeb


Member
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
Occupation: Web Developer
Location: India India

Other popular ASP.NET articles:

Article Top
You must Sign In to use this message board.
FAQ FAQ 
 
Noise Tolerance  Layout  Per page   
 Msgs 1 to 9 of 9 (Total in Forum: 9) (Refresh)FirstPrevNext
GeneralA unique article PinmemberSayed Sajid2:40 28 Jul '09  
GeneralEncrypt just 1 key PinmemberMillan_Mosh9:33 5 Nov '07  
GeneralProfile Pinmemberpaul_beckett23:34 4 May '07  
GeneralSecurity issue PinmemberStefan Prodan1:53 4 May '07  
GeneralRe: Security issue Pinmemberphase6415:14 17 May '07  
AnswerRe: Security issue PinmemberMohammed. Habeeb23:54 17 May '07  
GeneralRe: Security issue Pinmemberphase6417:19 19 May '07  
GeneralRe: Security issue PinmemberDummyDUmb13:41 18 Oct '07  
AnswerRe: Security issue PinmemberMohammed. Habeeb23:40 17 May '07  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 3 May 2007
Editor:
Copyright 2007 by Mohammed Habeeb
Everything else Copyright © CodeProject, 1999-2009
Web21 | Advertise on the Code Project