Securing Passwords with AES in Powershell (May 8, 2020)

Securing credentials can be a difficult issue for your scripts. While this method may not be the best its worlds better than just placing plain text credentials directly in your script. Note, that there are other methods that may be more appropriate depending on the situation.

We'll be encrypting the password using AES so we'll need to generate a key. For this example, I'll be using a 256-bit key; this is determined by the length of out byte array. Where 128-bit is 16 bytes, 192-bit is 24 bytes and a 256-bit key is a 32 bytes array.

#Create the empty array
$AESKey = New-Object Byte[] 32 #32 = 256-bit
#Fill the array, if you fail to do this your key will be all 0's
[Security.Cryptography.RNGCryptoServiceProvider]::Create().GetBytes($AESKey)
#Save the key to a file
$AESKey | Out-File -FilePath "C:\Encryption.Key" #You'll want to pick a better place to store this file.

Now that you have this key file; remember to set the file system permissions to prevent unauthorized accounts from accessing it. Also, make sure to never check this file into GIT or whatever source control system you use.

Next we use this key to encrypt the password. I'm assuming the key is still loaded into the variable $AESKey during this part.

Method 1:

This method will prompt for a username and password. The username you provide doesn’t matter.

$Password = (Get-Credential).Password | ConvertFrom-SecureString -key $AESKey

Method 2:

This method does not prompt but the password is visible on the screen

$Password = "Password" | ConvertTo-SecureString -AsPlainText -Force
$Password | ConvertFrom-SecureString -key $AESKey

Using either method the variable $Password now contains the AES encrypted version of the password

You can either store this directly in the script or in a different file so you can further secure the password using filesystem permissions.

To derypt the password for use.

$Password = "76492d1050a5345MgB8AGQA...DgAZgAzAGMANQA3ADAANQAzAGEAZgA="
#Load Decryption Key
$AESKey = Get-Content C:\Encryption.Key
#Decrypt the key
$SecurePassword = $Password | ConvertTo-SecureString -Key $AESKey

Finally, I needed to convert this to a PSCredential to us it.

$Credential = New-Object System.Management.Automation.PSCredential -ArgumentList $User, $SecurePassword
Here be dragons, or a footer. Both work.