Click here to Skip to main content
6,822,613 members and growing! (15,799 online)
Email Password   helpLost your password?
Web Development » ASP.NET » Howto     Intermediate License: The Code Project Open License (CPOL)

Encrypt and Decrypt Configuration Sections in ASP.NET 2.0

By Muthupandiammal

Encrypting connection strings in the Web.config file in ASP.NET.
XML, C#2.0.NET2.0, ASP.NET, Dev
Revision:3 (See All)
Posted:25 May 2009
Views:3,909
Bookmarked:15 times
printPrint   add Share
      Discuss Discuss   Broken Article?Report  
2 votes for this article.
Popularity: 1.02 Rating: 3.40 out of 5

1

2
1 vote, 50.0%
3

4
1 vote, 50.0%
5

Introduction

The ASP.NET Configuration API provides support for encrypting and decrypting configuration sections in web.config. This feature comes extremely handy when you need to hide sensitive information like passwords. In this article, we will explore how to encrypt and decrypt sections of the web.config.

We can encrypt configuration sections by using two built-in providers: the DPAPI (Windows Data Protection API) Provider or the RSA provider. The RSA provider (default) uses an RSA key which holds public and private keys, where as the DPAPI provider uses a built-in machine-specific key. Let us explore the steps required to encrypt the sections using RSA.

Step 1

Open web.config and add the following sample entries in the file between the configuration tag. You can add a connection string:

string provider = "RSAProtectedConfigurationProvider";
string section = "connectionStrings";
protected void btnEncrypt_Click(object sender, EventArgs e)
{
    try
    {
        Configuration confg = 
          WebConfigurationManager.OpenWebConfiguration (Request.ApplicationPath);
        ConfigurationSection confStrSect = confg.GetSection(section);
        if (confStrSect != null)
        {
            confStrSect.SectionInformation.ProtectSection(provider);
            confg.Save();
        }
   
        Response.Write("Configuration Section " + "" +
            WebConfigurationManager.ConnectionStrings["MyConnString"].ConnectionString + 
            "" + " is automatically decrypted");
    }
    catch (Exception ex)
    {
    }
}

Step 2

After this, open the web.config file and we can see the encrypted data. In the code above, we open the web.config file as a System.Configuration.Configuration object using the specified virtual path. We then call GetSection() to retrieve the specified ConfigurationSection object, in our case connectionStrings. The ConfigurationSection.SectionInformation property gets us the SectionInformation object, and then we finally call the ProtectSection() method on the SectionInformation object to mark the section for protection.

<connectionstrings configprotectionprovider=""RsaProtectedConfigurationProvider"" />
 <encrypteddata xmlns=""http://www.w3.org/2001/04/xmlenc#"" 
       type=""http://www.w3.org/2001/04/xmlenc#Element"" />
   <encryptionmethod algorithm=""http://www.w3.org/2001/04/xmlenc#tripledes-cbc"" />
   <keyinfo xmlns=""http://www.w3.org/2000/09/xmldsig#"" />
    <encryptedkey xmlns=""http://www.w3.org/2001/04/xmlenc#"" />
     <encryptionmethod algorithm=""http://www.w3.org/2001/04/xmlenc#rsa-1_5"" />
     <keyinfo xmlns=""http://www.w3.org/2000/09/xmldsig#"" />
      <keyname />Rsa Key</keyname />
     </keyinfo />
     <cipherdata />
      <ciphervalue />ZehN7B+VXBdJTe1X3NFz9Uz3NqxvjSMmbytLeHGNlZa4
JkkpRkXzphm5sedHeMTk5KZCHxoYrJ4ssJ0OcZnzLxNUrAB9Ie3y8xJVWJ2s0RQ
dmaGk5bSJADE1xKJBuOtDIOi/Ron7qJDWXwllC3v
vmNwgabmJ9RU+RN35TOQpznc=</ciphervalue />
     </cipherdata />
    </encryptedkey />
   </keyinfo />
   <cipherdata />
    <ciphervalue />q2amqNwjeyEbMxF5pZ3XqfboNUJKSml773mPkISGi6uWCWCDPs
0ICClmH1eQYcsI9FlxFvEfyRyRRugqOU2xe+gd3aRZEZ5irpGFB45Fn6M+te7kg
OeTK1gjGEsbeaNjBNwgpcXMh9RiA9xVOvWlLAyJ3u8DsDQ+4JmM/zTUtxer/8Dl
UI7+u8D+9V4b5tWxShp4BToMFdTcefhMb19pGdn+jocGet
WBJirO5CJsLXI=</ciphervalue />
   </cipherdata />
 </encrypteddata />
</connectionstrings />

Decrypting web.config

Similarly, while decrypting the section, we call the UnprotectSection() method of the SectionInformation object.

protected void btnDecrypt_Click(object sender, EventArgs e)
{
    try
    {
        Configuration confg = 
         WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
        ConfigurationSection confStrSect = confg.GetSection(section);
        if (confStrSect != null && confStrSect.SectionInformation.IsProtected)
        {
            confStrSect.SectionInformation.UnprotectSection();
            confg.Save();
        }
    }
    catch (Exception ex)
    {
    }
}

Similar to connection strings, it is possible to encrypt any section in the web.config file.

Good luck .........

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Muthupandiammal


Member

Company: Acusis Software pvt ltd
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 2 of 2 (Total in Forum: 2) (Refresh)FirstPrevNext
Generalstandard way of doing things PinmemberDonsw17:29 9 Jul '09  
GeneralWhere's the source code? PinmemberDewey19:28 25 May '09  

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

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads.

PermaLink | Privacy | Terms of Use
Last Updated: 25 May 2009
Editor: Smitha Vijayan
Copyright 2009 by Muthupandiammal
Everything else Copyright © CodeProject, 1999-2010
Web21 | Advertise on the Code Project