Thursday, March 5, 2009

Encrypting Connection Strings in Web.config

Encrypting Connection Strings in Web.config

Thanks to Wei-Meng Lee

One of the best practices in ASP.NET is to save your database connection strings in the Web.config file instead of hard-coding it in your code. This allows you to change database servers easily, without needing to modify your code. As an additional protection, it is always better to use integrated Windows security to access your database, rather than using SQL Server authentication, and thus including your SQL server credentials in the connection string. Either way, it's not such a good idea to save your connection strings as plain text in Web.config -- you should ideally encrypt the connection strings so that it leaves no chance for a potential hacker to easily get more information about your database server.

In ASP.NET 2.0, Microsoft has taken this further by allowing you to encrypt the connection strings in Web.config, all without much plumbing on your part.

Using the DataProtectionConfigurationProvider and RSAProtectedConfigurationProvider for Encryption

To see how you can encrypt the connection strings stored in the Web.config file, you will configure a GridView control to bind to an SqlDataSource control. The connection string used by the SqlDataSource control is saved in the Web.config file. You then encrypt the connection strings, using the two Protection Configuration Providers available in .NET 2.0.

1. Launch Visual Studio 2005 and create a new Website project. Name the project as C:\EncryptConfig.

2. Populate the default form with a GridView control and configure it to use an SqlDataSource control. Configure the SqlDataSource control using the Choose Data Source drop-down list in the GridView Tasks menu (see Figure 1) to connect to the Authors table in the pubs database in SQL Server 2000. In particular, ensure that the connection string to the database is stored in Web.config.

Figure 1
Figure 1: Configuring the GridView control.

The Source View of the GridView and SqlDataSource controls look like this:

GridView ID="GridView1" runat="server" DataKeyNames="au_id"      DataSourceID="SqlDataSource1" AutoGenerateColumns="False">                                                                                 GridView>  SqlDataSource ID="SqlDataSource1" runat="server"       SelectCommand="SELECT * FROM [authors]"      ConnectionString=""> SqlDataSource>     

3. The default form should now look very much like Figure 2.

Figure 2
Figure 2: The GridView and SqlDataSource control.

4. The Web.config file will now contain the connection string:

                             ...  

5. Switch to the code-behind of the default form and add in the EncryptConnStr() method. The EncryptConnStr() method first retrieves the Web.config file and then applies encryption to the specified section (, in this case) of the file using the Protection Configuration Provider indicated (passed in via the protectionProvider parameter).

Imports System.Configuration Imports System.Web.Security      Public Sub EncryptConnStr(ByVal protectionProvider As String)         '---open the web.config file         Dim config As Configuration = _            ConfigurationManager.OpenWebConfiguration( _            Request.ApplicationPath)         '---indicate the section to protect         Dim section As ConfigurationSection = _            config.Sections("connectionStrings")         '---specify the protection provider         section.SectionInformation.ProtectSection(protectionProvider)         '---Apple the protection and update         config.Save()     End Sub 

6. Also, add in the DecryptConnStr() method. The DecryptConnStr() method will decrypt the encrypted connection strings in web.config:

    Public Sub DecryptConnStr()         Dim config As Configuration = _            ConfigurationManager.OpenWebConfiguration( _            Request.ApplicationPath)         Dim section As ConfigurationSection = _            config.Sections("connectionStrings")         section.SectionInformation.UnProtectSection()         config.Save()     End Sub 

7. Note that the UnProtectSection() method, unlike ProtectSection(), does not require a provider name. When a section is encrypted, information regarding the provider that performed the encryption is stored in the Web.config file. UnProtectSection will use that information to determine which provider to use to decrypt the data.

8. There are two protection configuration providers available for your use -- DataProtectionConfigurationProvider and RSAProtectedConfigurationProvider. The DataProtectionConfigurationProvider uses the Windows DPAPI to perform encryption. The RSAProtectedConfigurationProvider uses the public-key algorithm available in the .NET Framework's RSACryptoServiceProvider class to perform encryption.

9. To test the EncryptConnStr() method, call it in the Form_Load event (you should only call the Encypt() method once) with the indicated Protection Configuration Provider:

    Protected Sub Page_Load(ByVal sender As Object, _                             ByVal e As System.EventArgs) _                             Handles Me.Load         Encrypt("DataProtectionConfigurationProvider")         '--or--         ' Encrypt("RSAProtectedConfigurationProvider")     End Sub 

10. If you use the DataProtectionConfigurationProvider provider, your connection string will now look like this:

                                                                                  AQAAANCMnd8.............p4nZCszebgXs=                                       ... 

11. If you use the RSAProtectedConfigurationProvider provider, your connection string will now look like this:

                                                                                                                                                           RSA Key                                                            J7HkJ/9i...c2usLA=                                                                             k6w9KUZ...5p2AP5gQ==                                      ... 

12. Notice that the section added to Web.config contains information needed to decrypt the connection strings. More importantly, doesn't contain the decryption key. For example, if you use the Windows DataProtectionConfigurationProvider, the decryption key is auto-generated and saved in the Windows Local Security Authority (LSA).

13. The really cool thing about encrypting the Web.config file is that the process of decrypting the required connection string is totally transparent to the developer. Controls and code that need to access the connection string will automatically know how to encrypt the encrypted information. However, if you want to decrypt the Web.config file so that you can make modifications to it, simply call the DecryptConnStr() method.

You can check if a section is protected by using the IsProtected property, like this:

If Not section.SectionInformation.IsProtected Then    section.SectionInformation.ProtectSection(protectionProvider)    config.Save() End If 

You can encrypt almost all the sections in Web.config, with the exceptions of some sections such as and . This is because these sections are accessed by parts of the unmanaged code in ASP.NET.

Programmatically Add a New Connection String

You can programmatically add a new connection string to the Web.config file, even though it is encrypted. The following AddConnString() method adds a new connection string named NorthWindConnectionString to an encrypted Web.config:

   Public Sub AddConnString()         '---add a connection string to Web.config         Dim config As Configuration = _                ConfigurationManager.OpenWebConfiguration( _                Request.ApplicationPath)         config.ConnectionStrings.ConnectionStrings.Add _            (New ConnectionStringSettings("NorthwindConnectionString", _            "server=localhost;database=northwind;integrated security=true"))         config.Save()     End Sub 

If you were to decrypt the Web.config file, you will find the newly added connection string:

           

Summary

In this article, I have discussed how easy it is to encrypt connection strings in the Web.config file using the two Protection Configuration Providers -- DataProtectionConfigurationProvider and RSAProtectedConfigurationProvider -- for encryption. Since it is now so easy to perform encryption in Web.config, there is really no reason for not doing so. 

2 comments:

  1. I will strongly Suggest to use
    "http://msbiztalk.blogspot.com/2011/05/biztalk-sso-configuration-data-storage.html"

    ReplyDelete
  2. Mobilunity is a reliable Ukrainian programming office. Re-appropriate white name engineers from Mobilunity - one of the most amazing white marking specialist co-op organizations situated in Kyiv, Ukraine to get the best custom arrangements. It offers the administrations of profoundly talented, qualified, experienced and devoted white name designers for the turn of events, marking, mix, and tasks of the mass market programming items.

    The Mobilunity committed designers supplier organization offers the decent cost for the improvement of current deals, Web optimization and promoting projects fueled by devoted white name programming engineers to make an extraordinary worth against the cash a client spends>> Mobilunity

    ReplyDelete

FEEDJIT Live Traffic Map