Section 4.7. Encrypt Connection Strings

4.7. Encrypt Connection Strings

Note: Protect your connection strings in Web.config from peering eyes by encrypting them!

Instead of saving your database connection string within your application, it is often much better (and easier to maintain) to have your connection strings stored in the Web.config file. In ASP.NET 2.0, Microsoft has taken this further by allowing you to encrypt the connection string that you store in Web.config.

4.7.1. How do I do that?

To see how you can encrypt the connection strings stored in Web.config, you will configure a GridView control to bind to a SqlDataSource control. The connection string used by the SqlDataSource control would be saved in the Web.config file. You will 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 web site project. Name the project C:\ASPNET20\chap04-EncryptConfig.

  2. Populate the default form with a GridView control and configure it to use a SqlDataSource control. Configure the SqlDataSource control to connect to the pubs database and use the authors table. In particular, ensure that the connection string is stored in Web.config.

    Tip: Refer back to the lab Section 4.1 if you are not sure how to configure the GridView control to use a SqlDataSource control.

  3. The default form should now look like Figure 4-44.

    Figure 4-44. The GridView and SqlDataSource control

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

    <configuration     xmlns="">    <appSettings/>    <connectionStrings>       <add name="pubsConnectionString" connectionString="Data                   Source=.\SQLEXPRESS;Initial Catalog=pubs;                  Integrated Security=True"            providerName="System.Data.SqlClient" />    </connectionStrings>    <system.web> ...

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

    Imports System.Configuration Imports System.Web.Security     Public Sub Encrypt(ByVal protectionProvider As String)         '---open the web.config file         Dim config As Configuration = _            System.Web.Configuration. _               WebConfigurationManager.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 the Decrypt( ) method to decrypt the encrypted connection strings in Web.config:

    Public Sub Decrypt( )     Dim config As Configuration = _        System.Web.Configuration. _           WebConfigurationManager.OpenWebConfiguration( _        Request.ApplicationPath)     Dim section As ConfigurationSection = _        config.Sections("connectionStrings")     section.SectionInformation.UnProtectSection( )     config.Save( ) End Sub

    Tip: 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.

  7. Two protection configuration providers are available for your use:

    • DataProtectionConfigurationProvider

    • RSAProtectedConfigurationProvider

    To test the Encrypt( ) method, call it in the Form_Load event:

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

    Tip: RSAProtectedConfigurationProvider uses the public-key algorithm available in the .NET Framework's RSACryptoServiceProvider class to perform encryption; DataProtectionConfigurationProvider uses the Windows DPAPI.You should call the Encrypt( ) method only once.

  8. If you use the DataProtectionConfigurationProvider, your connection string will now look like Example 4-7.

    Example 4-7. Connection string with DataProtectionConfigurationProvider
    <configuration xmlns="">    <protectedData>       <protectedDataSections>          <add name="connectionStrings"               provider="DataProtectionConfigurationProvider"               inheritedByChildren="False" />       </protectedDataSections>    </protectedData>    <appSettings/>             <connectionStrings>          <EncryptedData>             <CipherData>                <CipherValue>AQAAANCMnd............WaWSpYkRgVTirQ=</CipherValue>             </CipherData>         </EncryptedData>       </connectionStrings>    <system.web> ...

  9. If you use the RSAProtectedConfigurationProvider, your connection string will now look like Example 4-8.

    Example 4-8. Connection string with RSAProtectedConfigurationProvider
    ... <configuration xmlns="">    <protectedData>       <protectedDataSections>          <add name="connectionStrings"                provider="RSAProtectedConfigurationProvider"               inheritedByChildren="False" />       </protectedDataSections>    </protectedData>    <appSettings/>       <connectionStrings>          <EncryptedData Type=""             xmlns="">             <EncryptionMethod                 Algorithm="" />             <KeyInfo xmlns="">                <EncryptedKey xmlns="">                   <EncryptionMethod Algorithm="                      xmlenc#rsa-1_5" />                   <KeyInfo xmlns="">                      <KeyName>RSA Key</KeyName>                   </KeyInfo>                   <CipherData>                      <CipherValue>XzI2CV8F1Pd........oVf1DnuM=</CipherValue>                   </CipherData>                </EncryptedKey>             </KeyInfo>             <CipherData>                <CipherValue>039jWP/......XIvitv0KBQ==</CipherValue>             </CipherData>          </EncryptedData>       </connectionStrings>       <system.web> ...

  10. The really nice 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 Decrypt( ) method.

  11. You can check whether a section is protected by using the IsProtected property, like this (you can use this block of code in the Page_Load event, for example):

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

    Self-Contained Protection

    Notice that the <protectedData> section added to Web.config contains information needed to decrypt the connection strings.

    More importantly, <protectedData> doesn't contain the decryption key. For example, if you use the Windows DataProtectionConfigurationProvider, the decryption key is autogenerated and saved in the Windows Local Security Authority (LSA).

4.7.2. What about...

...programmatically adding a new connection string to an encrypted Web.config file?

The following AddConnString( ) method shows how you can add a new connection string to the Web.config file.

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

...protecting other sections in Web.config?

You can encrypt almost any section in Web.config, with the exception of sections accessed by parts of the unmanaged code in ASP.NET, such as <httpRuntime> and <processModel>.

...retrieving connection strings programmatically?

It can be done. To programmatically retrieve a connection string from Web.config, use the following code:

Dim connect As String = _    ConfigurationManager.ConnectionStrings _    ("NorthwindConnectionString").ConnectionString Response.Write(connect)

4.7.3. Where can I learn more?

To learn more about the ProtectedConfigurationProvider class, check out the MSDN Help topic "ProtectedConfigurationProvider Class."

To understand how Windows Data Protection works, check out

For an introduction to the cryptography classes in .NET, check out my article at

ASP. NET 2.0(c) A Developer's Notebook 2005
ASP. NET 2.0(c) A Developer's Notebook 2005
Year: 2005
Pages: 104 © 2008-2017.
If you may any questions please contact us: