AES encrypt with Powershell

After some trial and error and readup on the topic, I wrote a script that encypts text with AES 256bits encryption to a file that can be decoded if you have the Key. It’s all ready in Powershell.

A clue here is that if you have a script to be run under a specific user account, or need to run your script on a different computer, or you want to send your encrypted content for someone else to decrypt, you will need to use this keyfile solution instead of regular System.Security.Securestring, as this is only stored in the system for the user in question.

Prerequisites: Powershell V.7

$EncryptionKeyBytes = New-Object Byte[] 32
$EncryptionKeyBytes | Out-File "c:\temp\encryption.key"

$EncryptionKeyData = Get-Content "c:\temp\encryption.key"

# store in system | convert back to file with AES encrypted data
Read-Host "enter your password" -AsSecureString | ConvertFrom-SecureString -key $EncryptionKeyData| Out-File -FilePath "c:\temp\secret.encrypted"
Write-Host "---------------------------------------------------`n
Encryption Key is stored in c:\temp\encryption.key `n The AES 256bits encrypted message in c:\temp\secret.encrypted"


$PasswordSecureString = Get-Content "C:\temp\secret.encrypted" | ConvertTo-SecureString -Key $EncryptionKeyData

$cleartext = ConvertFrom-SecureString $PasswordSecureString -AsPlainText

If Powershell V.5 is used the decoding needs a different syntax:

#$decrypted = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($PasswordSecureString)
#$decrypted = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($decrypted)

More on the Powershell encrytion topic here:

Tip if using VScode and Powershell, I suggest switching to Powershell ISE

How secure?

AES 256 is virtually impenetrable using brute-force methods. While a 56-bit DES key can be cracked in less than a day, AES would take billions of years to break using current computing technology. However no encryption is entirely secure.

More articles