Click here to Skip to main content
13,352,638 members (36,232 online)
Click here to Skip to main content
Add your own
alternative version


72 bookmarked
Posted 30 Mar 2007

Encrypting the app.config File for Windows Forms Applications

, 18 Apr 2007
Rate this:
Please Sign up or sign in to vote.
Encrypting the app.config file for Windows Forms Applications


ASP.NET offers the possibility to encrypt sections in the web.config automatically. It seems it is not possible for WinForm applications to do that for the app.config. And this is true for a part: WinForms does not offer tools to configure it. But it can be done. It is all .NET. Isn't it? So how do we do it? Read on and see how.

Using the Code

First let me explain something about the configuration files in .NET. The app.config and web.config are divided into sections. The encrypting and decrypting operations are performed on sections and not on the file as a whole.

Developers can extend a configuration file by defining custom sections. This can be done by adding a section tag to the configSections element or the sectionGroup element like in the example below. The name attribute of section element specifies the name of the new section. The type attribute specifies the handler that processes the configuration section: it gets the data out of the section. As you can see in the example below, I implemented both scenarios.

<?xml version="1.0" encoding="utf-8" ?>
        <section name="Vault" 

                 type="System.Configuration.NameValueSectionHandler" />
        <sectionGroup name="applicationSettings" 

                    type="System.Configuration.ApplicationSettingsGroup, System, 
                    Version=, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
            <section name="EncryptConnStringsSection.My.MySettings" 

                    type="System.Configuration.ClientSettingsSection, System, 
                    Version=, Culture=neutral, PublicKeyToken=b77a5c561934e089" 

                    requirePermission="false" />
        <add name="EncryptConnStringsSection.My.MySettings.testConn"

            connectionString="Data Source=someserver;Initial 
                             Catalog=ProjectX_Dev;Integrated Security=True" />

Now that I have explained how to create sections in the app.config, let's go on to show how to encrypt a section. It is really a simple operation. And once a section has been encrypted, you do not have to worry about decrypting it. The .NET Framework does it automatically for you. It is a transparent operation and works as if you did not encrypt the section.

The configuration namespace contains a class that represents a section. This class is called ConfigurationSection. A member of this class is the ElementInformation property. This property gets information about a section and it has the method ProtectSection defined on it. This method encrypts the section. Out of the box, there are two encryption algorithms supported via providers:

  • DPAPIProtectedConfigurationProvider
  • RSAProtectedConfigurationProvider

The default provider is RSAProtectedConfigurationProvider. You use the default provider by passing nothing/null as a parameter to the ProtectSection method.
I wrote the following class to demonstrate this method:

Imports System.Configuration

''' <span class="code-SummaryComment"><summary></span>
''' This class protects (encrypts) a section in the applications configuration file.
''' <span class="code-SummaryComment"></summary></span>
''' <span class="code-SummaryComment"><remarks>The <seealso cref="RsaProtectedConfigurationProvider"/> </span>
''' is used in this implementation.<span class="code-SummaryComment"></remarks></span>
Public Class ConfigSectionProtector

    Private m_Section As String

    ''' <span class="code-SummaryComment"><summary></span>
    ''' Constructor.
    ''' <span class="code-SummaryComment"></summary></span>
    ''' <span class="code-SummaryComment"><param name="section">The section name.</param></span>
    Public Sub New(ByVal section As String)
        If String.IsNullOrEmpty(section) Then _ 
            Throw New ArgumentNullException("ConfigurationSection")

        m_Section = section
    End Sub

    ''' <span class="code-SummaryComment"><summary></span>
    ''' This method protects a section in the applications configuration file. 
    ''' <span class="code-SummaryComment"></summary></span>
    ''' <span class="code-SummaryComment"><remarks></span>
    ''' The <span class="code-SummaryComment"><seealso cref="RsaProtectedConfigurationProvider" /> </span>
    ''' is used in this implementation.
    ''' <span class="code-SummaryComment"></remarks></span>
    Public Sub ProtectSection()
        ' Get the current configuration file.
        Dim config As Configuration = ConfigurationManager.OpenExeConfiguration
        Dim protectedSection As ConfigurationSection = config.GetSection(m_Section)

        ' Encrypts when possible
        If ((protectedSection IsNot Nothing) _
        AndAlso (Not protectedSection.IsReadOnly) _
        AndAlso (Not protectedSection.SectionInformation.IsProtected) _
        AndAlso (Not protectedSection.SectionInformation.IsLocked) _
        AndAlso (protectedSection.SectionInformation.IsDeclared)) Then
            ' Protect (encrypt)the section.
            ' Save the encrypted section.
            protectedSection.SectionInformation.ForceSave = True
        End If
    End Sub
End Class 

As you can see, this class also has a method ProtectSection. Basically it gets section information out of the app.config and checks if it can be encrypted. If so, it protects the section using the default encryption provider and it saves it. And it's done.

It is simpler to protect or unprotect connectionstrings. It can be done with the following code sample:

' Connection string encryption
Dim config As Configuration = ConfigurationManager.OpenExeConfiguration
' We must save the changes to the configuration file.
config.Save(ConfigurationSaveMode.Full, True)  


  • 30-03-2007: Initial version
  • 12-04-2007: Added a link to my blog. Maybe you will like it. Let me know, please.
  • 18-04-2007: Updated the example project
  • 21-04-2007: Updated last code example


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


About the Author

Web Developer
Netherlands Netherlands
Name : A.C.F. de Ron B ICT (Ton)
Position : Senior System designer
Date of birth : 15-12-1971
Nationality : Dutch
Language : Dutch, English
Experience since : 1996
Blog :
Summary :

After my study Business Administration Informatics at the University for Economic Studies, In gained experience as a Database Designer, Software Developer, Software Engineer, Tester and .NET coach. With Centura Team Developer I built several applications for social care foundations and for the life insurance branch, e.i. Winterthur and Zwisterleven.

Also I worked for Philip Morris Holland where I maintained and developed on the specification system for cigarettes. Also I worked there on .Net projects which aided production logistics. At this moment I work for Unilever Research where I designed and implemented a formulation creation tool and a monitor stock administration application using .Net 2.0 and Visual Studio.Net 2005.

You may also be interested in...


Comments and Discussions

Praisenice Pin
BillW335-Nov-15 5:13
professionalBillW335-Nov-15 5:13 
SuggestionSome fixes to prevent spamming the config files Pin
colin@ngland.net4-Mar-15 13:13
membercolin@ngland.net4-Mar-15 13:13 
QuestionWorth updating this example Pin
Brian23330-Apr-14 8:02
memberBrian23330-Apr-14 8:02 
QuestionSmall Query About Encrypion. Pin
chandan028522-Sep-13 0:43
memberchandan028522-Sep-13 0:43 
AnswerRe: Small Query About Encrypion. Pin
Vakarev_dmitri14-Jun-15 9:15
memberVakarev_dmitri14-Jun-15 9:15 
QuestionError To decrypt Pin
Edison J Romo R13-Sep-13 14:41
memberEdison J Romo R13-Sep-13 14:41 
QuestionYou suck. Pin
sunayv20-Jun-13 2:03
membersunayv20-Jun-13 2:03 
GeneralMy vote of 1 Pin
B.Farivar23-Apr-13 20:45
memberB.Farivar23-Apr-13 20:45 
QuestionNot working inside IDE Pin
Pravesh Koirala 10811-Aug-11 2:32
memberPravesh Koirala 10811-Aug-11 2:32 
AnswerRe: Not working inside IDE Pin
TRON11-Aug-11 22:58
memberTRON11-Aug-11 22:58 
GeneralRe: Not working inside IDE Pin
Pravesh Koirala 10812-Aug-11 17:29
memberPravesh Koirala 10812-Aug-11 17:29 
Generalerror : "Extension names must be unique" Pin
donet0123-Aug-10 7:56
memberdonet0123-Aug-10 7:56 
GeneralRe: error : "Extension names must be unique" [modified] Pin
vikrantislav8-Dec-10 10:12
membervikrantislav8-Dec-10 10:12 
GeneralRe: error : "Extension names must be unique" Pin
vikrantislav9-Dec-10 9:59
membervikrantislav9-Dec-10 9:59 
Question.pfx file Pin
raland16-Oct-08 23:33
memberraland16-Oct-08 23:33 
AnswerRe: .pfx file Pin
TRON20-Oct-08 11:07
memberTRON20-Oct-08 11:07 
GeneralMS Example on how encrypt winforms app.config Pin
peterpan2561-Sep-08 5:17
memberpeterpan2561-Sep-08 5:17 
QuestionDeploy problem Pin
luc_favaro20-Aug-08 10:15
memberluc_favaro20-Aug-08 10:15 
AnswerRe: Deploy problem Pin
TRON21-Aug-08 12:25
memberTRON21-Aug-08 12:25 
GeneralProblem with this implementation... Pin
DaveBlack8-Oct-07 12:29
memberDaveBlack8-Oct-07 12:29 
GeneralRe: Problem with this implementation... Pin
TRON9-Oct-07 7:18
memberTRON9-Oct-07 7:18 
GeneralRe: Problem with this implementation... Pin
kevinlkingma18-Jul-08 4:42
memberkevinlkingma18-Jul-08 4:42 
GeneralRe: Problem with this implementation... Pin
Ed Gadziemski30-Jul-08 13:01
memberEd Gadziemski30-Jul-08 13:01 
GeneralRe: Problem with this implementation... Pin
t.alkahtiri7-Nov-13 1:03
membert.alkahtiri7-Nov-13 1:03 
QuestionHow do I encrypt this config file? Pin
HenkVanTol4-May-07 5:46
memberHenkVanTol4-May-07 5:46 

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.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.180111.1 | Last Updated 18 Apr 2007
Article Copyright 2007 by TRON
Everything else Copyright © CodeProject, 1999-2018
Layout: fixed | fluid