Encrypting and Decrypting connection strings in web.config

In an ASP.NET website or web application, connection string for connection to a database server are stored in web.config file. It becomes easy to manage and access the connection strings from a central file accessible to all ASP.NET pages. But the security and privacy of the connection strings are higly important. It is a good idea to protect the connection strings in web.config by encrypting them. ASP.NET gives a built in way to do this. We can use RSAProtectedConfigurationProvider to encrypt the connection strings using User Level Key and Machine Level Key. User Level Key is used when you are running your application on a shared server and Machine Level Key is used when you are running your application on dedicated server. In this article we will see how to encrypt using Machine Level Key. In the web.config following is the section having all connection string:

<CONNECTIONSTRINGS>

<ADD connectionString="Initial Catalog=myDB; Data source=(loca);Integrated security=SSPI;" name="conString1" />

</CONNECTIONSTRINGS>

After storing all connection strings, go to the Visual Studio 2005 Command Prompt.
(Start->Programs->Microsoft Visual Studio 2005->Visual Studio 2005 Tools->Command Prompt)

There write this command on command prompt:

aspnet_regiis -pef "connectionStrings" "c:\myProjects\website1"

Where the "c:\myProjects\website1" is the physical path of your website. Review the web.config after this. You will find it encrypted.

Later on you can access this connection string as normal way in your pages:

[VB.NET]
ConfigurationManager.ConnectionStrings("conString1").ConnectionString

[C#.NET]
ConfigurationManager.ConnectionStrings["conString1"].ConnectionString

To revert the web.config connection strings back to plain text:

aspnet_regiis -pdf "connectionStrings" "c:\myProjects\website1"

Ebook Download
View all
Learn
View all