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

Encrypt or Decrypt Connection Strings in web.config file using asp.net.

By , 23 Dec 2011
 

Introduction

In this article I will explain how to encrypt or decrypt connection Strings in web.config file using asp.net.

Description

In Previous posts I explained lot of articles regarding Asp.net, Gridview, SQL Server, Ajax, JavaScript etc. In many of articles I used connection Strings section in web.config file to store database connection. The connection Strings section contains sensitive information of database connections including username and password of database. Is it secured to store the sensitive information of database connections in plain text files called web.config and machine.config files?
 
If we are using applications in our internal servers with security then it’s ok if we deploy our applications in shared host environment then we have chance to arise security problems to avoid these problems asp.net 2.0 provided built in protected configuration model functionality to encrypt or decrypt few sections of web.config file those are
 
RSAProtectedConfigurationProvider: This is default provider and uses the RSA public key encryption algorithm to encrypt and decrypt data.
 
DataProtectionConfgurationProvider: This provider uses windows data protection application programming interface to encrypt and decrypt the data.
 
The encrypting and decrypting of connection strings in web.config file will do by using aspnet_regiis.exe command line tool and code behind.

First Method

First we will do encryption and decryption using aspnet_regiis.exe command line tool in file system website
 
To implement encryption and decryption first create one new website using visual studio.
 
After that open web.config file in application and add sample db connection in connectionStringssection like this
<connectionStrings>
<add name="dbconnection" connectionString="Data Source=RahulMittal;Integrated Security=true;Initial Catalog=MySampleDB"/>
</connectionStrings >
After add dbconnection in connectionString check the below steps to encrypt or decrypt the connection string in web.config.
 
1. 1) Go to Start >> All Programs >> Microsoft visual studio 2008 >> Visual Studio Tools >> Visual Studio 2008 Command Prompt (Note: if you’re using windows 7 right click on command prompt and select Run as administrator)
 
2. 2) after open command prompt type the following command aspnet_regiis.exe -pef "connectionStrings" "C:\VisualStudio2008\Authorization"
 
Here –pef indicates that the application is built as File System website. Second argumentconnectionStrings indicates that name of the configuration section needs to be encrypted. The Third argument is the physical path of the folder where the web.config file is located.
 
3. 3) after enter the command click enters if everything goes well we will get success message like “Encrypting configuration section… Succeeded!”
 
Now open your application and check connectionStrings in web.config file that would be like this
<connectionStrings configProtectionProvider="RsaProtectedConfigurationProvider">
<EncryptedData Type="http://www.w3.org/2001/04/xmlenc#Element"
xmlns="http://www.w3.org/2001/04/xmlenc#">
<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>ZNUbIEnOwlZzC8qbzHj5F2GS9gLYSkWCIgCJGkrgZAX8A+8oEIssyohhxUKvAubD3jizFc5IjbLGt7HNXhoFhXNTUPYz2y6tdKJDVgDmtCgVf8Z2C990zoMRBJG+VXhmgnlo1vtHYhGx8x/bBzE1prT1+xDpep98vHF22d+LrVI=</CipherValue>
</CipherData>
</EncryptedKey>
</KeyInfo>
<CipherData>
<CipherValue>tODWlPD0Q/B/mP14GQ/5tUxcjmhHcy9a0oPunV5osNrMQRztgi2h5V6sxJOEh+NC+G9gQNkv1huXf1s7eoZRRLy5/LDtLXzzqMUOqLSlJUs9igChvi33c9XG4rwGF15Tpn4N34bpQBt94n0rpSkQ18V9HCPzii+UO64PlA+ykDeQhc9aQr4gO3mCfUzmY2S9gsXzRbzdq0oCWBDvx8UkX2uDxaysVHC9Fo7u6IrlpU0+hOdK95Y3/A==</CipherValue>
</CipherData>
</EncryptedData>
</connectionStrings>
Here we don’t want to write any code to decrypt the encrypted connectionString in our application because .NET automatically decrypts it. If we want to use the connection string just call it like normal way
string strconnection = ConfigurationManager.AppSettings["dbconnection"].ToString();
Now if we want to decrypt connectionStrings section in web.config use the following commandaspnet_regiis.exe -pdf "connectionStrings" "C:\VisualStudio2008\Authorization"
 
After command execute we will get message like “Decrypting configuration section… Succeeded!”

Now check your connctionStrings section in your web.config file you will see decrypted connection string.
 
Till now we learned how to encrypt and decrypt connectionStrings section in File system website. If I want to encrypt connection string in IIS based site like i.e. Deployed website for that we need to use the following commands
 
Encrypt connectionStrings in web.config of IIS based site
 
aspnet_regiis.exe -pe "connectionStrings" -app "/SampleWebSite"
Here –pe indicates that the application is built as IIS based site. Second argument connectionStrings is the name of configuration section needs to be encrypted. The Third argument -app indicates virtual directory and last argument is the name of virtual directory where application is deployed.
 
Decrypt connectionStrings in web.config of IIS based site
 
aspnet_regiis.exe -pd "connectionStrings" -app "/SampleWebSite"
Till now we learned how to encrypt and decrypt connectionStrings section in web.config file using aspnet_regiis.exe command line tool now I will explain code behind method to encrypt and decrypt the connection string section in web.config.
 
Second Method: In second method I will use RSAProtectedConfigurationProvider and DataProtectionConfgurationProvider to encrypt and decrypt connectionStrings in web.config using asp.net.
 
First open Default.aspx page and write the following code
<html xmlns="http://www.w3.org/1999/xhtml">
<head  runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1"  runat="server">
<div>
<asp:Button id="btnEncrypt" runat="server" Text="Encrypt" onclick="btnEncrypt_Click" />
<asp:Button ID="btnDecrypt" runat="server" Text="Decrypt" onclick="btnDecrypt_Click" />
</div>
</form>
</body>
</html>
After that open code behind page and add the following namespace references
using System;
using System.Configuration;
using System.Web.Configuration;
After add namespaces write the following code in code behind

C# code

string provider = "RSAProtectedConfigurationProvider";
string section = "connectionStrings";
protected void Page_Load(object sender, EventArgs e)
{
 
}
protected void btnEncrypt_Click(object sender, EventArgs e)
{
   Configuration confg = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
   ConfigurationSection configSect = confg.GetSection(section);
   if (configSect != null)
   {
      configSect.SectionInformation.ProtectSection(provider);
      confg.Save();
   }
}
 
protected void btnDecrypt_Click(object sender, EventArgs e)
{
   Configuration config = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
   ConfigurationSection configSect = config.GetSection(section);
   if (configSect.SectionInformation.IsProtected)
   {
      configSect.SectionInformation.UnprotectSection();
      config.Save();
   }
}

VB.NET

Imports System.Web.Configuration
Partial Class _Default
   Inherits System.Web.UI.Page
   Private provider As String = "RSAProtectedConfigurationProvider"
   Private section As String = "connectionStrings"
   Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
   End Sub
   Protected Sub btnEncrypt_Click(ByVal sender As Object, ByVal e As EventArgs)
      Dim confg As Configuration = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath)
      Dim confgSect As ConfigurationSection = confg.GetSection(section)
      If confgSect IsNot Nothing Then
         confgSect.SectionInformation.ProtectSection(provider)
         confg.Save()
      End If
   End Sub
   Protected Sub btnDecrypt_Click(ByVal sender As Object, ByVal e As EventArgs)
      Dim config As Configuration = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath)
      Dim confgSect As ConfigurationSection = config.GetSection(section)
      If confgSect.SectionInformation.IsProtected Then
         confgSect.SectionInformation.UnprotectSection()
         config.Save()
      End If
   End Sub
End Class
 
After that open web.config file in application and add sample db connection in connectionStrings section like this
<connectionStrings>
<add name="dbconnection" connectionString="Data Source=RahulMittal;Integrated Security=true;Initial Catalog=MySampleDB"/>
</connectionStrings >
Now run your application and check your web.config file after click on Encrypt button that would be like this
<connectionStrings configProtectionProvider="RsaProtectedConfigurationProvider">
<EncryptedData Type="http://www.w3.org/2001/04/xmlenc#Element"
xmlns="http://www.w3.org/2001/04/xmlenc#">
<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>WagJ9DDjWTNc1nmYVNQXaQqXalQzXaiCHAOtUJvTWBRZiuT6UK1fBElM80PnL6dC5Umb8qvfHdkSMgoMW9CJzwOTZ0zTy17JBGZqRQmlfW2G9LacoWIil0UrxjhgmJmRXhwXHFpdGwEVl7AoQGVlJGabXuChutaTxmfGOoUbCr0=</CipherValue>
</CipherData>
</EncryptedKey>
</KeyInfo>
<CipherData>
<CipherValue>qry5qnr3qxOgyoNPeP7OKEiHpr/PPTsaeQ2mYUsSK7cg4Kkl9uPO4RyUXgBIkgCTsjbObqLlyndcSBnYyek6bxG/IBL82G1R5J1ci8i1eyt8kIDqouzYOx5vtouErld4z1L+7WGf9Wg37QAH5RiiEfkCHndJJq3dTqjxnnXZSno6NgbxSXDfqzwE/eKDVhGV3oaTQSfjVmO8e5a9wvREYeeyasDhojx8J2mdy7/Q9rEIpv98RTiRxA==</CipherValue>
</CipherData>
</EncryptedData>
</connectionStrings>	
If we want to implement encryption and decryption with “DataProtectionConfigurationProvider” just replace “RSAProtectedConfigurationProvider” with “DataProtectionConfigurationProvider” and use same code.

License

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

About the Author

Rahul Kumar Mittal (Napster)
Software Developer (Senior)
India India
Microsoft Certified Technology Specialist : .Net Framework 4 with Web Applications
Follow on   Twitter   Google+

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
Hint: For improved responsiveness ensure Javascript is enabled and choose 'Normal' from the Layout dropdown and hit 'Update'.
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
QuestionThank youmemberYahya Mohammed Ammouri1-Jun-13 21:22 
GeneralMy vote of 3memberkarthick.pvm11-Feb-13 2:04 
QuestionProblem when run encrypted config file in another machinememberMember 441125612-Dec-12 22:19 
AnswerThanks. Nice and simplememberAhsanS11-Dec-12 20:19 
GeneralNice TutorialmemberMr.Literal31-Oct-12 9:13 
QuestionFor a Production Server?memberMember 885168223-Oct-12 2:49 
QuestionSystem.InvalidOperationException: Failed to map the path '/'.memberAnbu arunmozhi11-Oct-12 23:18 
GeneralMy vote of 5memberTamil Selvan K16-Jul-12 20:17 
Generalfor vb 2008..its same? thanksmembernur imelia28-Dec-11 20:38 
GeneralRe: yes it's same..memberRahul Mittal (Napster)28-Dec-11 21:46 
Generalfor visual studio 2010 what do? plz path exactly in command ...memberarh6626-Dec-11 20:33 
GeneralRe: For VS2010 First of all You need to Open VS Command Prompt W...memberRahul Mittal (Napster)27-Dec-11 7:13 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web02 | 2.6.130617.1 | Last Updated 23 Dec 2011
Article Copyright 2011 by Rahul Kumar Mittal (Napster)
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid