5

I have a custom section in my web.config I need to encrypt. This custom config section uses the configSource attribute to point at a separate config file (as this file is not to be source controlled) and I'd like for this separate config file to be encrypted. I'm not having any luck using aspnet_regiis.exe to encrypt this section.

Is what I'm trying to achieve possible?

My web.config:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
    <configSections>
        <section name="protectedAppSettings" type="System.Configuration.NameValueSectionHandler, System,Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />       
    </configSections>       
    <protectedAppSettings configSource="config\EnvironmentConfigurations\ProtectedAppSettings.config" />
  </configuration>

My custom configuration file:

<?xml version="1.0" encoding="utf-8"?>
<protectedAppSettings>  
  <add key="XXX" value="xxx"/>
</protectedAppSettings>

I've added aspnet_regiis to my path so I can call it from the root directory of my site. This is the command I'm executing:

aspnet_regiis -pef protectedAppSettings ""

The output I get from this command tells me that encrypting was successful

I've found this link that says that it should just work but it doesn't for me..

Braydie
  • 716
  • 9
  • 27

1 Answers1

7

This was because of the type I was using to define my config section. Although there are no docs to prove it, it appears that the NameValueSectionHandler type does not encrypt when used for a config source. The solution was to change the type to System.Configuration.AppSettingsSection and the encryption works correctly

Braydie
  • 716
  • 9
  • 27
  • 1
    Thanks. This solved my problem. Here is the full reference:
    – Alek Davis May 08 '18 at 23:22
  • 1
    Also, in case someone wonders, the values are still retrieved as if they were NameValue type: var section = ConfigurationManager.GetSection("protectedAppSettings") as NameValueCollection; if (section == null) throw new Exception("Cannot read section 'protectedAppSettings' from the configuration file."); string xxx = section["XXX"] as string; – Alek Davis May 10 '18 at 17:41
  • I also had to specify the strongly-typed assembly, otherwise aspnet_regiis was not able to find the AppSettingsSection class. Similar to @AlekDavis but using the latest .NET version, my full section line is: `
    `
    – Tobias Nov 06 '20 at 07:45