Microsoft & .NETVisual BasicEncrypt Connection Strings in VS 2005 .config Files

Encrypt Connection Strings in VS 2005 .config Files

Developer.com content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More.

In present editions of .NET, you can build connections with a .udl file, and copy and paste into a .config file. If you cleverly decided to encrypt your connection string, you could use the DataProtection (DPAPI) wrapper created in “Encrypt DataSets for Offline Storage“. All of these capabilities still exist, but they have been consolidated and will be easier to use in Visual Studio 2005—once you know where the changes were made.

This article shows you how to add a connection string to your app.config file in Visual Studio 2005, encrypt that connection string, and introduce a tool for automatically encrypting connection strings for ASP.NET.

Adding a Connection String to Project Settings

With so much technology changing all the time, it is easy to have a Homer Simpson moment—D’oh!—and later realize you did something the old way when a new easier way exists. I do this all the time and am sure I am not the only one. (I hate when that happens.) Project settings and .config files will provide ample opportunity for Homer moments in the near future.

In Visual Studio 2005, Microsoft is increasing a reliance on XML but seems to be moving away from the requirement that you have to write XML directly to use it. XML makes a better storage medium than an author medium—that is, it is great to use but unnatural to write—and in Visual Studio 2005 the XML in an App.config file can be managed by Project Properties pages. For example, to add elements that were traditionally application settings we can select Project|<projectname> Properties, change to the Settings tab and click to begin adding settings using a visual designer instead of writing XML.

For example, to add a connection string, follow these steps:

  1. Ensuring the Settings tab of the project properties page is open, add a new item named ConnectionString.
  2. Change the type to (Connection String) and the scope to Application.
  3. In the Value column, click the elided button to open the connection string designer (see Figure 1).
  4. Define and test the connection string as you would using the Data Link Properties editor defined for .udl files. Click OK.

Figure 1: The integrated connection string builder is used like Data Link Properties editor.

After completing Step 4, the Value field—see Figure 2—will contain the connection string for your server. (The actual server doesn’t matter, but I used the Northwind sample database for SQL Server for the example.)

Figure 2: The Settings tab is used to manage elements in configuration files.

Reading the Connection String

We used to use System.Configuration.ConfigurationSettings.AppSettings and a custom tag to store connection strings. You can still do that, but that is the old (D’oh!) way. ConfigurationSettings is deprecated and there is a new section named ConnectionStrings and a coinciding collection in the framework to read these strings.

In Visual Studio 2005, you will use these steps to read connection strings:

  1. Add a reference to System.Configuration.dll.
  2. Add an Imports System.Configuration statement.
  3. Invoke ConfigurationManager.ConnectionStrings(“full path to connection string”).ConnectionString to read a specific connection string.

In Step 3, you will note that you are using the ConfigurationManager instead of ConfigurationSettings, which has been deprecated. The full path is the namespace.Settings.name. By default, the namespace will be the same as your assembly name or default namespace in VB. Settings is a literal value, and name is the name you entered in the Settings page for that connection string. I named mine ConnectionString. Thus, given a sample program EncryptConnectionString, the full path will be EncryptConnectionString.Settings.ConnectionString.

Encrypting the Connection String

Next, you will want to encrypt the connection string. The problem in the past has been that everyone had to define an encryption scheme and a GUI for encrypting the data. While this isn’t automatic in Visual Studio—yet, but it should be—it is pretty easy.

Note: A good feature for Visual Studio would be a checkbox or something that indicates that a value should be encrypted and the ConfigurationManager would automatically encrypt and decrypt this data. (Of course, figuring out who has permission to decrypt might be an issue here.)

The first thing you need to do is grab the aforementioned DPAPI wrapper class and add that to your project. (Copy and paste it right from the article online; I tested this approach and it works perfectly.) Next, you will use the Object Test Bench tool to create your GUI for you.

In “Object Test Bench: Cool New VS 2005 Feature“, you learned that you can invoke instance and static methods in Visual Studio 2005. For methods that accept arguments, Visual Studio will create a simple GUI for you.

The Encrypt method is a public module method that is the same thing as a shared class method. To encrypt the connection string, right-click in the Value field of the Settings tab, select Edit Cell, and copy the connection string value. Invoke the static method Encrypt (from a class diagram or the class view explorer), paste the unencrypted connection string in the Invoke Method dialog (see Figure 3), pick a value for the store parameter, and click OK.

Figure 3: Let Visual Studio create utility dialogs automatically through the Object Test Bench.

After you click OK, the return value can be copied or stored in the Object Test Bench. Replace the unencrypted value in the Settings page with the encrypted value and you are finished. Just remember to call the Decrypt method when you read the connection string with the ConfigurationManager. The code in Listing 1 demonstrates how to grab and decrypt the connection string in your code.

Listing 1: A sample that demonstrates how to use the new ConfigurationManager.

Imports System.Configuration
Module Module1

   Sub Main()
      Dim connectionString As String = _
         ConfigurationManager.ConnectionStrings( _
         "EncryptedConnectionString.Settings.ConnectionString") _
         .ConnectionString

      Console.WriteLine(connectionString)

      Dim encrypted As String = Encrypt(connectionString, Store.User)

      Dim unencrypted As String = Decrypt(encrypted, Store.User)

      Console.WriteLine("Results: " & (unencrypted = connectionString))
      Console.ReadLine()

   End Sub

End Module

Encrypting Configuration Sections in ASP.NET 2.0

Don’t spend time re-inventing every wheel. It really is worth the time to figure out what features are available and usually the investment of a few books and several days reading is worth the investment. Although I have a vested interest in your buying books, I firmly believe the investment will pay off.

One such return can be had by reading this article. If you need to encrypt connection strings for ASP.NET applications, in web.config files, aspnet_regiis -pe section_name will do the trick for you. You can read more about this feature of ASP.NET 2.0 in the integrated help topic ms-help://MS.VSCC.v80/MS.MSDNQTR.v80.en/MS.MSDN.v80/
MS.VisualStudio.v80.en/dv_aspnetcon/html/51cdfe5b-9d82-458c-94ff-c551c4f38ed1.htm.

Easier Development, Tougher Demands

The difficulty with software development is that while things continually get easier, customer demands continually become more complex. For example, although we have an easy way to author application settings without hand-coding XML, it is no longer acceptable to publish unencrypted data such as connection strings. This article has introduced new aspects of Visual Studio, showing you how to leverage those aspects to complete routine, important tasks.

About the Author

Paul Kimmel is the VB Today columnist for www.codeguru.com and has written several books on object-oriented programming and .NET. Check out his book Visual Basic .NET Power Coding from Addison-Wesley and his upcoming book UML DeMystified from McGraw-Hill/Osborne (Spring 2005). Paul is also the founder and chief architect for Software Conceptions, Inc., founded 1990. He is available to help design and build software worldwide. You may contact him for consulting opportunities or technology questions at pkimmel@softconcepts.com.

If you are interested in joining, sponsoring a meeting, or posting a job, check out www.glugnet.org, the Web page of the Greater Lansing area Users Group for .NET.

Copyright © 2005 by Paul T. Kimmel. All Rights Reserved.

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Latest Posts

Related Stories