Click here to Skip to main content
Click here to Skip to main content

Encrypt and Decrypt ConnectionString in app.config and/or web.config!

By , 8 Sep 2007
 

Introduction

In Windows/Web based applications, it's not rational for you to put your ConnectionString in the native/normal format! This is because anybody can see your userID/username and password!.

In this article, I want to teach you how to encrypt ConnectionString and decrypt it as you wish.

Background

This feature was born in .NET Framework 2.0 (Visual Studio 2005).

Using the Code

First of all, we suggest you to create a static class with the name Utilities and put the below functions in it. After all, you can call just two functions for encryption and decryption of your connection string.

namespace DT.Security
{
    public static class Utilities
    {
        public static void ProtectConnectionString()
        {
            ToggleConnectionStringProtection
		(System.Windows.Forms.Application.ExecutablePath, true);
        }

        public static void UnprotectConnectionString()
        {
            ToggleConnectionStringProtection
		(System.Windows.Forms.Application.ExecutablePath, false);
        }

        private static void ToggleConnectionStringProtection
				(string pathName, bool protect)
        {
            // Define the Dpapi provider name.
            string strProvider = "DataProtectionConfigurationProvider";
            // string strProvider = "RSAProtectedConfigurationProvider";

            System.Configuration.Configuration oConfiguration = null;
            System.Configuration.ConnectionStringsSection oSection = null;

            try
            {
                // Open the configuration file and retrieve 
	       // the connectionStrings section.

                // For Web!
                // oConfiguration = System.Web.Configuration.
	       //                  WebConfigurationManager.OpenWebConfiguration("~");

                // For Windows!
                // Takes the executable file name without the config extension.
                oConfiguration = System.Configuration.ConfigurationManager.
                                                OpenExeConfiguration(pathName);

                if (oConfiguration != null)
                {
                    bool blnChanged = false;

                    oSection = oConfiguration.GetSection("connectionStrings") as
                System.Configuration.ConnectionStringsSection;

                    if (oSection != null)
                    {
                        if ((!(oSection.ElementInformation.IsLocked)) &&
                (!(oSection.SectionInformation.IsLocked)))
                        {
                            if (protect)
                            {
                                if (!(oSection.SectionInformation.IsProtected))
                                {
                                    blnChanged = true;

                                    // Encrypt the section.
                                    oSection.SectionInformation.ProtectSection
								(strProvider);
                                }
                            }
                            else
                            {
                                if (oSection.SectionInformation.IsProtected)
                                {
                                    blnChanged = true;

                                    // Remove encryption.
                                    oSection.SectionInformation.UnprotectSection();
                                }
                            }
                        }

                        if (blnChanged)
                        {
                            // Indicates whether the associated configuration section 
                            // will be saved even if it has not been modified.
                            oSection.SectionInformation.ForceSave = true;

                            // Save the current configuration.
                            oConfiguration.Save();
                        }
                    }
                }
            }
            catch (System.Exception ex)
            {
                throw (ex);
            }
            finally
            {
            }
        }
    }
}

Points of Interest

After I learned this feature, I used it in all of my Windows/Web based applications!

History

  • 8th September, 2007: First release

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Dariush Tasdighi
Web Developer
Iran (Islamic Republic Of) Iran (Islamic Republic Of)
Member
I'm experienced in below items:
 
- XML 1.0
- CSS 2.0
- ASP 3.0
- HTML 4.01
- XHTML 1.0
- Javascript 1.5
- .NET Framework 1.1/2.0
- Microsoft Office 2000/XP
- Microsoft Visual Basic 6
- Microsoft SQL Server 2000/2005
- Microsoft C#.NET (Windows Based)
- Microsoft C#.NET (XML Web Service)
- Microsoft C#.NET (Web Based = ASP.NET)
 
My Site URLs:
http://www.IranianExperts.ir
http://www.IranianExperts.com
 
My Yahoo Group URL: http://groups.yahoo.com/group/iranianexperts
 
Mobile: 0098-912-108-7461
Address: Tehran, Tehran, Iran

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
Questionخیلی استادی. استادmemberhamed elahi16 Mar '13 - 1:58 
سلام. از اینکه می بینم استادم اینقدر متواضعانه تجربیاتش رو اینقدر دقیق و بسور رایگان روی این سایت میگذاره بخ خودم افتخار می کنم که شاگرد همچین استادی بودم. Wink | ;) Wink | ;)
خیلی حال کردم وقتی اسم شما رو به عنوان مولف این پروژه دیدم هرچند برای شما خیلی ساده و کوچیکه اما برای من بسیار لذت بخش بود
QuestionTwo different computer can't read the same encrypted filememberbiczek26 Jan '13 - 6:02 
I have problem. I was supposing it will work but is not working.
Well, I have windows form application that use connection string to connect to DB. I encrypted my app.config file and I install the program on the another computer. When I try to start my program I receive error: "DataProtectionConfigurationProvider... HRESULT 0X800900B... key is invalid". It's possible to encrypt file on one computer and used it on another one??
GeneralMy vote of 5membermanoj kumar choubey29 Mar '12 - 23:28 
Nice
Questiondidn't work for me, full of bugs.memberMember 238286828 Jun '11 - 16:52 
didn't work for me, full of bugs.
GeneralMy vote of 5memberVirtualIdeal7 Dec '10 - 16:21 
Excellent,thank you sir,I could use it to protect my infomation
GeneralMy vote of 5memberReyhaneh22 Sep '10 - 8:35 
I was your student in Iran and now I work in one of the most favourite company in Canada. I always use your comments. Thanks for everything, I have learnt a lot from you.
QuestionWhat's the difference?memberGreizzerland18 Jan '10 - 7:19 
Please tell me what's the difference of your code with the original from MSDN
http://msdn.microsoft.com/en-us/library/89211k9b(VS.80).aspx[^]
GeneralSeems unsecurememberxr280xr2 Mar '09 - 6:14 
Hi,
Thanks for the article. I may be missing something but this seems unsecure (whether you declare your method as public or not). We're not specifying a key for the encryption so what key is this using? It does not seem very private when you can just run aspnet_iisreg -pdf to decrypt your configuration file.
 
On a side note you can also use aspnet_iisreg -pef to accomplish the same thing as the code above.
GeneralRe: Seems unsecurememberCStroliaDavis24 Jun '09 - 11:34 
Hey xr,
 
The security provided by encrypting web.config is experienced, primarily in the following ways:
1. By preventing external users from seeing private information in web.config files that are exposed to the public (usually unintentionally).
2. This helps prevent leakage of information through privileged users who are basically honest.
 
In the first case, a common scenario is when the web.config is updated, sometimes, inexperienced administrators will backup the old configuration file with a name like web.config.old. or .bak or something like that. A malicious user will often try out these types of variations, since these are not (or at least weren't) hidden by IIS. This would give them a text file showing them many of the configuration settings.
 
As for people who have direct access to the computer/server where the web.config resides, it is actually quite easy to decrypt this information. Ideally, the only people who have access to these files are people who are authorized to view them. In any case, it is still helpful to have that extra layer of protection that prevents these users from seeing the userName and password combinations for static accounts. Even though, they could get the information if they wanted to, as a general rule, they don't have to see that information if they are in the configuration file, modifying non sensitive values. If a malicious user were to try to get them to divulge sensitive information that normally resides in web.config, chances are that information would be unknown, and the process necessary to get that information might take just enough effort to wake them up to what's happening.
 
Make no mistake, many malicious users are experts at social engineering and can often, easily get sensitive information from people who are not paying attention. Adding that extra layer of security can help to minimize the risk a little.
 
By the way, the key is generally created automatically on whatever the machine the web site is running on. It is possible to generate specific keys for combinations of the machine, user or website on any given machine, and these can be set to behave a certain way within the machine.config file, or even influenced (to some extent) in the web.config files themselves.
 
By default, a web.config that is encrypted on one machine cannot be decrypted on a different machine. It is possible to have a key that is shared across multiple machines so that web.config files can be copied without decrypting them first.
 
I don't recall, but I believe the same key is, or can be, used for encrypting the user tokens when a user authenticates to a particular web site. This is where a shared key can be more beneficial, since a user may move from one server to another in a web farm. When they are logged into a web site it would be necessary for the other servers to be able to determine if the user is already logged in or not.
 
I hope this information is useful
QuestionCan not be declassifiedmemberlvxiaojiang26 Jun '08 - 17:54 
Can not be declassified
f***!!
 
value="y7gSjVQTKVBxIXgOQEw35l2RigS7eVrEUQ7rrUBOXalWHMHjm6L4faqmR2suT4FQVDV7G2Wetnw9/v9MDc7LrRwBvAQfUSLnPJq7ZkdOdA/1lbxK/TUG+d0Zx1Tyork2jrFOdDXcxIAHko9BY1ihjoZ5TBshgzYQ411AGo4pEZ/O1hyvZ1Odc1xAATOkzeJ5"
 
Cry | :((

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web01 | 2.6.130523.1 | Last Updated 8 Sep 2007
Article Copyright 2007 by Dariush Tasdighi
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid