Thursday, May 31, 2012

How to Encrypt and Decrypt web.config using aspnet_regiis

 

Encrypting and decrypting connection string and the web.config is one of the very important task we have to do when we deploy the application in the server. The main reason and the importance of this task is because once you deploy the application with clear text anyone who has permission to access the server can open your web.config and will be able to see the user id and password used to connect to your database.

There are many ways you can encrypt your web.config. Also there are many algorithms available to encrypt your connection string or web.config elements.

Here we will see a very simple method using aspnet_regiis to encrypt and decrypt connectionString element.

First we will have a look at the connectionStrings in web.config

Encrypt Connection String

Below is the command you will be executing to encrypt the connectionStrings.

C:\Windows\Microsoft.NET\Framework\v4.0.30319>aspnet_regiis -pef connectionStrings "C:\Encrypt"

Encrypt Connection String 1

In the above command,  connectionStrings is the element we are encrypting, you may change this if you have appSettings or any other section you wanted to encrypt. Also the path C:\Encrypt is the path where I kept the web.config file. It should be your application path where your web.config exists.

Now we will see after encryption how our connectionStrings looks like by opening our web.config.

Decrypt ConnectionString

You can see that our encrypt command added many keys and the connectionString is completely encrypted which you can not read at all.

Decrypt web.config

Ok, now we will move on to decrypting part of the same connectionStrings. Advantage of this approach is, you don’t need to write any specific code to decrypt the connection string. When you access the connection string form your code behind you will get the connection string in encrypted format.

Below is the command you will be executing to decrypt the ConnectionSteings in case you wanted to read the data in clear text format.

C:\Windows\Microsoft.NET\Framework\v4.0.30319>aspnet_regiis -pdf connectionStrings "C:\Encrypt"

Decrypt ConnectionString 1

Explanation of the above command is same as the one I have given it for encrypting. Now after executing above command you will see the clear text conectionStrings in your web.config.

I hope you are very clear about the idea and concept regarding encrypt and decrypt connectionString. If you still need some more explanation you can read it form MSDN

2 comments:

Anonymous said...

So what prevents the user who could previously view web.config from running the decrypt code ?

Raj said...

Well the ecryption uses a machine sepcific key to encrypt the config file. To decrypt you either need the key or access to the machine where it was originally encrypted.