Encrypting connection strings in web.config

Encrypting web.config elements is a good security feature. Web.Config elements can include passwords and important keys that we need to protect.Encrypting web.config elements is a good security feature. Web.Config elements can include passwords and important keys that we need to protect.

There are several methods to encrypt the web.config:

  • Using a command line statement
  • Using .NET code
  • Configuring the web deployment

The easier solution, although limited, is configuring the web deployment. When we prepare the deployment of a web application, a file with PUBXML extension is included in the project. This file has the configuration for the application deployment in XML format.

PUBXML file

Using a single additional configuration we can we can ensure the encryption of the connection string in the production web.config:

<MSDeployEnableWebConfigEncryptRule>true</MSDeployEnableWebConfigEncryptRule>

There are two limitations to this approach:

  • This statement only encrypts the connectionStrings element. If you need to encrypt other sections, such as appSetings, this statement will not solve the problem.
  • If the connection strings are in a different file, not in the web.config, this configuration doesn’t work, it can’t encrypt the connection string in a different file than web.config 

The solution for these limitations would be an Exec element in the  PUBXML file to execute a command line statement after the deployment.

For example, to encrypt the appSettings element we can use the following elements inside the PUBXML file:

 

<Target Name=“CustomPostPublishActions” AfterTargets=“MSDeployPublish”>
                           <Exec Command=“C:\Windows\Microsoft.NET\Framework\v4.0.30319\aspnet_regiis -pe appSettings -app /webCustomers” />
</Target>