Search - Articles
DevASP.NET for ASP.NET, VB.NET, XML and C# (C-Sharp) Developers Tuesday, March 03, 2009
Dev Articles
Search Directory
ASP.NET
VB.Net
C-Sharp
SQL Server
 

How to Encrypt and Decrypt connection string in web.config file in ASP.NET

Author: Richard Wand
Download Source Code : 1337_EncryptDecryptConnectionString.zip

This article will explain how we can encrypt and decrypt connection string in web.config file in ASP.NET.

 

Although web.config file is secure when we have implemented security in our server but in shared environment it can be possible that someone get access to web.config and read your sensitive information. Web.config contains many sections including connectionStrings section. This section also contains sensitive information like username and password for database access.
 
ASP.NET provides a good way to save encrypted configuration sections in web.config file. It offers two providers to Encrypt and Decrypt configuration sections.
 
DataProtectedConfigurationProvider
 
It is windows data protection API to encrypt and decrypt configuration sections.
 
RSAProtectedConfigurationProvider

It is the default API that uses RSA public key to encrypt and decrypt configuration sections.

  1. Create new website in Visual Studio 2010
  2. Add two Buttons and a Label in aspx page of a web form

    <asp:Button ID="ButtonEncrypt" runat="server" Text="Encrypt Connection String"
        onclick="ButtonEncrpty_Click" />
    <br />
    <br />
    <asp:Button ID="ButtonDecrypt" runat="server" Text="Decrypt Connection String"
         onclick="ButtonDecrypt_Click" />
    <br />
    <br />
    <asp:Label ID="lblMessage" runat="server" ></asp:Label>
     
  3. Add a connectionString section in your web.config file.

    <connectionStrings>
           <add name="SampleDB" connectionString="Data Source=Local;Initial Catalog=SampleDatabase;Integrated Security=True" />
    </connectionStrings>

     
    Write a Sample database name in connection string for encryption and decryption purposes.
     
  4. We have to use following namespaces in our code

    C#
     
    using System.Configuration;
    using System.Web.Configuration;
     
    VB.NET
     
    Imports System.Configuration
    Imports System.Web.Configuration
     
  5. Now Add a Button click event for ButtonEncrypt and write code below in it.

    C#
     
    protected void ButtonEncrypt_Click(object sender, EventArgs e)
    {
        try
        {
            Configuration config = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
            ConfigurationSection configSection = config.GetSection("connectionStrings");
     
            if (configSection != null)
            {
                 configSection.SectionInformation.ProtectSection("RSAProtectedConfigurationProvider");
                config.Save();
                lblMessage.Text = "Connection string Encrypted successfully";
            }
        }
        catch (Exception ex)
        {
            lblMessage.Text = "Unable to Encrypt connection string";
        }
     }
     
    VB.NET
     
    Protected Sub ButtonEncrypt_Click(ByVal sender As Object, ByVal e As EventArgs) Handles ButtonEncrypt.Click
        Try
            Dim config As Configuration = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath)
            Dim configSection As ConfigurationSection = config.GetSection("connectionStrings")
     
            If configSection IsNot Nothing Then
                configSection.SectionInformation.ProtectSection("RSAProtectedConfigurationProvider")
                config.Save()
                lblMessage.Text = "Connection string Encrypted successfully"
            End If
        Catch ex As Exception
            lblMessage.Text = "Unable to Encrypt connection string"
        End Try
    End Sub
     
    Create an instance of Configuration class and call OpeWebConfiguration() method of WebconfigurationManager class. Create an instance of ConfigurationSection class and call GetSection() method of Configuration instance. We have to provide section name in the GetSection() method as string. Check if section is there in the web.config file. Call the ProtectSection() method of SectionInformation property of ConfigurationSection instance. In ProtectSection() method, we have to provide the provide name. You can provide DataProtectedConfigurationProvider in place of RSAProtectedConfigurationProvider. Call the Save() method of configuration class in the end.
     
  6. Now start debugging and click on Encrypt button. Open web.config file and see ConnectionString section will look 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>PhyHL8ENWHWG8INN+PZW3OPrRUcDtU7Zo+hgjBLahigofJAHAzoi8wYqx6q+D/L2LjV2mRZBqcMm5ZiRfFVH1MtL4vgcuh6kaI31ItG+JQkYFV2SNLv9L25msS55vd2xDEp/tNSDyIq3XjmzwGQWHrSETsYWClx/H9w5lbOjj80=</CipherValue>

         </CipherData>

        </EncryptedKey>

       </KeyInfo>

       <CipherData>

        <CipherValue>yWe5pixRwnBDNLPSURkkW9F6mw7vWXP7JI6G5z/Dtc0uJq0Qg16DVnxvAuVLkb2iwanDLwwddneAIgq+Ij+SLOpPs49foU92uUfnWgzdfoezo3jUOBQ+yCW50WCVOrbRsa8MNb0FxXpIM+iUGzrj0Q+086cvDLsSFExASSyCWM1Ri7TwNtaZwbGHeXNHZPzqr9lV6ilyYDz0F5DSQt56k7bLyfWt2gl4ort6TLrSLfI=</CipherValue>
       </CipherData>
      </EncryptedData>

    </connectionStrings>
     
     
  7. Now Add another Button click event for ButtonDecrypt and write code below in it.

    C#
     
    protected void ButtonDecrypt_Click(object sender, EventArgs e)
    {
        try
        {
            Configuration config = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
            ConfigurationSection configSection = config.GetSection("connectionStrings");
     
            if (configSection != null && configSection.SectionInformation.IsProtected)
            {
                configSection.SectionInformation.UnprotectSection();
                config.Save();
                lblMessage.Text = "Connection string Decrypted successfully";
            }
        }
        catch (Exception ex)
        {
            lblMessage.Text = "Unable to Decrypt connection string";
        }
    }
     
    VB.NET

    Protected Sub ButtonDecrypt_Click(ByVal sender As Object, ByVal e As EventArgs) Handles ButtonDecrypt.Click
        Try
            Dim config As Configuration = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath)
            Dim configSection As ConfigurationSection = config.GetSection("connectionStrings")
     
            If configSection IsNot Nothing AndAlso configSection.SectionInformation.IsProtected Then
                configSection.SectionInformation.UnprotectSection()
                config.Save()
                lblMessage.Text = "Connection string Decrypted successfully"
            End If
        Catch ex As Exception
            lblMessage.Text = "Unable to Decrypt connection string"
        End Try
    End Sub
     
    All the code is same as in Encrypt button event. You need to call the UnprotectSection() method of SectionInformation property of ConfigurationSection instance.
     
  8. Now start debugging and click on Decrypt button. Open web.config file and see ConnectionString section in its normal condition.

    <connectionStrings>
           <add name="SampleDB" connectionString="Data Source=Local;Initial Catalog=SampleDatabase;Integrated Security=True" />
    </connectionStrings>
     

 

   
Add Article Comment:
Name :
Email Address :
   
Comments :
 
   
<< How to export DataTable to PDF in ASP.NET

Disclaimer - Privacy
© 2002-2017 DevASP.net