Click here to Skip to main content
11,709,844 members (48,076 online)
Click here to Skip to main content

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

, 8 Sep 2007 CPOL 132.2K 3.4K 58
Rate this:
Please Sign up or sign in to vote.
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)

Share

About the Author

Dariush Tasdighi
Web Developer Sematec Ins.
Iran (Islamic Republic Of) Iran (Islamic Republic Of)
My experiences are:

HTML 5.0, CSS 3.0
JQuery, Angular JS, Bootstrap

MVC 5.0, WEB API, c#

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

You may also be interested in...

Comments and Discussions

 
QuestionNot working. Pin
sunayv20-Jun-13 0:41
membersunayv20-Jun-13 0:41 
Questionخیلی استادی. استاد Pin
hamed elahi16-Mar-13 1:58
memberhamed elahi16-Mar-13 1:58 
سلام. از اینکه می بینم استادم اینقدر متواضعانه تجربیاتش رو اینقدر دقیق و بسور رایگان روی این سایت میگذاره بخ خودم افتخار می کنم که شاگرد همچین استادی بودم. Wink | ;) Wink | ;)
خیلی حال کردم وقتی اسم شما رو به عنوان مولف این پروژه دیدم هرچند برای شما خیلی ساده و کوچیکه اما برای من بسیار لذت بخش بود
QuestionTwo different computer can't read the same encrypted file Pin
biczek26-Jan-13 6:02
memberbiczek26-Jan-13 6:02 
AnswerRe: Two different computer can't read the same encrypted file Pin
sergiomf20-Aug-14 5:14
membersergiomf20-Aug-14 5:14 
GeneralRe: Two different computer can't read the same encrypted file Pin
me&he22-Mar-15 8:26
memberme&he22-Mar-15 8:26 
GeneralMy vote of 5 Pin
manoj kumar choubey29-Mar-12 23:28
membermanoj kumar choubey29-Mar-12 23:28 
Questiondidn't work for me, full of bugs. Pin
Member 238286828-Jun-11 16:52
memberMember 238286828-Jun-11 16:52 
GeneralMy vote of 5 Pin
VirtualIdeal7-Dec-10 16:21
memberVirtualIdeal7-Dec-10 16:21 
GeneralMy vote of 5 Pin
Reyhaneh22-Sep-10 8:35
memberReyhaneh22-Sep-10 8:35 
QuestionWhat's the difference? Pin
Greizzerland18-Jan-10 7:19
memberGreizzerland18-Jan-10 7:19 
GeneralSeems unsecure Pin
xr280xr2-Mar-09 6:14
memberxr280xr2-Mar-09 6:14 
GeneralRe: Seems unsecure Pin
CStroliaDavis24-Jun-09 11:34
memberCStroliaDavis24-Jun-09 11:34 
QuestionCan not be declassified Pin
lvxiaojiang26-Jun-08 17:54
memberlvxiaojiang26-Jun-08 17:54 
QuestionHow can I apply it on Window service Pin
bmwgamil18-Oct-07 11:16
memberbmwgamil18-Oct-07 11:16 
NewsTwo other related encryption articles in CodeProject ... Pin
Tony Selke27-Sep-07 7:05
memberTony Selke27-Sep-07 7:05 
GeneralVeiled Attempt at Social Engineering Pin
DumpsterJuice9-Sep-07 4:30
memberDumpsterJuice9-Sep-07 4:30 
GeneralRe: Veiled Attempt at Social Engineering Pin
Dariush Tasdighi9-Sep-07 22:03
memberDariush Tasdighi9-Sep-07 22:03 
GeneralRe: Veiled Attempt at Social Engineering Pin
DumpsterJuice10-Sep-07 1:04
memberDumpsterJuice10-Sep-07 1:04 
GeneralTopic already covered Pin
Vasudevan Deepak Kumar9-Sep-07 2:47
memberVasudevan Deepak Kumar9-Sep-07 2:47 
GeneralRe: Topic already covered Pin
Dariush Tasdighi9-Sep-07 3:40
memberDariush Tasdighi9-Sep-07 3:40 

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.

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