Encrypting and decrypting sensitive data in your web.config files using Protected configuration - Part III
In the last 2 posts, Part I and Part II I wrote the general idea and how to implement the protected configuration.The reason I started to learn this subject was actually the need to encrypt application blocks section with Entlib 4.1. So here is how to are implementing the following scenario:
Suppose you have an application using the Entlib. And suppose you are using the DAAB. The DAAB contains in it's configuration a connection string that you wish to encrypt. Not only that, you also wish to deploy your application to several servers ( A web farm).
Here are the steps to accomplish this mission:
1. Create a web application , lets call it EncryptTest. This application has only a single page. default.aspx. Add an application to your IIS and map it to the created web application.
2. Right click the web.config and open the Entlib configuration tool.
3. Add the Data Access application block and set some connection string.
4. Create a new key container using the cmd command :
aspnet_regiis -pc "MySampleKeys"–exp
5. Open the machine.config file and add the key key :
<add name="RsaProtectedConfigurationProviderqqq" type="System.Configuration.RsaProtectedConfigurationProvider,System.Configuration, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" description="Uses RsaCryptoServiceProvider to encrypt and decrypt" keyContainerName="MySampleKeys" cspProviderName="" useMachineContainer="true" useOAEP="false"/>
Notice that the name is a new name and that the keyContainerName is the name of the key container we created at step 4.
5. Go back to the configuration tool of the Entlib and in the properties of the DAAB choose the new name I in my sample this is the RsaProtectedConfigurationProviderqqq).The entlib has a design time support , so if you cant see the new name , simply close the IDE and reopen it.
6. Now in your code check that everything works. For instance run these 2 lines of code in the Page_Load event of your app:
Microsoft.Practices.EnterpriseLibrary.Data.Database oDB = Microsoft.Practices.EnterpriseLibrary.Data.DatabaseFactory.CreateDatabase("MyDSN");
Response.Write(oDB.ConnectionString);
7. Export the key container using the command:
aspnet_regiis -px "MySampleKeys" keys.xml. You now have an xml file you can import to other computer. Copy this xml file to the servers.
8. Import the key container using the command
aspnet_regiis -pi "MySampleKeys" keys.xml ( specify the path to the keys.xml file).
9. Grant permission to this key container if you need to.
10. Finally add the new entry to the machine.confige as you did in step 5.
Enjoy.