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.

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 pissword" -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($SecureString)
#$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