Click here to Skip to main content
15,867,997 members
Articles / Programming Languages / C# 4.0
Tip/Trick

Encryption Decryption Connection String for the App.Config File

Rate me:
Please Sign up or sign in to vote.
4.86/5 (23 votes)
14 Jun 2013CPOL2 min read 173.8K   12.2K   56   28
How to develop connection string encryption on the application config file.

Update:- 1. The virsion of the project is upgraded nwo it is in 4.6.1 

 

Introduction

This tip is about encryption of the connection string from app.config file. I searched a lot on the net but was not able to find proper step by step information, which gives us proper instruction on how we can develop this functionality. Then I found a good link on Microsoft forums where I found how we can encrypt the connection string. Then I found it is very easy and can be implemented within no time. This application will generate the Encrypted connection string from the config file. We just need to copy that section and put in our app.config.

Background

If we want to encrypt the Connection with a Windows Application Service while deploying the application to the customer we can use this code.  

Using the Code

This project is very simple. I have used Microsoft’s ConfigSection.SectionInformation.ProtectSection("DataProtectionConfigurationProvider") using this command it will encrypt the config file. What my program does is that it will look for .NET executable file. When you provide the executable file, you will have two options:

  1. Encrypt File
  2. Decrypt File

The below code is very easy to understand. The EncryptConnectionString takes two parameters. We are passing the .NET executable file name which we need to execute. The code will convert the ConnectionString Section in the encrypted format and open the file in Notepad.

C#
public static void EncryptConnectionString(bool encrypt,string fileName)
{
    Configuration configuration = null;
    try
    {
        // Open the configuration file and retrieve the connectionStrings section.
        configuration = ConfigurationManager.OpenExeConfiguration(fileName);
        ConnectionStringsSection configSection = 
        configuration.GetSection("connectionStrings") as ConnectionStringsSection;
        if ((!(configSection.ElementInformation.IsLocked)) && 
        	(!(configSection.SectionInformation.IsLocked)))
        {
            if (encrypt && !configSection.SectionInformation.IsProtected)
            {
                //this line will encrypt the file
                configSection.SectionInformation.ProtectSection
                	("DataProtectionConfigurationProvider");
            }

            if (!encrypt && 
            configSection.SectionInformation.IsProtected)//encrypt is true so encrypt
            {
                //this line will decrypt the file. 
                configSection.SectionInformation.UnprotectSection();
            }
            //re-save the configuration file section
            configSection.SectionInformation.ForceSave = true;
            // Save the current configuration
          
            configuration.Save();
            Process.Start("notepad.exe", configuration.FilePath);
            //configFile.FilePath 
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.ToString());
    }             
}

If you set the config file entry like below:

Section 1

XML
<connectionStrings>
    <add name="SecurePassDataBase" connectionString="Data Source=D-6058;
    Initial Catalog=DEMO_Test;User ID=sysdba;Password=xxxxxx" />
</connectionStrings> 

You will get the encrypted connection string like below:

Section 2

XML
<connectionStrings configProtectionProvider="DataProtectionConfigurationProvider">
    <EncryptedData>
      <CipherData>
        <CipherValue>AQAAANCMnd8BFdERjHoAwE/Cl+sBAAAATeylFe/
        xsUiVdcZvovEYDwQAAAACAAAAAAADZgAAwAAAABAAAABZsoaKP62hL85wpS+O3+
        znAAAAAASAAACgAAAAEAAAAHZ5NcKcDcWuEVDKyU4mz7J4AQAAAILD3fmIimyY2rkEkAdAtRn0dh9tI7+
        Y5+ILciikoSd/y2myUS88vJ59pIf82vOLk/0UwKL8TnHEaFTeX7SJ5par6pW7Pyhu4kKTEMyMUQsZX/
        h8RjNOnt+Q/kZIdqF2YWxFUP0RF3GWirvMNWS3do7IE0WaJ1W3wL+HhalglmKURWIGHsvJlybl+
        EGI8crPnli0W/yMN+fR0P/ndaTY87kR4+0gvKDWzZ/dMh8E7ZtodFzTQ4pjpl5YyRHH/
        Tc3oFUtimCnzXvCVT4ykK6NEQfPiPc5KJW6ajTEEGOrAXTnr9HF2wCRekE3WUVPYkeHRTjtuf
        2hUyvYx4eoGeOIAzFFXxY1GzZqhl8YaHlukZagiTVbfXA6Wh+K0dsAiOPz+wbCT92/
        blgsdkoKSMy8vRqFxAhX8HoW6KbJhsBPOvv36iBr1RecCpzUxWrVssS+wi/JclVfVs0nYb/
        pFidcJwhuwBsS6IzvV1tgrk8F9CUor+6DYHd/ABQAAABZjFi30hPRmKj+pvxFzjeNH+
        Dhhg==</CipherValue>
      </CipherData>
    </EncryptedData>
</connectionStrings>

Just replace Section 1 with Section 2 in your application config file.

You can easily access the connection in your program like below:

C#
string connectionString = ConfigurationManager.ConnectionStrings["SecurePassDataBase"].ToString();

No need to change or do anything else to be able to access the connection string. Hope this code will help you to generate the encryption in your WinForm application.

Acknowledgement

I would like to thank Shreyas Ramdahve who reviews my articles and makes them perfect.

License

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


Written By
Architect
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
PraiseThank you Pin
Rajashan628-Jun-21 3:51
Rajashan628-Jun-21 3:51 
Questionhow to deploy as a network application Pin
Amar zaidi19-May-19 2:57
Amar zaidi19-May-19 2:57 
PraiseNice and easy Pin
Waqas Ahmed 201024-Mar-18 22:15
Waqas Ahmed 201024-Mar-18 22:15 
QuestionNot work on client machine ! Pin
Elsharif16-Jan-18 7:10
Elsharif16-Jan-18 7:10 
AnswerRe: Not work on client machine ! Pin
Preetam U Ramdhave28-Mar-18 8:52
Preetam U Ramdhave28-Mar-18 8:52 
GeneralRe: Not work on client machine ! Pin
Amar zaidi19-May-19 3:02
Amar zaidi19-May-19 3:02 
QuestionIs this web.config Machine dependent? Pin
Member 1251593015-Sep-17 2:30
Member 1251593015-Sep-17 2:30 
AnswerRe: Is this web.config Machine dependent? Pin
Preetam U Ramdhave21-Sep-17 13:59
Preetam U Ramdhave21-Sep-17 13:59 
QuestionNice but... Pin
Hitro6-Sep-16 4:02
Hitro6-Sep-16 4:02 
AnswerRe: Nice but... Pin
Preetam U Ramdhave21-Nov-16 10:41
Preetam U Ramdhave21-Nov-16 10:41 
AnswerRe: Nice but... Pin
Preetam U Ramdhave21-Nov-16 12:18
Preetam U Ramdhave21-Nov-16 12:18 
QuestionThanks Pin
Chougule Vinay5-Sep-16 22:32
Chougule Vinay5-Sep-16 22:32 
QuestionInvalid Data Pin
Flote Fuertes13-Jun-16 22:02
Flote Fuertes13-Jun-16 22:02 
QuestionNice, but... Pin
Member 112897294-Mar-16 10:51
Member 112897294-Mar-16 10:51 
AnswerRe: Nice, but... Pin
Preetam U Ramdhave10-May-16 7:39
Preetam U Ramdhave10-May-16 7:39 
QuestionRegarding your encryption technique Pin
Jonathan R Bolton23-Dec-15 4:15
professionalJonathan R Bolton23-Dec-15 4:15 
AnswerRe: Regarding your encryption technique Pin
Preetam U Ramdhave28-Dec-15 7:36
Preetam U Ramdhave28-Dec-15 7:36 
QuestionGreat Work, thank you Pin
Member 1048687114-Aug-15 4:03
Member 1048687114-Aug-15 4:03 
Questionok good Pin
mojtaba poormohamad15-May-15 1:28
mojtaba poormohamad15-May-15 1:28 
QuestionNice work Pin
Thiago Daher13-Mar-15 19:53
Thiago Daher13-Mar-15 19:53 
QuestionGetting NullReferenceException on Decryption Pin
MicrosoftDotNetNewbie17-Jul-14 7:46
MicrosoftDotNetNewbie17-Jul-14 7:46 
GeneralMy vote of 5 Pin
Sapan Ghafuri28-Sep-13 13:25
Sapan Ghafuri28-Sep-13 13:25 
GeneralRe: My vote of 5 Pin
Thiago Daher13-Mar-15 20:13
Thiago Daher13-Mar-15 20:13 
GeneralRe: My vote of 5 Pin
Sapan Ghafuri18-May-15 8:57
Sapan Ghafuri18-May-15 8:57 
Questionweb config Pin
Hanieef14-Jun-13 15:45
Hanieef14-Jun-13 15:45 

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

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