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:
- Place Encryptor in the same directory as your application executable and the config file.
- 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