Encrypt and Decrypt connectionString in web.config file using code in asp.net

Introduction: In previous articles i explained How to encrypt and decrypt username,password and store in Sql Server database using asp.net and  How to Encrypt connection string in web.config in asp.net | How to Decrypt connection string in web.config in asp.net and How to Encrypt Query String in asp.net(C#, VB) | Encrypting and Decrypting Query String in asp.net(C#, VB) and 20 differences between Stored procedures and Functions in Sql Server .
Now in this article i  will explain how to Encrypt and Decrypt or we can say Encode and Decode connection String in web.config file using code in asp.net.As we know connectionstring in the web.config file contains the most sensitive information. No one wants to disclose the information related to his database to all the users where the application is deployed. So in this case you can encrypt the connection string. 

  • Place two button on design file(.aspx)
  <asp:Button id="btnEncrypt" runat="server" Text="Encrypt" onclick="btnEncrypt_Click" />
<asp:Button ID="btnDecrypt" runat="server" Text="Decrypt" onclick="btnDecrypt_Click" />

C#.Net Code to Encrypt and Decrypt connectionString in web.config file using code
  • Then in the code behind file(.aspx.cs) write the code as:
Include following namespaces:

using System;
using System.Configuration;
using System.Web.Configuration;

string provider = "RSAProtectedConfigurationProvider";
    //OR string provider = "DataProtectionConfigurationProvider";
    string section = "connectionStrings";

    protected void Page_Load(object sender, EventArgs e)
    {
    }
    protected void btnEncrypt_Click(object sender, EventArgs e)
    {
        Configuration confg = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
        ConfigurationSection configSect = confg.GetSection(section);
        if (configSect != null)
        {
            configSect.SectionInformation.ProtectSection(provider);
            confg.Save();
        }
    }
    protected void btnDecrypt_Click(object sender, EventArgs e)
    {
        Configuration config = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
        ConfigurationSection configSect = config.GetSection(section);
        if (configSect.SectionInformation.IsProtected)
        {
            configSect.SectionInformation.UnprotectSection();
            config.Save();
        }
    }

VB.Net Code to Encrypt and Decrypt connectionString in web.config file using code

  • Then in the code behind file(.aspx.vb) write the code as:
Include following namespaces:
Imports System.Web.Configuration

Partial Class _Default
   Inherits System.Web.UI.Page
   Private provider As String = "RSAProtectedConfigurationProvider"
‘OR string provider = "DataProtectionConfigurationProvider";

   Private section As String = "connectionStrings"

   Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
   End Sub

   Protected Sub btnEncrypt_Click(ByVal sender As Object, ByVal e As EventArgs)
      Dim confg As Configuration = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath)
      Dim confgSect As ConfigurationSection = confg.GetSection(section)
      If confgSect IsNot Nothing Then
         confgSect.SectionInformation.ProtectSection(provider)
         confg.Save()
      End If
   End Sub

   Protected Sub btnDecrypt_Click(ByVal sender As Object, ByVal e As EventArgs)
      Dim config As Configuration = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath)
      Dim confgSect As ConfigurationSection = config.GetSection(section)
      If confgSect.SectionInformation.IsProtected Then
         confgSect.SectionInformation.UnprotectSection()
         config.Save()
      End If
   End Sub
End Class
  • Suppose your connection string was like:
            <connectionStrings>
  <add name="MyDbCon" connectionString="Data Source=LocalServer;Initial Catalog=MyDataBase;Integrated Security=True" />
 </connectionStrings>
  • After clicking on encrypt button it will look like as:
            <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>WMeNxK/sciigctZQEKsI92PInfnvjEG0FauBojJs48nVDywksp6g5EuxysxQbddo5mSSvJZeT9iA2dIp+Xcnss+qbyT/M0HDMY0w7ru2Yt+JIsedoxZ/6Ohqv19k0U6/jZkc0VeDpe3YozVyS6WainqAfUEBLnO8M9vsWyPDQT4=</CipherValue>
     </CipherData>
    </EncryptedKey>
   </KeyInfo>
   <CipherData>
    <CipherValue>vYwnoyMEtEz4xYQmQ6Xm8C9m18a5ruaw9VwjjJVoAmXi+lD1o5eNUqq/fiZM6yrQYWWDb/0h81TFCrICyxGlTP1/1jhxFwFStAwuTNF1V9LThB86pEFkvjLUnYlGlYjgizcY+IzY9tDvdh5TfVMf0egqS+vx3ZsjJCpryNqTaO9OTNoa/EazrvI116L+pEnji+Ba76LAE5D0gt3nYz0G+3xx6grvuF9M</CipherValue>
   </CipherData>
  </EncryptedData>
 </connectionStrings>

Note: In case you  want  encryption and decryption with “DataProtectionConfigurationProvider” instead of “RSAProtectedConfigurationProvider”  then just replace “RSAProtectedConfigurationProvider” with “DataProtectionConfigurationProvider” and the code code will remain same.


DataProtectionConfigurationProvider, which uses the Windows data protection API (DPAPI), and the RsaProtectedConfigurationProvider, which uses RSA.

If the encrypted configuration file is going to be on only a single server, you can use the DataProtectionConfigurationProvider. If you want to deploy the same encrypted configuration file on multiple servers in a Web farm, you should use the RsaProtectedConfigurationProvider. This provider makes it easy for you encrypt the data on one server computer and then export the RSA private key needed to decrypt the data. You can then deploy the configuration file and the exported key to the target servers, and then re-import the keys.

Now over to you:
"If you like my work; you can appreciate by leaving your comments, hitting Facebook like button, following on Google+, Twitter, Linked in and Pinterest, stumbling my posts on stumble upon and subscribing for receiving free updates directly to your inbox . Stay tuned for more technical updates."
Previous
Next Post »

If you have any question about any post, Feel free to ask.You can simply drop a comment below post or contact via Contact Us form. Your feedback and suggestions will be highly appreciated. Also try to leave comments from your account not from the anonymous account so that i can respond to you easily..