Encrypting and Decrypting Sections of a Web.config with PowerShell

In this post I will show you how to Encrypt and Decrypt Sections of a Web.config file.

This function will encrypt a sections of a web.config file.

function Encrypt-ConfigurationSection([int] $id, [string] $app, [string] $section, [string] $version){
$currentDirectory = (Get-Location)
Set-Location "C:\windows\Microsoft.Net\Framework\$version\"
.\aspnet_regiis.exe -pe $section -app $app -site $id -prov "RsaProtectedConfigurationProvider"
Set-Location $currentDirectory
}

Example call

Encrypt-ConfigurationSection 1 ‘/WebApplication1’ ‘connectionStrings’ ‘v4.0.30319’

This function will decrypt a sections of a web.config file.

function Decrypt-ConfigurationSection([int] $id, [string] $app, [string] $section, [string] $version){
$currentDirectory = (Get-Location)
Set-Location "C:\windows\Microsoft.Net\Framework\$version\"
.\aspnet_regiis.exe -pd $section -app $app -site $id
Set-Location $currentDirectory
}

Example Call

Decrypt-ConfigurationSection 1 ‘/WebApplication1’ ‘connectionStrings’ ‘v4.0.30319’

Now, if you look at the functions you will notice that there is a $version variable. The $version variable is important. This is because if you are working with an ASP.net web application that uses an Application Pool with a Managed Runtime Version of v2.0, then you want to be using the aspnet_regiis application for that version. The same goes for Applications that use and Application Pool with a Managed Runtime Version of v4.0.

About these ads

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