November 23, 2012

Encrypting and Decrypting Web.config Sections in .NET 4.0

Sometimes we need to store a lot of confidential data in web.config in our production environment (for examples: username\password for impersonation or for connect to database, some appSettings, etc.). And it is not secure to store that as clear text, obviously some people on your server may have access to this file and steal your data.
.NET Framework gives us a good solution. We can encrypt configuration sections in web.config files.

How to Encrypt a section
1. Find aspnet_regiis.exe on your PC.
2. Grand access to ApplicationPool Identity for NetFrameworkConfigurationKey RSA key contanier:
aspnet_regiis -pa "NetFrameworkConfigurationKey" "<ApplicationPool Identity user>"
3. Encrypt a section:
aspnet_regiis -pe "<Path/to/section>" -app "/<YouWebApplication>"
*All these commands require administrative privileges, so if you want to use command prompt for it - don't forget to 'run as administrator'. Otherwise you will get a lot of very strange errors.

It looks very simple...
But let's consider all these steps in more detail.

November 1, 2012

Settings in .NET are easy

As I said 'few' days ago, today I`ll tell you about Settings files.
Settings files are designed to make our life simpler during working with application and user configuration.

A bit theory

Settings file consists of few parts in our project.
  1. Settings file (auto generated class derived from ApplicationSettingsBase).
  2. app.config (contains default values for all options).
Generated setting file derived from ApplcationSettingsBase already contains initialized static instances of all our options. We don't need to create this class manually and load any data, because it has already been created and loaded. And it is ready to work.

All settings have next properties:
  • Name (this is the name of our setting): with this name we will have automatically generated property in Settings class.
  • Type (the type of our setting): there are a lot of predefined types like string, int, etc., but you can also set your custom type.
  • Value (this is default value for setting).
  • Scope: all settings should be in one of two scopes (User or Application). It represents how our setting will be accessed at runtime.