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

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

, 1 Feb 2009
Rate this:
Please Sign up or sign in to vote.
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
  • cryptoClasses

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

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

Step 2: Imports Following Namespace

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

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:

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

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

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

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)

About the Author

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

Comments and Discussions

 
GeneralIt only works in development and not in an elegant way PinmemberDimitrisGr23-Feb-09 22:54 

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

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

| Advertise | Privacy | Mobile
Web03 | 2.8.140721.1 | Last Updated 2 Feb 2009
Article Copyright 2008 by Manish K Gupta
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid