ma.citi

A Coder's Blog

Encrypt Database Connection String

Very often the database connection string is stored in the web.config. The conncetion string can include passwords and other information that shouldn’t be available.

A good practice is to encrypt the connection strings section of the web config.

Encrypt Connection Strings section of the web.config

Using IIS manager click on your application and then click on MachineKey.

machinekey screenshot

Untick “Automatically generate at runtime” for Validation key and Decryption key and click on Generate Keys. IIS will need this keys to decrypt your encrypted config section.

machinekey screenshot

To Encrypt the ConnectionStrings section of the web config we need to use aspnet_regiis program.

Open the “Visual Studio Tools” folder (type Visual Studio Tools in Search Windows) and open Developer Command Prompt for VS2013 (note: launch it as administrator)

The command to encrypt your section is the following

aspnet_regiis -pe "connectionStrings" -app "/yourappname" -prov "RsaProtectedConfigurationProvider"

where prov is the encrytpion provider, you can use DPAPIProtectedConfigurationProvider as well (it uses the windows data protection api), but it won’t work on multiple servers.

If you want to encrypt the configuration section of the web.config using the physical directory (not virtual), use the -pef option:

aspnet_regiis -pef "connectionStrings" "C:\yourpath\yourapp" -prov "RsaProtectedConfigurationProvider"

To decrypt the encrypted section:

aspnet_regiis -pd "connectionStrings" -app "/yourappname"