Obfuscating Credentials

by Dec 10, 2013

How can you securely embed confidential passwords in a PowerShell script? You can't. But you can make it harder for people to discover the secret.

Here is a code generator script that is designed to run inside the PowerShell ISE editor:

# ask for credentials
$cred = Get-Credential
$pass = $cred.Password
$user = $cred.UserName

# create random encryption key
$key = 1..32 | ForEach-Object { Get-Random -Maximum 256 }

# encrypt password with key
$passencrypted = $pass | ConvertFrom-SecureString -Key $key

# turn key and password into text representations
$secret = -join ($key | ForEach-Object { '{0:x2}' -f $_ })
$secret += $passencrypted

# create code
$code  = '$i = ''{0}''' -f $secret 
$code += '$cred = New-Object PSCredential(''' 
$code += $user + ''', (ConvertTo-SecureString $i.SubString(64)'
$code += ' -k ($i.SubString(0,64) -split "(?<=\G[0-9a-f]{2})(?=.)" |'
$code += ' % { [Convert]::ToByte($_,16) })))'

# write new script
$editor = $psise.CurrentPowerShellTab.files.Add().Editor
$editor.InsertText($code)
$editor.SetCaretPosition(1,1) 

When you run it, it asks for a username and a password. Then, it generates a cryptic piece of PowerShell code that you can use in your scripts.

Here's a sample cryptic piece of code generated by the script above:

$i = '73cc7284f9e79f68e9d245b5b2d96c4026397d96cfac6023325d1375414e5f7476492d1116743f0423413b16050a5345MgB8AGgAdABLAEkARABiAFIARgBiAGwAZwBHAHMAaQBLAFoAeQB2AGQAOQAyAGcAPQA9AHwAMgBiADIAMABmADYANwA1ADYANwBiAGYAYwA3AGMAOQA0ADIAMQA3ADcAYwAwADUANAA4ADkAZgBhADYAZgBkADkANgA4ADMAZAA5ADUANABjADgAMgAwADQANQA1ADkAZAA3AGUAMwBmADMAMQAzADQAZgBmADIAZABlADgAZQA='$cred = New-Object PSCredential('contoso\fabrikam', (ConvertTo-SecureString $i.SubString(64) -k ($i.SubString(0,64) -split "(?<=\G[0-9a-f]{2})(?=.)" | % { [Convert]::ToByte($_,16) }))) 

The cryptic auto-generated script code will define the variable $cred, which will hold a valid credential including the password. You can then use $cred inside of your script wherever a -Credential parameter wants a username and password from you.

Twitter This Tip! ReTweet this Tip!