Sometimes while developing websites on your dev machine you may want to encrypt sections of your web.config to hide user ids, passwords or other secret type stuff.
To do this by using a particular directory path, as in a file system hosted website, you can use the ASPNET_REGIIS utility with the –pef switch. If you are using IIS to host your site rather than a website, you can use the ASPNET_REGIIS utility with the –pe switch and a –app switch to point to the virtual directory. Either of these two techniques can be used to encrypt using the RSAProtectedConfigurationProvider and the machine key.
In this example I have a website hosted in the file system and will use the –pef switch. My website has an <appSettings> section that contains secrets.

To encrypt this section first open a .Net command prompt.
Execute the ASPNET_REGIIS command using the –pef switch followed by the section name (case sensitive) and the directory path as shown below.

After you hit enter and you will receive a success message:

Returning to the IDE, if you left your web.config displayed, you will be prompted to reload the file.

Click “Yes” to view the web.config again.
Notice that the <appSettings> has changed.

You will see some squiggles concerning invalid child elements. To clear them modify the configuration element by adding a namespace.
xmlns="http://schemas.microsoft.com/.NetConfiguration/v2.0
Below is an example.

The retrieval of the encrypted values is done automatically. In the button click handler shown below, I retrieve the unencrypted value no different than when unencrypted.


To decrypt the web.config file, use the ASPNET_REGIIS command again from a .Net command prompt. The difference is you replace the –pef switch with –pdf switch to decrypt the section.

This command will return your web.config section to its unencrypted format.
Again, if you are not using a website but IIS, you may want to use the ASPNET_REGIIS utility with the –pe switch.
Also the machine key may need permissions granted depending under which identity the site is running. It should be located at \Documents and Settings\All Users\Application Data\Microsoft\Crypto\RSA\MachineKeys.
(BTW Ssuper was either a typo or stands for Super, super. Take your pick)
Technorati Tags: C#,.NET,ASP.NET