Hiding passwords in PowerShell (slightly)

The following stores text in an encrypted file. Of course, since the method to decrypt it is in the code, this is barely better than having the password in plain text.
But at least it’s not plain text.

When storing the encrypted text we must use a key, otherwise the string can only be recovered on the current machine.

$CurrentFolder = split-path -parent $MyInvocation.MyCommand.Definition
$key=(1..16) # This makes a 128bit byte variable
$key |out-file "$currentfolder\key.txt"
read-host -assecurestring | convertfrom-securestring -key $key | out-file "$currentfolder\encrypted.txt"

To retrieve the encrypted text

$CurrentFolder = split-path -parent $MyInvocation.MyCommand.Definition
$key=Get-Content "\\somewhere\secure\not\with\your\code\key.txt"
$Encryptedpassword = Get-Content "$CurrentFolder\encrypted.txt"
$secure_string = $Encryptedpassword | ConvertTo-SecureString -key $key
$plaintTextPassword=(New-Object System.Management.Automation.PSCredential 'N/A', $secure_string).GetNetworkCredential().Password
Write-host $plaintTextPassword

Store the key somewhere with sensible security permissions, not with your code (not even in the same code repository).


Find more IT Infrastructure tips at www.alexmags.com

Leave a Reply