Encrypting connectionstring or any section in web.config (Codesmith, Nettiers)

We are using NetTiers templates with Codesmith tool to generate the code base for our database. The autogenerated code base uses the SQL connection string in clear text format. We realized that it is a showstopper only after our deployment team pointed it out. To our surprise we were able to find a quick solution without having to change or edit the autogenerated code. Since NetTiers uses Microsoft Enterprise library to generate the code the inherent code uses the EntLib dataaccess layer thus paving a way to an easy implementation of encryption.

OK enough of the story, below are the steps to follow:

Go to http://www.orcsweb.com/articles/aspnetmachinekey.aspx and generate a machine key. The machine key looks something like below:

<machineKey validationKey=‘9A4A4ACEB1C1B352050B73FF641FACD00756C125E256C170ACA2F307059E00D05FA3BDA8BA2BB432D88C6912E5A9D33E0A2EC55AA272959CEA075E81660D9B4B’ decryptionKey=‘F1E5AFF42211D3503158EFA109704EE756EFDD996010966F’ validation=‘SHA1’/>

Copy this machine key text to web.config under the system.web tag.

<?xml version=“1.0”?> <configuration> <appSettings/> <connectionStrings/> <system.web> <machineKey validationKey=‘9A4A4ACEB1C1B352050B73FF641FACD00756C125E256C170ACA2F307059E00D05FA3BDA8BA2BB432D88C6912E5A9D33E0A2EC55AA272959CEA075E81660D9B4B’ decryptionKey=‘F1E5AFF42211D3503158EFA109704EE756EFDD996010966F’ validation=‘SHA1’/> </system.web> </configuration>

Add your connection string which has to be encrypted to the connectionStrings section. At the command prompt, change the directory to the .NET Framework version 2.0 directory by typing the following command:

cd \WINDOWS\Microsoft.Net\Framework\v2.0.*

Run the following commands: If your web application is hosted as a website on IIS then go with:

aspnet_regiis -pe “connectionStrings” -app “/MyApplication” aspnet_regiis -pe “system.web/machineKey” -app “/MyApplication”

If your web application is a project in your visual studio and you have the path the website folder then go with:

aspnet_regiis -pef “connectionStrings” “C:\trunk\Dev\SampleWebApp” aspnet_regiis -pef “system.web/machineKey” “C:\trunk\Dev\SampleWebApp”

That is it! if you open web.config you will see the section encrypted. If you are using Enterprise library application blocks for your data access layer then you dont have to do anything else to make your project understand the encrypted stuff.

In any other case, please read http://msdn.microsoft.com/en-us/library/dtkwfdky(VS.80).aspx for more details on how to use the encrypted stuff in your application.

About the author

I work with customers helping them achieve more using Microsoft Technologies. I am in my 9th year with Microsoft as of March 2020. I get to work with really smart people (both at Microsoft and Customers). Helping customers, removing any blockers, rapid prototyping is my core work.