How to Encrypt Connection String in ASP.NET

I’m going to demonstrate in this post how, as opposed to utilizing the command line, you can use code to encrypt your connection string. In the command line approach, you use aspnet_regiis.exe and a series of instructions to perform the encryption and decryption, which limits your versatility. In contrast, I think the coding approach is more simpler and more adaptable. Why, then, must your connection string and other important information be encrypted?

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.

Encrypting your sensitive data is a smart idea in any case. While it won’t protect you against a site assault per se, it is an additional layer of security that can make it harder for hackers to access your data.

Encrypting an XML node

Consider the following connection string as an example:

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

       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:

<mailSettings>
      <smtp from="[email protected]">
        <network 
          host="mail.Site.com" 
          port="25" 
          userName="[email protected]" 
          password="password" />
      </smtp>
    </mailSettings>

We use the code:

       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 only difference between encrypting and decrypting our XML node is that previously we checked to see if our XML node was not encrypted; now, however, we check to see if our XML node is encrypted, and after that, we call the UnprotectSection method to decrypt our XML node. The final code should resemble this:

       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:

       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 use the Application_Start() event to call the method in Global.asax to encrypt or decrypt our sensitive XML nodes:

       protected void Application_Start()
        {
            EncryptDecryptWebConfig.EncryptConnString();
            EncryptDecryptWebConfig.EncryptMailSettings();
 
            //EncryptDecryptWebConfig.DecryptConnString();
            //EncryptDecryptWebConfig.DecryptMailSettings();
        }

Conclusion

We hope that article above has given clearly information about how to encrypt your connection string. We hope that you can protect sensitive data and avoid conflict locally and while working on bigger projects with multiple software developers.

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *