Thursday, September 29, 2011

PowerShell: Quick Easy Encryption/Decryption

Using the Windows API we can quickly encrypt and decrypt data without much hassle.

The Windows encryption API being used here is documented on MSDN here:

# Convert a plain text string to a character array 
# and cast it to a byte array.
$bytes = "changeit".ToCharArray() | % {[byte] $_}

# Encrtyped the byte array.
$encryptedBytes = [System.Security.Cryptography.ProtectedData]::Protect(

Write-Host "Encrypted Data" -ForegroundColor Cyan
Write-Host ([string] $encryptedBytes) -ForegroundColor DarkGreen

# Unencrypt the data.
$bytes2 = [System.Security.Cryptography.ProtectedData]::Unprotect(

$bytes2 | % { $clearText += [char] $_}

Write-Host "Decrypted Data" -ForegroundColor Cyan
Write-Host ($clearText) -ForegroundColor Red