Encrypting Scripts With A Password

by Apr 9, 2009

In a previous tip, you have learned how you can encrypt a PowerShell script using your identity as a secret key. You might prefer to use a passphrase to encrypt and decrypt and allow anyone who knows the passphrase to run the script.

Here is how you accomplish that by first creating a sample script you would like to encrypt and save it as $homeoriginal.ps1. Then, encrypt it using this function:

function Encrypt-Script($path, $destination) {
$script = Get-Content $path | Out-String
$key = Read-Host "Enter secret key (at least 16 characters)" -asSecureString
if ($key.Length -lt 16) { Throw "key needs to be at least 16 characters" }
$helper = New-Object system.Management.Automation.PSCredential("test", $key)
$key = $helper.GetNetworkCredential().Password
$secure = ConvertTo-SecureString $script -asPlainText -force
$export = $secure | ConvertFrom-SecureString -Key (([int[]][char[]]$key)[0..15])
Set-Content $destination $export
"Script has been encrypted as '$destination'"
}

Encrypt-Script $homeoriginal.ps1 $homesecure.bin

To decrypt and execute the script, use this function:

function Execute-EncryptedScript($path) {
trap { Write-Host -fore Red "You are not authorized to decrypt and execute this script"continue }
& {
$raw = Get-Content $path
$key = Read-Host "Enter Passphrase" -asSecureString
$helper = New-Object system.Management.Automation.PSCredential("test", $key)
$key = $helper.GetNetworkCredential().Password
$secure = ConvertTo-SecureString $raw -key (([int[]][char[]]$key)[0..15]) -ea Stop
$helper = New-Object system.Management.Automation.PSCredential("test", $secure)
$plain = $helper.GetNetworkCredential().Password
Invoke-Expression $plain
}
}

Execute-EncryptedScript $homesecure.bin