Monday, July 28, 2008

PowerShell to encrypt / decrypt app.config sections

Here is a PS script called AppConfigCrypto.ps1 that allows you to encrypt and decrypt sections of an appConfig. Be aware that once a config is encrypted, you can't just copy it from machine to machine since the encryption is done via the default machine key. You should be able to get around this by importing your own keys and modifying the script below. If you don't import a user specified key, then you will have to encrypt on the machine where the application will execute.

Here's the PS script:

param(
[string]$sectionName,
[string]$exePath="app.config",
[switch]$encrypt,
[switch]$decrypt)

function CallExit($msg)
{
$msg
Usage
exit
}

function OKExit($msg)
{
$msg
exit
}

function Usage
{
"Usage: ./AppConfigCrypto.ps1 sectionName exePath [-encrypt | -decrypt]"
}

# check params
if ($sectionName.Trim().Length -eq 0) { CallExit("%You must pass a section name (e.g. appSettings, ConnectionStrings)") }
if ($encrypt -eq $false -and $decrypt -eq $false) { CallExit("%Must specify -encrypt or -decrypt") }
if ($encrypt -ne $false -and $decrypt -ne $false) { CallExit("%Must specify either -encrypt or -decrypt") }

# load the config
$config = [System.Configuration.ConfigurationManager]::OpenExeConfiguration((Resolve-Path $exePath))

# make sure section exists and is readable
$section = $config.GetSection($sectionName)
if ($null -eq $section) { CallExit("%$sectionName section not found") }
if ($section.IsReadOnly()) { CallExit("%$sectionName is read-only") }

if ($encrypt)
{
if ($section.SectionInformation.IsProtected -eq $true) { OKExit("%Section already encrypted") }
"Encrypting $sectionName . . ."
$section.SectionInformation.ProtectSection("RsaProtectedConfigurationProvider")
}
elseif ($decrypt)
{
if ($section.SectionInformation.IsProtected -eq $false) { OKExit("%Section already decrypted") }
"Decrypting $sectionName . . ."
$section.SectionInformation.UnprotectSection()
}

# save section
$section.SectionInformation.ForceSave = $true
$config.Save()

No comments:

Can't RDP? How to enable / disable virtual machine firewall for Azure VM

Oh no!  I accidentally blocked the RDP port on an Azure virtual machine which resulted in not being able to log into the VM anymore.  I did ...