Encrypting and decrypting configuration sections

I recently had to encrypt the connectionStrings section of a web.config file. This is a quick note on how I did it. Refer the MSDN documentation for more details.

Encrypting a Configuration Section

C:\Windows\Microsoft.NET\Framework\v4.0.30319>aspnet_regiis
-pef "connectionStrings" "C:\inetpub\wwwroot\HelloWorld"
-prov "DataProtectionConfigurationProvider"

Decrypting an Configuration Section

C:\Windows\Microsoft.NET\Framework\v4.0.30319>aspnet_regiis
-pdf "connectionStrings" "C:\inetpub\wwwroot\HelloWorld"
-prov "DataProtectionConfigurationProvider"

The -pef and -pdf arguments must point to the web folder root with no trailing slash (‘\’) in the path. I am executing this from v4.0.30319 directory because I have multiple framework versions installed and I need to be sure that I was using the correct version of the aspnet_regiis.exe file.

Moreover, the file sections encrypted using the DataProtectionConfigurationProvider provider cannot be decrypted on a different machine. If you are planning to use the same encrypted configuration file on multiple servers, such as a Web farm, use the RsaProtectedConfigurationProvider instead.

From MSDN: Encryption and decryption of the contents of a Web.config file is performed using a ProtectedConfigurationProvider class. The following list describes the protected configuration providers included in the .NET Framework:

  • DpapiProtectedConfigurationProvider uses Windows Data Protection API (DPAPI) to encrypt and decrypt data.
  • RsaProtectedConfigurationProvider uses RSA encryption algorithm to encrypt and decrypt data. Both providers offer strong encryption of data; however, if you are planning to use the same encrypted configuration file on multiple servers, such as a Web farm, only the RsaProtectedConfigurationProvider enables you to export the encryption keys used to encrypt the data and import them on another server.