Create an AES key for encrypting passwords
Encrypting Service Account Passwords
Encrypting passwords to use in automation scripts is much better than having the password stored in plain text in a file, or worse, having the password in plain text right in the script. One problem with encrypting the password is that it can be tied to the machine and user account that you are using. One way around this is to use an AES key to encrypt and decrypt the password so you can use the password on another machine or from another account.
The script can be used to generate an AES key file with random data using 16, 24 or 32 bits.
I’ve tested it using higher bits and it works fine, you just need to change the ValidateSet. Remember this is just the key not the encryption level.
This key file must be kept safe. Anyone with access to the contents can decrypt anything you have secured with it
<#
.SYNOPSIS
Create AES key with Random Data and export to file
.DESCRIPTION
Creates AES key that you can use to encrypt password to be used in PS Scripts.
AES keys can use 16, 24, or 32 bit keys
.PARAMETER encLevel
Set the AES encryption level. Valid options are 16, 24 and 32. 32 bit by default.
.PARAMETER keyFile
The file to write the key to. This is a mandatory parameter.
If the file exists the script will NOT overwrite the file.
.INPUTS
None
.OUTPUTS
None
.EXAMPLE
CreateAESKey.ps1 -keyFile c:\tmp\keyfile.key
Specify keyFile location and filename
.EXAMPLE
CreateAESKey.ps1 -keyFile c:\tmp\keyfile.key -encLevel 24
Set Encryption Level to 24bit (Default 32 bit)
Valid encryption levels for AES are 16,24,32
#>
param(
[ValidateSet('16','24','32')][Int32]$encLevel = 32,
[Parameter(Mandatory=$true)][String]$keyFile
)
cls
#Check if the keyFile exists. Stop if it is found.
if (Test-Path $keyFile) {
Write-Host "`nKeyFile: " -ForegroundColor Red -NoNewline
Write-Host "$keyFile " -ForegroundColor Yellow -NoNewline
Write-Host "found!`tStopping!`n" -ForegroundColor Red
break
}
Write-Host "Creating AES Key" -ForegroundColor Green
$key = New-Object Byte[] $encLevel
[Security.Cryptography.RNGCryptoServiceProvider]::Create().GetBytes($key)
$key | Out-File $keyFile #Write the key to file specified
cls
Write-Host "Created " -NoNewline
Write-Host $keyFile -ForegroundColor Green -NoNewline
Write-Host " using " -NoNewline
Write-Host $encLevel -ForegroundColor Green -NoNewline
Write-Host " bit encryption`n"