Click here to Skip to main content
15,884,177 members
Articles / All Topics

Programmatically Encrypt the Connection String In ASP.NET Applications

Rate me:
Please Sign up or sign in to vote.
4.62/5 (7 votes)
19 Nov 2015CPOL2 min read 17.9K   5   2
How to programmatically encrypt the Connection String in ASP.NET applications

In this post, I’m going to show you how you can encrypt your connection string using code, as opposed to command line. In command line approach, you use the aspnet_regiis.exe and issue a set of commands to do the encrypt/decrypt, which you lose some flexibility, but the code approach is much cleaner and more flexible in my opinion. But why do you need to encrypt your connection string and other sensitive information? There are a lot of reasons that warrant the need to encrypt sensitive information in Web.config, for example suppose your client uses a shared hosting, if the server is compromised, the hacker has access to the system files, and he/she can easily use the information in Web.config and access your database data, or if you have your email password in there, a hacker can use it for malicious purposes.

In any event, it is a good idea to encrypt your sensitive information, it is not going to save you if your site attacked per se, but it is an extra layer of security which can make the hacker’s work more difficult.

Encrypting an XML Node

Suppose we have a connection string like this:

XML
<connectionStrings>
    <add name="OurDb"
         connectionString="Data Source=(LocalDB)\MSSQLLocalDB;
         AttachDbFilename=|DataDirectory|\OurDb.mdf;
         Initial Catalog=OurDb;
         Integrated Security=True" 
         providerName="System.Data.SqlClient" />
  </connectionStrings>

For encrypting it, we use the code below:

C#
public static void EncryptConnString()
 {
     Configuration config = WebConfigurationManager.OpenWebConfiguration("~");
     ConfigurationSection section = config.GetSection("connectionStrings");

     if (!section.SectionInformation.IsProtected)
     {
         section.SectionInformation.ProtectSection("RsaProtectedConfigurationProvider");
         config.Save();
     }
 }

First, we grab the root element in our Web.config using WebConfigurationManager configuration manager class, then we use that variable and the GetSection method and grab our connection string, then we check to see if our node is already encrypted, if not we go ahead and use the section variable and call the ProtectSection method and use the RsaProtectedConfigurationProvider to encrypt that section, and then we save our Web.config.

The same process applies if we wanted to encrypt our email, for encrypting the smtp node with an XML like this:

XML
<mailSettings>
      <smtp from="info@Site.com">
        <network
          host="mail.Site.com"
          port="25"
          userName="info@site.com"
          password="password" />
      </smtp>
  </mailSettings>

We use the code:

C#
public static void EncryptMailSettings()
 {
     Configuration config = WebConfigurationManager.OpenWebConfiguration("~");
     ConfigurationSection section = config.GetSection("system.net/mailSettings/smtp");

     if (!section.SectionInformation.IsProtected)
     {
         section.SectionInformation.ProtectSection("RsaProtectedConfigurationProvider");
         config.Save();
     }
 }

Notice that we need to drill down to the specific section with slash like so:

"system.net/mailSettings/smtp"

Decrypting an XML Node

The decryption of our XML node is similar to encrypting it, the only difference is that before we've checked to see if node is not encrypted, but now we check to see if our XML node is encrypted, and then we call the UnprotectSection method to decrypt our XML node, the final code should look something like this:

C#
public static void DecryptConnString()
 {
     Configuration config = WebConfigurationManager.OpenWebConfiguration("~");
     ConfigurationSection section = config.GetSection("connectionStrings");
     if (section.SectionInformation.IsProtected)
     {
         section.SectionInformation.UnprotectSection();
         config.Save();
     }
 }

The same process is repeated for decrypting the email section:

C#
public static void DecryptMailSettings()
 {
     Configuration config = WebConfigurationManager.OpenWebConfiguration("~");
     ConfigurationSection section = config.GetSection("system.net/mailSettings/smtp");
     if (section.SectionInformation.IsProtected)
     {
         section.SectionInformation.UnprotectSection();
         config.Save();
     }
 }

Calling our Method to Encrypt or Decrypt our XML Nodes

Now we can call the method in Global.asax in Application_Start() event to encrypt or decrypt our sensitive XML nodes:

C#
protected void Application_Start()
 {
     EncryptDecryptWebConfig.EncryptConnString();
     EncryptDecryptWebConfig.EncryptMailSettings();

     //EncryptDecryptWebConfig.DecryptConnString();
     //EncryptDecryptWebConfig.DecryptMailSettings();
 }

This article was originally posted at http://www.hamidmosalla.com/feeds/posts/default

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
Iran (Islamic Republic of) Iran (Islamic Republic of)
Programming is my passion, because I find it so intellectually rewarding. I currently work as a back-end web developer, using Microsoft technology stack, I also blog about my experiences and contribute to open source projects on my free time.

Comments and Discussions

 
GeneralMy vote of 5 Pin
Awesh Vishwakarma26-Apr-21 22:37
professionalAwesh Vishwakarma26-Apr-21 22:37 
PraiseNice post Pin
Member 1215517320-Nov-15 1:40
Member 1215517320-Nov-15 1:40 

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

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