June 12, 2009

Encrypt config using powershell

Here is a simple way to encrypt your config file using a powershell script:
Add-Type -Assembly System.Configuration

function Config-Encrypt {
param( [string] $appPath = $(throw "Path of config file is incorrect or missing."),
[string] $sectionName = $(throw "Section in config file is incorrect or missing.")
)

Write-Host "Encrypting config section..."

$config = [System.Configuration.ConfigurationManager]::OpenExeConfiguration((Convert-Path $appPath))
$section = $config.GetSection($sectionName)

if (-not $section.SectionInformation.IsProtected)
{
if(-not $section.SectionInformation.IsLocked)
{
$section.SectionInformation.ProtectSection("RSAProtectedConfigurationProvider");
$section.SectionInformation.ForceSave = $true
$config.Save([System.Configuration.ConfigurationSaveMode]::Modified);
}
}

Write-Host "Completed."
}
All you would have to do is then call it like this:
Config-Encrypt 'c:\DataConfiguration.config' 'connectionStrings'
To Decrypt,you can create a function called Config-Decrypt. The code is basically the same with some minor changes:
Add-Type -Assembly System.Configuration

function Config-Decrypt {
param( [string] $appPath = $(throw "Path of config file is incorrect or missing."),
[string] $sectionName = $(throw "Section in config file is incorrect or missing.")
)

Write-Host "Decrypting config section..."

$config = [System.Configuration.ConfigurationManager]::OpenExeConfiguration((Convert-Path $appPath))
$section = $config.GetSection($sectionName)

if ($section.SectionInformation.IsProtected)
{
if(-not $section.SectionInformation.IsLocked)
{
$section.SectionInformation.UnprotectSection();
$section.SectionInformation.ForceSave = $true
$config.Save([System.Configuration.ConfigurationSaveMode]::Modified);
}
}

Write-Host "Completed."
}

No comments:

Post a Comment