Click here to Skip to main content
15,887,746 members
Articles / Desktop Programming / Windows Forms
Article

Encrypting the app.config File for Windows Forms Applications

Rate me:
Please Sign up or sign in to vote.
4.08/5 (11 votes)
17 Apr 2007CPOL2 min read 319.2K   5.3K   77   38
Encrypting the app.config file for Windows Forms Applications

Introduction

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
<?xml version="1.0" encoding="utf-8" ?>
<configuration> 
    <configSections>
        <section name="Vault" 
                 type="System.Configuration.NameValueSectionHandler" />
        <sectionGroup name="applicationSettings" 
                    type="System.Configuration.ApplicationSettingsGroup, System, 
                    Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
            <section name="EncryptConnStringsSection.My.MySettings" 
                    type="System.Configuration.ClientSettingsSection, System, 
                    Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" 
                    requirePermission="false" />
        </sectionGroup>
    </configSections>
    <connectionStrings>
        <add name="EncryptConnStringsSection.My.MySettings.testConn"
            connectionString="Data Source=someserver;Initial 
                             Catalog=ProjectX_Dev;Integrated Security=True" />
    </connectionStrings>

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:

VB.NET
Imports System.Configuration

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

    Private m_Section As String

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

        m_Section = section
    End Sub

    ''' <summary>
    ''' This method protects a section in the applications configuration file. 
    ''' </summary>
    ''' <remarks>
    ''' The <seealso cref="RsaProtectedConfigurationProvider" /> 
    ''' is used in this implementation.
    ''' </remarks>
    Public Sub ProtectSection()
        ' Get the current configuration file.
        Dim config As Configuration = ConfigurationManager.OpenExeConfiguration
                        (ConfigurationUserLevel.None)
        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.
            protectedSection.SectionInformation.ProtectSection(Nothing)
            ' Save the encrypted section.
            protectedSection.SectionInformation.ForceSave = True
            config.Save(ConfigurationSaveMode.Full)
        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:

VB.NET
' Connection string encryption
Dim config As Configuration = ConfigurationManager.OpenExeConfiguration
                    (ConfigurationUserLevel.None)      
config.ConnectionStrings.SectionInformation.ProtectSection(Nothing)
' We must save the changes to the configuration file.
config.Save(ConfigurationSaveMode.Full, True)  

History

  • 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

License

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


Written By
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 : http://www.tronsoft.nl
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.

Comments and Discussions

 
AnswerRe: How do I encrypt this config file? Pin
TRON10-May-07 22:22
TRON10-May-07 22:22 
Generalquick way to encrypt sections in app.config Pin
mpayne7921-Apr-07 10:55
mpayne7921-Apr-07 10:55 
GeneralRe: quick way to encrypt sections in app.config Pin
bmwgamil27-Jul-07 8:02
bmwgamil27-Jul-07 8:02 
GeneralRe: quick way to encrypt sections in app.config Pin
mpayne7927-Jul-07 13:52
mpayne7927-Jul-07 13:52 
GeneralRe: quick way to encrypt sections in app.config Pin
frobertpixto9-Feb-09 12:43
frobertpixto9-Feb-09 12:43 
GeneralRe: quick way to encrypt sections in app.config Pin
Sourabh N17-Sep-09 2:18
Sourabh N17-Sep-09 2:18 
GeneralRe: quick way to encrypt sections in app.config Pin
sjelen9-Feb-10 1:16
professionalsjelen9-Feb-10 1:16 
GeneralRe: quick way to encrypt sections in app.config Pin
Kent K18-Nov-09 8:08
professionalKent K18-Nov-09 8:08 
Very nice, I like this. I can encrypt the conn string section before deploying it with this method. I was unsure as well how an application would handle/be able to encrypt it on the first use, when the app was deployed as a click once with only online execution being set (what I'm doing). And, the ability to never have the sensitive connection info exist in plain text in the situation where I'm not using an installer, is very desirable.

I found one thing to pay attention to though, else the connection string is viewable to someone who looks in the right place. After trying this method, I looked at every deployed file and found the conn string in <your apps="" name="">.exe.deploy
It was at the end near references to the settings file it seemed, at least for the readable information that was present.

So, I looked at my connection string (a setting of my application like many may do). For that setting, there is a property 'GenerateDefaultSettingInCode' that was set to true. I changed it to false and re-deployed and the conn string info was gone!

So, the steps are:
-Create your app, storing potential sensitive info in a setting, such as the connection string.
-Make sure the 'GenerateDefaultSettingInCode' property is set to false for the setting you wish to protect.
-Do the steps you've outlined.
-Deploy the application (I'm using click once, deploying to a network location, where the app is only available online).

Oh, I'm using VS2008 and a 3.5 based app, in case others don't have the experience I've noted.
QuestionProtect encryption string fails - IsDeclared = False Pin
tbim16-Apr-07 22:09
tbim16-Apr-07 22:09 
AnswerRe: Protect encryption string fails - IsDeclared = False Pin
TRON17-Apr-07 9:20
TRON17-Apr-07 9:20 
GeneralRe: Protect encryption string fails - IsDeclared = False Pin
tbim17-Apr-07 14:24
tbim17-Apr-07 14:24 
GeneralNow you post it :) Pin
redjoy30-Mar-07 8:50
redjoy30-Mar-07 8:50 

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.