How to encrypt the Web.Config

In the security session we did I showed in one of the sample 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 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 =



Happy Coding!

Comments (1)

  1. Kevin Daly says:

    Excellent! I’ve been doing it with a script, this is much better.

    One question: Shouldn’t it be encrypted in Application_Start rather than Session_Start?

    The latter seems to have two disadvantages stemming from its nature as a Session-scoped event –

    1) It gets called unnecessarily every time someone starts a new session, instead of just once

    2) Because it doesn’t get called until a user connects and a Session is initiated, there is a window of opportunity for a malicious party who manages to gain access to the config file (which they’d most likely do via direct access to the file system).

Skip to main content