Click here to Skip to main content
15,867,594 members
Articles / Web Development / XHTML

Encryption of Connection Strings Inside the Web.config in ASP.NET 2.0

Rate me:
Please Sign up or sign in to vote.
4.07/5 (29 votes)
1 Feb 2009CPOL3 min read 162.8K   122   17
Encryption & Decryption of Connection Strings inside the Web.config in ASP.NET 2.0

Introduction

This article gives you a general view of the Encryption of Connection string inside the Web.config feature and how you can use encryption and increase the security and keep the secure connection with the database.

About Encryption & Decryption of Connection Strings

The .NET Framework 2.0 allows you to encrypt configuration sections within the Web.config or machine.config files.

Encryption support for configuration files is added to the .NET Framework 2.0. The .NET Framework libraries support encryption and decryption in code. In this article, I'll show how to protect data stored in a configuration file via encryption and describe configuration file sections.

It is recommended that you store your database connection strings in the Web.config file and encrypt the connection strings.

This feature allows developers to encrypt one or more sections of a configuration file. The following sections for encryption:

  • connectionStrings: Database connection strings
  • appSettings: Custom application settings
  • sessionState: Configures session state
  • Identity: Web application identities, which may include impersonation credentials

We can't use the Protected Configuration feature on the following sections of web.config and machine.config files:

  • processMode
  • runtime
  • mscorlib
  • configProtectedData
  • satelliteassemblies
  • cryptographySettings
  • cryptoNameMapping
  • cryptoCl<code>asses

Protect Sensitive Data

Encryption of configuration feature improves application security. If anybody can access the web.config file, then they can't access the database information. The .NET Framework provides two ways to encrypt configuration files:

  • The aspnet_regiis.exe command-line utility
  • Encryption within developers application code

This article focuses on the application code approach.

The following namespaces are used to encrypt configuration files for code approach:

  • System.Configuration
  • System.Web.Configuration

It contains the following two methods associated with encryption:

  • ProtectSection: Marks a configuration section for protection. The name of the provider to be used for the encryption and it is passed to the method as its only parameter
  • UnprotectSection: Removes the protected encryption from the associated configuration section

Example

The following simple ASP.NET web.config file demonstrates encryption and decryption of configuration data.

Step 1: View the connectionStrings web.config Section

XML
<connectionstrings><add class=""code-string"" name=""<span"">
"Conn" connectionString="Data Source=manish;Initial Catalog=Publish;
User ID=sa;Password=admin"
providerName="System.Data.SqlClient" /> </connectionstrings>

Step 2: Imports Following Namespace

We will write the code where we call the connection string or initialize the connection string.

VB.NET
Imports System.Configuration
Imports System.Web.Configuration

Step 3 : Create a Function (configencryption)

This function works for encryption and decryption.
The following VB.NET code from an ASP.NET Web form encrypts the connectionStrings section of the configuration file:

VB.NET
Public Shared Function webencrypt()
        Dim config As Configuration = WebConfigurationManager.OpenWebConfiguration("~")
        '' Write the section name of web.config file (connectionStrings)
        Dim configSection As ConfigurationSection = c_
			onfig.GetSection("connectionStrings")

        '' Check the section  of web.config file (connectionStrings) if Protected 
        '' then UnprotectSection (decrypt) the section
        If configSection.SectionInformation.IsProtected Then
            configSection.SectionInformation.UnprotectSection()
            config.Save()
        Else
            '' Check the section of web.config file (connectionStrings) 
            '' if UnprotectSection then 
            '' protect (encrypt) Section the section
            configSection.SectionInformation.ProtectSection_
			("DataProtectionConfigurationProvider")
            config.Save()
        End If
    End Function 

Step 4: Call this Function Before the Connection Initialize on *.vb File

VB.NET
Call webencypt()
sqlstring = System.Configuration.ConfigurationManager.ConnectionStrings_
						("conn").ConnectionString

After you run the above code and the web.config has been encrypted, you can open up the web.config file in your ASP.Net project. The contents of the web.config section will now appear encrypted.

Step 5: View the connectionStrings web.config Section (decrypted)

<connectionstrings class=""code-string"" 
	configprotectionprovider=""<span"">"DataProtectionConfigurationProvider">    
<encrypteddata>
      <cipherdata>
        <ciphervalue>AQAAANCMnd8BFdERjHoAwE/Cl+sBAAAAe3IeYtVA1Ein16Kz9W96UQQAAAACAAAAAA
ADZgAAqAAAABAAAABLQdIlQjmYEpvL/YlcKtQIAAAAAASAAACgAAAAEAAAALJbofuwZFVfY0X5w
PO172OYAQAAM1JJuZpvWvHlvZZCGMpLXmvkURVkdv3gjWjED3y0X29kGfKrecXPg+xngFAQ1qG4
Ruxa96leDTo+Eb1QrvXgZgdABN+rXmmzPwi9csOCorTidlJ/55drL96zyeQrynPfs4HRqtRPmc8
4F/4hVbEe9xnKIiykSPEYSnOIef4arj567y5vmwcgh8b11d4wmbMIbrvgWFOWniJRXgvkHAYMje
/R5C6yRDDqr7OCkvZoX/hqe+mkJRvpHewCXJBIcbHsF2sCs3WZQlNbDY7H9J3EESPR4S0qPTEb3
q8GD31vjMPo7WbDTTN8/lXi6BbooyY6IPviIkxUvmbAxxiWXmz7J93WYKqnhFUHunv8JgoBgc8a
6t55zpsG1oNGSJAAJ7qBu0Y1+gktPQof/DabkL54Zl8wK8/u6q7mU+nJbaHW9AKC6bfCWa16QXV
6jF2QWHGqrsXzRqURXsG0t+9bdNwmiNHimpVc6p+JhiXNd9Ym8NbDCCS2ICgNDActd5MmGfJpHM
PbubNuVgcueSdH8bdHJXSc1hucDURrFAAAAHOaFiNRTxD+d8YctPO/HiGD9NeV  </cipherdata>

Step 6: When Next Time Page Post Back then View the connectionStrings web.config Section

XML
<connectionstrings><add class=""code-string"" name=""<span"">
"Conn" connectionString="Data Source=manish;Initial Catalog=Publish;
User ID=sa;Password=admin"
providerName="System.Data.SqlClient" />
  </connectionstrings>

Conclusion

In this article, we saw how to encrypt and decrypt the connection strings section in ASP.NET 2.0 web.config files.

Disclaimer

This article is purely for educational purposes and is a compilation of notes, material and my understanding on this subject.

License

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


Written By
Software Developer (Senior) Diaspark
India India
I am Manish Gupta, i m Software Developer

Comments and Discussions

 
GeneralMy vote of 2 Pin
Viper20109-Sep-13 14:37
Viper20109-Sep-13 14:37 
GeneralMy vote of 5 Pin
Member 888949020-Jul-12 3:03
Member 888949020-Jul-12 3:03 
Questionfor web config file Pin
Ganesh Gavhale7-Feb-12 20:46
Ganesh Gavhale7-Feb-12 20:46 
GeneralNice code, Pin
javier.alpizar1-Jul-10 7:55
javier.alpizar1-Jul-10 7:55 
GeneralRe: Nice code, Pin
Manish K Gupta4-Jul-12 21:06
Manish K Gupta4-Jul-12 21:06 
GeneralMy vote of 2 Pin
zakm7-Jun-10 1:05
zakm7-Jun-10 1:05 
GeneralIt only works in development and not in an elegant way Pin
DimitrisGr23-Feb-09 22:54
DimitrisGr23-Feb-09 22:54 
GeneralGood idea, try combining it with a facade pattern Pin
Brett Slaski9-Feb-09 5:22
Brett Slaski9-Feb-09 5:22 
QuestionHow secure is it? Pin
Qistoph2-Feb-09 20:57
Qistoph2-Feb-09 20:57 
QuestionAny C# Code ? Pin
Pankaj Nikam2-Feb-09 3:17
professionalPankaj Nikam2-Feb-09 3:17 
AnswerRe: Any C# Code ? Pin
sumit70342-Feb-09 5:40
sumit70342-Feb-09 5:40 
GeneralRe: Any C# Code ? Pin
Pankaj Nikam2-Feb-09 7:18
professionalPankaj Nikam2-Feb-09 7:18 
GeneralNice Pin
Vimalsoft(Pty) Ltd1-Feb-09 23:36
professionalVimalsoft(Pty) Ltd1-Feb-09 23:36 
Generalgood article Pin
Donsw12-Jan-09 3:00
Donsw12-Jan-09 3:00 
Generalnice trick Pin
ArpitDubey11-Nov-08 7:17
ArpitDubey11-Nov-08 7:17 
General[Message Removed] Pin
hankjmatt13-Oct-08 23:51
hankjmatt13-Oct-08 23:51 
Generalasp.net Pin
ramesh_pune131-May-08 20:29
ramesh_pune131-May-08 20:29 

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

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