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:
param( [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=2.0.0.0, 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.ProtectSection($dataProtectionProvider); $section.SectionInformation.ForceSave = [System.Boolean]::True; $configuration.Save([System.Configuration.ConfigurationSaveMode]::Modified); Write-Host "Succeeded!" }
This appears to only work if the config contains a root element, which external configs don’t appear to work if that element exists.