Showing posts with label encryption. Show all posts
Showing posts with label encryption. Show all posts

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."
}

June 7, 2009

Powershell Get MD5 For File

Often when comparing 2 files you have the following 3 options:
  • Date/Time Stamp
  • CRC Check
  • MD5 Check
Each one has a speed tag associated with it where date-time is fast and MD5 is a bit slower. MD5 will however give the best comparison check. Below is an example on how to get the MD5 hash associated with a file:
function Get-MD5File {
Param([string]$file)
$open = [System.IO.FileMode]("open")
$read = [System.IO.FileAccess]("Read")
$md5 = new-object System.Security.Cryptography.MD5CryptoServiceProvider
$fs = new-object System.IO.FileStream($file, $open, $read)
$Hash = $md5.ComputeHash($fs)
$fs.Close()
return $Hash
}

#test a file
$MD5File = Get-MD5File c:\test.pl
Write-Host $MD5File
I believe that the POSh community extensions located here has some easy way to do this as well.