Click here to Skip to main content
Click here to Skip to main content

Programmatic Adding Custom Encrypted Configuration Section in ASP.NET

By , 11 Jul 2009
Rate this:
Please Sign up or sign in to vote.


First of all, I would like to describe my headline and then skip into the article's main target.

So every ASP.NET web developer has some knowledge about ASP.NET configuration concepts and the main question is why we must use configuration in the applications? Perhaps this is a technique for segregating between the application and the settings of the application. The answer is yes. ASP.NET provides a wide variety of tools for configuring the application. This is a simple and human readable file in XML format named web.config file.


Every web applications inherits the settings from the machine.config file and the root web.config file. I mean you can apply settings to single web applications or individual web applications. For example, you set some of the custom error pages, type of debugging, default language and more. But this is not just everything the web.config can do for us. You can make a custom application setting and bind a custom value to it and then use it in every place in your application.

It's important to understand that the web.config file in a web application is a secure place that no one can access because the applications most important information is stored in the web.config file. For example, application database connection string is one of the dangerous information that is placed in web.config file and if anyone can access it, perhaps she/he can access the application's backend and this is not desirable for a web developer.

Using the Code

Now let's break and back to the headline. Imagine you need to store some kind of custom information in your application configuration file. What is the best solution to do this? My answer is using some tools that ASP.NET provides for helping us in these type of solutions. However you can choose other types of storage such as custom XML files or something else.

ASP.NET provides the WebConfigurationManager class in the System.Web.Configuration namespace, which allows you to extract information from a configuration file at runtime. The WebConfigurationManager class is my starting point. It provides some members for managing the configuration settings, we use a useful method whose name is OpenWebConfiguration().

This method returns a configuration object that provides access to the configuration information for the specified web application. Now let's consider the following example:
In this example I loop over the connection string(s) of my application database(s) with WebConfigurationManager class and ConnectionStrings property:

protected void Page_Load(object sender, EventArgs e)
    foreach (ConnectionStringSettings connStr in 
        Response.Write("Name : " + connStr.Name + "<br/>");
        Response.Write("Connection String : " + 
           connStr.ConnectionString + "<br/><br/>");

Note that the ASP.NET applications have a built-in connection string that refers to the ASP.NET native database for using membership.

Now let's begin with the programmatic adding custom application configuration settings in unprotected state and then I explain how to protect it using data protection providers.

Writing Configuration Sections

Imagine I have custom settings in my application for a custom service provider. This service has a unique URI, serving status and the port number.
Now look at the following web.config body:

        <sectionGroup name="someSectionName">

        <section name="customServiceProvider" 
        type="CustomServiceProvider" />

    <customServiceProvider uri="someUri" status="someStatus" 
        port"somePort" />

As you see in this example, web.config file has two different parts of the declaration for a custom section. A section must present between <configsections> tags and then write your own section with custom attributes outside of the <configsections> tag.

Now let's go back to the code and write custom sections class and then use it. In the App_Code folder of the application, I define a class with the name of the section's type:

<section name="customServiceProvider&
    type="CustomServiceProvider" />

Now you must create a custom class for providing the custom section. Look at the following code of the CustomServiceProvider section class:

using System.Configuration;

public class CustomServiceProvider : ConfigurationSection
        IsRequired = true)]
    public string Uri
        get { return (string)base["uri"]; }
        set { base["uri"] = value; }

    IsRequired = true)]
    public string Status
        get { return (string)base["status"]; }
        set { base["status"] = value; }

        IsRequired = false,
        DefaultValue = 8081)]
    public int Port
        get { return (int)base["port"]; }
        set { base["port"] = value; }

As you see in this example, the custom section must extend the ConfigurationSection class and then write its own attributes of the section.

Now you can run the application and ASP.NET compiles the code behind and makes the custom section in the web.config file.
This is a custom section that is stored in the web.config file, and you can use it anywhere you need in your application. But this information is not encrypted and this is a clear text in the web.config file. However no one can access this file, but sometimes in some solutions you must prevent web.config file from providing a clear text mode of some configuration. In this case, we can protect the target configuration by using the ASP.NET protection providers.

Encrypting Configuration Sections

Now I have a web.config file with some application configurations and one custom section that is used in the application.

ASP.NET supports two encryption options, RSA and DPAPI (Data Protection API). Each of them has some attributes and using of any option has advantages and disadvantages. But with both of these options, encryption is completely transparent. When you retrieve a section from an encrypted section, ASP.NET automatically performs the decryption and returns the plain text to your code. Similarly, if you modify a value programmatically and save it, Encryption is performed automatically, however you won't be able to edit that section of the web.config file by hand.
To enable encryption programmatically, you need to retrieve the corresponding ConfigurationSection.SectionInformation object and then call the ProtectSection() method. Finally you must save your changes to the web.config file with Save method.

Configuration config = WebConfigurationManager.
if (config.HasFile)
    // load custom section to the object
    CustomServiceProvider csp =

    // now if you request for encrypt config section
    if (chkEncryptSection.Checked)
        if (!csp.SectionInformation.IsProtected)
        if (csp.SectionInformation.IsProtected)

Note that you must have permission to modify the web.config file in IIS. If you don't have write permission, ASP.NET throws an exception when you try to save your configuration changes to the web.config file.

Now you can open the web.config file and look at the section that you write by hand. When you call the ProtectSection method in your custom section, ASP.NET makes your custom section change automatically as you see in the following:


Encrypting the Connection String

Remember you can protect any section of your web.config file, and this is the example of the encrypting ConnectionString option in the application configuration file (web.config).
Look at the following example:

Configuration config = WebConfigurationManager.
if (config.HasFile)
    // load the connection string section 
    // to the object and then encrypt or decrypt it.
    ConfigurationSection connStr =
    if (chkEncryptConnStr.Checked)
        if (!connStr.SectionInformation.IsProtected)
        Response.Write("Protect ConnectionString.");
        if (connStr.SectionInformation.IsProtected)
        Response.Write("Unprotected ConnectionString.");

Remember you can use your connection string config anywhere you need.


  • 11th July, 2009: Initial post



About the Author

Software Developer Atra Inc
Iran (Islamic Republic Of) Iran (Islamic Republic Of)
Software developer and programming with .Net framework tech.
Managing Director of the Atra Inc in Tabriz/Iran that serves some Software Solution's.
Follow on   Twitter

Comments and Discussions

Generalbad format [modified] Pinmemberemilio_grv10-Jul-09 23:45 
GeneralRe: bad format Pinmembermoh-heidari11-Jul-09 2:54 
GeneralRe: bad format Pinmemberemilio_grv13-Jul-09 0:13 



| Advertise | Privacy | Mobile
Web02 | 2.8.140315.1 | Last Updated 11 Jul 2009
Article Copyright 2009 by mheidari
Everything else Copyright © CodeProject, 1999-2014
Terms of Use
Layout: fixed | fluid