Encrypting PowerShell Scripts

Sometimes, you may want to hide the code of your PowerShell script in order to protect passwords contained within the code. One way to safely encrypt PowerShell script is by converting it into a secure string. You must first create a sample script you would like to encrypt and save it as $home\original.ps1.

Next, use the following function to encrypt it into a file called secure.bin:

function Encrypt-Script($path, $destination) {
$script = Get-Content $path | Out-String
$secure = ConvertTo-SecureString $script -asPlainText -force
$export = $secure | ConvertFrom-SecureString
Set-Content $destination $export
"Script '$path' has been encrypted as '$destination'"
}

Encrypt-Script $home\original.ps1 $home\secure.bin

When you now look at secure.bin, all content is safely encrypted:

Get-Content $home\secure.bin

To execute the script, you need to decrypt it. Here is the second part, which reads in an encrypted script and executes it:

function Execute-EncryptedScript($path) {
trap { "Decryption failed"; break }
$raw = Get-Content $path
$secure = ConvertTo-SecureString $raw
$helper = New-Object system.Management.Automation.PSCredential("test", $secure)
$plain = $helper.GetNetworkCredential().Password
Invoke-Expression $plain
}

Execute-EncryptedScript $home\secure.bin

This approach allows you to use your personal identity as secret key. As a result, the person who encrypted the script is the only one who can decrypt and execute it- a great way to keep personal scripts secret.


Posted Apr 08 2009, 08:00 AM by ps1

Comments

shaka411 wrote re: Encrypting PowerShell Scripts
on 02-07-2010 1:36 PM

When decrypting the script (bin file) for execution how can I pass it a variable?

Mark van de Beek wrote re: Encrypting PowerShell Scripts
on 09-09-2010 6:29 AM

I also would like to know if it possible to pass a variable from the decrypted file into the script which is decrypting the file.

paperless wrote re: Encrypting PowerShell Scripts
on 12-30-2010 10:47 AM

PShellExec is a free utility that encrypts and executes data sensitive PowerShell scripts. See more details at www.screencast.com/.../fsawR7vSur9s

suneg wrote re: Encrypting PowerShell Scripts
on 09-16-2011 9:37 AM

I too was after passing variables to my encrypted script. Worked it out finally.

Change the Encrypt-Script statment to encrypt your file as another ps1.

Take all the parameter declarations out of your original script.

Add them to the arguments on the execute-encryptedscript function e.g.

function Execute-EncryptedScript($path, $yourvariable, $yourvariable2)

set your variables like this:-

Execute-EncryptedScript $home\secure.ps1 -yourvariable "value1" - yourvariable2 "value2"

Hope that helps you guys. Brillaint script btw ps1!

Thanks

Concentrated Tech NSoftware Dell Compellent Sponsored by Idera and Concentrated Tech and NSoftware and Dell Compellent
Copyright 2011 PowerShell.com. All rights reserved.