I typically store at least one sensitive item in the web.config file: namely, the connection string to my database. There are several ways to protect your web.config file from falling into the wrong hands (for example, you can explicitly forbid ASP .NET from serving .config files or you can redirect users to a “You stink” page using HttpHandlers). But imagine for a moment that the worst happened and that somehow an attacker got hold of your web.config file. Now what? Obviously, we would like it if sensitive parts of the web.config file look like complete gibberish so that the cracker feels like an utter idiot for wasting all the time trying to get the file.

Encrypting the web.config file is, apparently, not only entirely possible but also ridiculously easy. Enter — drumroll please — aspnet_regiis.

All you need to do is type in…

aspnet_regiis -prov DataProtectionConfigurationProvider -pef [the name of the configuration setting that you want to encrypt; for example, connectionStrings] [location of the folder in which your web.config resides; for example, C:Website1]

–prov — what provider to use

–pef [section name] [location of config file] — what section to encrypt (using the provider mentioned above) and the >location of the .config file

...in cmd prompt and wait a couple of seconds while your configuration file gets encrypted. Load up web.config and you should see something like:

<CipherValue>AQAAANCMnd8BFdERjHoAwE/Cl+sBAAAAM85VV82faE2ocurvYx6Z4gmoreincomprehensiblegarbagehereitg6XOFiehAkVwulqACFAAAAEZTASYdjIvoIiAR3yzotHc6z8E5</CipherValue>

Accessing the connection string, however, is no different after you encrypt than before. That is, you would still get your connection string as follows:

string connStr=ConfigurationManager.ConnectionStrings["connStr"].ConnectionString;

Note that it’s also possible to encrypt web.config programmatically (go down to step5).