Encrypting External Configuration Files Using Protected Configuration/DPAPI


Oct 12, 2007

In ASP.NET 2.0, the Protected Configuration functionality can be used to automatically encrypt and decrypt sections of the Web.config file. This is useful for keeping sensitive data like connection strings and cryptographic keys secret from internal personnel who require access to other areas of the configuration file.

Web.config files contain application level configuration, and they are often deployed with the code, from development/testing/staging environments to production environments. Because secrets like connection string should be different in production, the Web.config file has to be modified. However, another piece of functionality, the configSource attribute or the appSettings element, allows configuration sections in Web.config to be located in external files.

These two functionalities work just fine together. This makes deployment easier because secrets can be stored statically and encrypted on each machine, or just the production machine, plus the Web.config file doesn’t need to be modified each time.

Example

[MISSING IMAGE]

connectionStrings section in Web.config (staging and production) refers to external source

[MISSING IMAGE]

Staging connection string defined in connectionString.config (staging)

[MISSING IMAGE]

Production connection string defined in connectionString.config (production)

[MISSING IMAGE]

Encrypt the connectionStrings section for the application (production) using aspnet_regiis

[MISSING IMAGE]

Encrypted connectionStrings setting connectionStrings.config (production)

Now, the Web.config file can be deployed without overwriting the connectionStrings attribute, and the production database password is encrypted! It’s the best of both worlds – security and convenience playing nicely. Just remember not to deploy the connectionString.config file.