SARNIL
I will try not get a Twitter account!

Encrypt ConnectionStrings in App.config

October 31, 2007 12:45 by sarnil

Working on one of our windows forms projects recently, I needed to encrypt the database connection strings in the App.config file. With a few minutes of googling, I found exactly what I was looking for here on MSDN (http://msdn2.microsoft.com/en-us/library/89211k9b(VS.80).aspx).

The code that did the trick for me is as below:

 

static void ToggleConfigEncryption(string exeConfigName)
{
// Takes the executable file name without the
// .config extension.
try
{
// Open the configuration file and retrieve 
// the connectionStrings section.
Configuration config = ConfigurationManager.
OpenExeConfiguration(exeConfigName);
ConnectionStringsSection section =
config.GetSection("connectionStrings")
as ConnectionStringsSection;
if (section.SectionInformation.IsProtected)
{
// Remove encryption.
section.SectionInformation.UnprotectSection();
}
else
{
// Encrypt the section.
section.SectionInformation.ProtectSection(
"DataProtectionConfigurationProvider");
}
// Save the current configuration.
config.Save();
Console.WriteLine("Protected={0}",
section.SectionInformation.IsProtected);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}

 

I placed the code above in a console application and which requires just one parameter i.e. the application executable file name.

My console application, Encryptor, is available for download from here. To use it:

  1. Place Encryptor in the same directory as your application executable and the config file.
  2. Run Encryptor from the command line as:

                Encryptor <ApplicationExeFileName.exe>

As shown in the code above, Encryptor is a toggle application. That means, if you run it once, it will encrypt the connectionString and run it the second time and it will decrypt it.

That's it! Enjoy.

PS: If you want my Encryptor VS2005 Project, just put up a comment and I shall make arrangements ;-) 


Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5
Tags: , ,
Categories: Tech
Actions: E-mail | Permalink | Comments (0) | Comment RSSRSS comment feed

Related posts

Add comment


(Will show your Gravatar icon)  

[b][/b] - [i][/i] - [u][/u]- [quote][/quote]



Live preview

September 6. 2008 03:11