Encrypting external config sections (using PowerShell)

The .Net framework allows you to encrypt sections of your configuration files, e.g. connection strings. If they live in the web.config it’s very simple:

aspnet_regiis -pe "connectionStrings"

Unfortunately, for those of us who like to keep our connection strings in an external config section, it can be a little more convoluted.

A bit of Googling turned up a couple of blog posts & Stack Overflow answers pointing in the right direction, and after a few hiccups (encrypting the machine.config by accident!) here’s a script that does the job:

  [String] $configFilePath = $(throw "Config file path is mandatory"),
  [String] $sectionName = "connectionStrings",
  [String] $dataProtectionProvider = "DataProtectionConfigurationProvider"
#The System.Configuration assembly must be loaded
$configurationAssembly = "System.Configuration, Version=, Culture=Neutral, PublicKeyToken=b03f5f7f11d50a3a"
[void] [Reflection.Assembly]::Load($configurationAssembly)
$configurationFileMap = New-Object -TypeName System.Configuration.ExeConfigurationFileMap
$configurationFileMap.ExeConfigFilename = $configFilePath
$configuration = [System.Configuration.ConfigurationManager]::OpenMappedExeConfiguration($configurationFileMap, [System.Configuration.ConfigurationUserLevel]"None")
$section = $configuration.GetSection($sectionName)
if (-not $section.SectionInformation.IsProtected)
  Write-Host "Encrypting configuration section..."
  $section.SectionInformation.ForceSave = [System.Boolean]::True;
  Write-Host "Succeeded!"

One thought on “Encrypting external config sections (using PowerShell)

  1. SueDeuno March 3, 2014 / 2:52 pm

    This appears to only work if the config contains a root element, which external configs don’t appear to work if that element exists.

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 )

Connecting to %s