Credential Obfuscator

by Feb 2, 2015

PowerShell ISE 3.0 and later

While it is generally not recommended to hard code passwords in scripts, there are sometimes scenarios where this is done. Rather than hard coding plain text passwords, at least an effort should be made to obfuscate passwords. Password obfuscation is a weak protection, but it will keep non-PowerShell people from getting to the secret easily.

Here is a small script that asks for a username and a password, and then produces an obfuscation script that produces the credential object.

When you run the script that is produced by the script below, in $cred you get a credential object containing username and password, that can be used for any cmdlet with the –Credential parameter.

$cred = Get-Credential -Message 'Enter Domain\Username and Password'
$pwd = $cred.Password
$user = $cred.UserName
$key = 1..32 | ForEach-Object { Get-Random -Maximum 256 }
$pwdencrypted = $pwd | ConvertFrom-SecureString -Key $key

$private:ofs = ' '

$generatedScript = @()
$generatedScript += '$password = ''{0}''' -f $pwdencrypted
$generatedScript += '$key = ''{0}''' -f "$key"

$generatedScript += '$passwordSecure = ConvertTo-SecureString -String $password -Key ([Byte[]]$key.Split('' ''))' 
$generatedScript += '$cred = New-Object system.Management.Automation.PSCredential(''{0}'', $passwordSecure)' -f $user
$generatedScript += '$cred' 

$file = $psise.CurrentPowerShellTab.Files.Add()
$file.Editor.Text = $generatedScript | Out-String
$file.Editor.SetCaretPosition(1,1)

The automatically generated password script will look similar to this:

$password = '76492d1116743f0423413b16050a5345MgB8AHMAUQA3AFAAVwB0AGkAUQBUAC8AdwBqADYAUABVAFYAUwB4AEYAYgB4AFEAPQA9AHwAZgA0ADgAOQA4AGYANwA0AGEAMAA0ADUANwA5ADkAMwA5ADkAMwA1ADUANQA0AGYANwA5AGQANwBkAGYAOQBmAGEAYQA3ADMAYgBkADIAOQA3AGMAYQBmADUAMgA3ADEANwA3AGEAYgBmADAAYgA1AGYAYwAyADYAYgAzADkAOAA='
$key = '187 98 34 82 148 52 13 86 246 2 130 197 217 97 147 98 75 197 149 246 74 35 27 7 211 15 131 93 182 231 171 3'
$passwordSecure = ConvertTo-SecureString -String $password -Key ([Byte[]]$key.Split(' '))
$cred = New-Object system.Management.Automation.PSCredential('mickey\mouse', $passwordSecure)
$cred

Twitter This Tip! ReTweet this Tip!