Click here to Skip to main content
Licence CPOL
First Posted 8 Sep 2007
Views 92,102
Downloads 1,600
Bookmarked 49 times

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

By | 8 Sep 2007 | Article
Encrypt and Decrypt ConnectionString in app.config and/or web.config!

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. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
GeneralMy vote of 5 Pinmembermanoj kumar choubey23:28 29 Mar '12  
Questiondidn't work for me, full of bugs. PinmemberMember 238286816:52 28 Jun '11  
GeneralMy vote of 5 PinmemberVirtualIdeal16:21 7 Dec '10  
GeneralMy vote of 5 PinmemberReyhaneh8:35 22 Sep '10  
QuestionWhat's the difference? PinmemberGreizzerland7:19 18 Jan '10  
GeneralSeems unsecure Pinmemberxr280xr6:14 2 Mar '09  
GeneralRe: Seems unsecure PinmemberCStroliaDavis11:34 24 Jun '09  
QuestionCan not be declassified Pinmemberlvxiaojiang17:54 26 Jun '08  
QuestionHow can I apply it on Window service Pinmemberbmwgamil11:16 18 Oct '07  
NewsTwo other related encryption articles in CodeProject ... PinmemberTony Selke7:05 27 Sep '07  
GeneralVeiled Attempt at Social Engineering PinmemberDumpsterJuice4:30 9 Sep '07  
GeneralRe: Veiled Attempt at Social Engineering PinmemberDariush Tasdighi22:03 9 Sep '07  
GeneralRe: Veiled Attempt at Social Engineering PinmemberDumpsterJuice1:04 10 Sep '07  
GeneralTopic already covered PinmemberVasudevan Deepak Kumar2:47 9 Sep '07  
This topic has already been covered long back. Check out this article:
 
http://www.codeproject.com/aspnet/secure_connectionstrings.asp[^]
 

 
Vasudevan Deepak Kumar
Personal Homepage
Tech Gossips

GeneralRe: Topic already covered PinmemberDariush Tasdighi3:40 9 Sep '07  

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

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

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