Encryption of connection strings in .NET and official kick off for the blog

So basically i will kick off this blog for real before Joakim gets the chance. This post is about an interesting thing that enhances the security when working with connection strings.
When working against databases it is inevitable to use connection strings from config file. There is a way of encrypting these in an easy way using a command:
aspnet_regiis -pe "connectionStrings" -app "/myWebsite" -prov "provider"
This is pretty easy and straight forward. However, sometimes you wan't to be able to do this programatically. It can sometimes be nice to have an app that encrypts and decrypts the strings. so you don't need to bother with commands. I have chosen to show how to do this when you have you're custom provider configuration directly in the config file that holds the connection strings (the stuff that says what type of encryption you want to use and how, for more information on what you can choos please refer to MSDN). You can however use the configuration from machine.config as well. So if we start with looking at the configuration of the provider:

type="System.Configuration.RsaProtectedConfigurationProvider,System.Configuration, Version=,
Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"description="Uses RsaCryptoServiceProvider to
      encrypt and decrypt
useMachineContainer="false"useOAEP="false" />

I will not go into details on what each attribute in the add element sets. The important attribute for this article is useMachineContainer.This attribute declare whether to encrypt the strings for the specific machine or, if set to false, for the specific user executing the encryption. .NET creates a key bound to either the machine or the user that later on will be used to decrypt or encrypt the strings. This way only that specific machine or user can use the connectionstrings.
Of course, this implies that your application only uses one machine or user to access the database.
Now that we have the configuration set in the config file containing the connection strings let's proceed with the actual encryption. Our actual connection strings look like this:
<clear />
addname="LocalSqlServer"connectionString="data source=.\SQLEXPRESS;Integrated
Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true"
providerName="System.Data.SqlClient" />
We start with opening the actual configuration file first.
// Map to the application configuration file.
ExeConfigurationFileMap configFile= newExeConfigurationFileMap();
// Set which file to encrypt
configFile.ExeConfigFilename = "C:\mywebpage\Web.config";
//this object is a represantion of the config-file
Configuration config= null;
//sets the actual configfile to be used, this file is located elsewhere so the
//OpenMappedExeConfiguration is used, else if the local config file is to be used
//OpenExeConfiguration should be used to set the Configuration object.
config = ConfigurationManager.OpenMappedExeconfiguration(configFile, ConfigurationUserLevel.None);

When this is done we need to get the section that we wan't to protect. The class Configuration has a property that gives the connectionstrings.
// Get the section to protect.
ConfigurationSection section = config.ConnectionStrings;

After that we just have to check if the section is either already encrypted or if it's locked for some reason. The we simply use the method section.SectionInformation.ProtectSection to protect the strings with the provider that we set in the config file. If a provider from machine.config is to be used simply declare that one instead.
//check if the section already is encrypted or if it's locked
if ((section.SectionInformation.IsProtected == false) && (section.ElementInformation.IsLocked == false))
// Save the encrypted section
   section.SectionInformation.ForceSave = true;
Now the connection string section in the config file will look like this:
EncryptionMethodAlgorithm="http://www.w3.org/2001/04/xmlenc#tripledes-cbc" />
EncryptionMethodAlgorithm="http://www.w3.org/2001/04/xmlenc#rsa-1_5" />
KeyName>Rsa Key</KeyName>


To decrypt it simply call the method section.SectionInformation.UnprotectSection instead of section.SectionInformation.ProtectSection. Be however sure to do this using the same machine or user that encrypted the strings. Otherwise it won't work.

Basically the key here is to use same user for encrypting and decrypting. You don't have to create keys on your own or hassle with other stuff. Just make sure that

/ 1 نظر / 63 بازدید
Wondermage Gallery

سلام دوست عزيز [گل] گالري عکس Wondermage با بيش از 1100 تصوير با کيفيت در 11 بخش مجزا شما را به ديدن اين تصاوير دعوت مي کند. اميدوارم از تصاوير خوشتان بيايد و ما را از نظراتتان محروم نکنيد. در صورت تمايل Wondermage را با نامي دلخواه که مفهوم گالري را برساند در صفحه خود لينک کرده و به ما اطلاع دهيد تا به عنوان تشکري کوچک متقابلا در دايرکتوري ما لينک شويد. به دوستانتان هم اطلاع دهيد، شايد اوقات خوبي را در گالري سپري کنند. اميدوارم موفق باشيد و از تصاوير لذت ببريد.