Monday, 9 February 2009

Encrypting sections in web.config

Sometimes you want to ensure that your settings (e.g. connection strings) in web.config file are encrypted so nobody except the app iteslf can read/understand them. ASP.Net offers tool called aspnet_regiis which allows that. It can be found in the %WINDOWSDIR%\Microsoft.Net\Framework\version directory.

Let's say we have a web app deployed on IIS called 'MyApp'. The app uses connection string defined in web.config:
<add name="myConnectionString"
connectionString="some connection string"/>

The easiest way to encrypt presented connection string is to invoke following command:
-pe "connectionStrings" -app "/MyApp"

It is also possible to encrypt web.config providing physical path to the application folder rather than app name (e.g. if app is not deployed on IIS):
-pef "connectionStrings"
"physical path to app root folder"

The encrypted information in the web.config can still be accessed by your app without any explicit decoding. Aspnet_regiis tool can be also used to descrypt information, encrypt different sections etc. You can learn more about it here.

If the encoding succeeds but tha app cannot read the encrypted section because of following error:
"Failed to decrypt using provider 'RsaProtectedConfigurationProvider'. Error message from the provider: The RSA key container could not be opened."

you have to add following parameter to your encryption command:
-pe "connectionStrings" -app "/MyApp"
-prov DataProtectionConfigurationProvider

No comments: