Encrypt application/web configuration file

Under some scenarios the developers want to encrypt some sections inside app.config or web.config file, this article How To: Encrypt Configuration Sections in ASP.NET 2.0 Using RSA describes how to do so clearly, Scott Guthrie also posted one: Encrypting Web.Config Values in ASP.NET 2.0.

However, in the posts above they uses aspnet_regiis.exe and seems it doesn’t directly support app.config, if we want to encrypt app.config for Windows Form or WPF applications, while I tried use it to encrypt my app.config file, it generates a web.config which means my Winform definitely can’t use it, even if I copy the encrypted appSettings section from this generated web.config to my own app.config (ConfigurationManager.AppSettings[EncryptedKeyName] is null after I did that).


Config Encrypt

Click to view large screenshot



Encrypted WebConfig

Click to view large screenshot


After several minutes google search and testing I found the code below is simple and very straight forward to achieve this:

            Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

            SectionInformation appSettingsSecInfo = config.GetSection("appSettings").SectionInformation;
            if (!appSettingsSecInfo.IsProtected)
                Console.WriteLine("The configuration file has NOT been protected!");

                // Encrypt this section by using security provider (RsaProtectedConfigurationProvider or DpapiProtectedConfigurationProvider).
                appSettingsSecInfo.ForceSave = true;


This code snippet will do the encryption job and works for both app.config/web.config, here is the MSDN definition page for SectionInformation.ProtectSection:

Overview of Protected Configuration:

RsaProtectedConfigurationProvider Class:

DpapiProtectedConfigurationProvider Class:


About Wayne Ye
Wayne is a software developer, Tech Lead and also a geek, he has more than 6 years experience in developing Web/Windows based applications using ASP.NET, HTML/CSS, JavaScript/AJAX, Web Service, Silverlight, Winform, WPF, Win32 API/WMI, he also invests tremendous effect in GOF Design Patterns, S.O.L.i.D principle, MVC, MVVM, Domain Driven Design, SOA, HTTP/REST and AOP. In his spare time, he likes writing tech/life blogs on WayneYe.com, and separate time with his dear wife and lovely son. Wayne's Geek Life http://WayneYe.com Infinite passion on programming.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: