This tutorial will demonstrate how you can encrypt a connection string in the web.config file using ASP.NET 4.0 and C#.

Adding a Database

To demonstrate how to encrypt a connection string, we will need to create a simple web site with a database that we can connect to. At this point I have created a new ASP.NET Empty Web Site. To add the database:

  1. Right click the project in your solution explorer.
  2. Select add ASP.NET folder.
  3. Select App_Data.
  4. Right click the App_Data folder.
  5. Select add new item…
  6. Select a SQL Database.
  7. Name it ‘Database.mdf’.
  8. Click add.

Adding the ConnectionString

Now that our database is setup, we need to add a connection string to it in our Web.Config file. To do this, open up the Web.Config file for editing and add the following code between the and tags:

Encrypting the ConnectionString

Next, we need to add a web form to the project to which we can add some C# code to encrypt the connection string that we have added. To do this:

  1. Right click the project in your solution explorer.
  2. Select add new item…
  3. Select a web form.
  4. Name it ‘Default.aspx’.
  5. Open Default.aspx.cs up for editing.
  6. Add the following code to the Page_Load event method:


Next, all we need to do is load up the web site and ensure that our code to encrypt our connection string has executed. To do this, load up the web site. (Note: If you receive an error about opening the config file, ensure that you are running Microsoft Visual Studio as an administrator.) Once the web site is loaded and our code has executed, open up the Web.Config file again and notice that the connection string we added earlier has been encrypted. It should now look similar to this:

Download Source Files