How to encrypt passwords in Web.confg

In Windows Azure and especially with SQL Azure we need to store passwords to access things. I wanted to show how you can encrypt the web.config file by adding code to the global.asax file. The cool part of this is that using this technique you can secure application specific settings like connection strings and other data in the unlikely event that someone is able to get a copy of the configuration file (like by copying it to a thumb drive from the host machine or something similar).

The basic logic is to create a variable that points to a configuration section, then checking that the section is protected (i.e. encrypted). If it isn’t, then call the ProtectSection method to encrypt the contents. The server uses the local DPAPI (Data Protection API) to encrypt the configuration section with a machine specific key, so only that machine can decrypt the contents. The code to add to the global.asax.cs file in the Application Start event for this is:

public class Global : System.Web.HttpApplication

    protected void Session_Start(object sender, EventArgs

    private void EncryptSection(string sSection)

config = System.Web.Configuration 

        ConfigurationSection configSection =

        if (!configSection.SectionInformation.IsProtected)


Comments (3)

  1. Fred says:

    Do you have any good strategies for doing something like this in conjunction with web.config transformations ?

  2. Chuck says:

    Just a note, add the using System.Configuration;.

    Otherwise I've been wanting something like this, its perfect.

  3. hardwood flooring in toronto says:

    As your thinking,fully agree with your thoughts. Continue to write <a href=" ">hardwood flooring in toronto</a> and tell us a great job