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
[Security.Cryptography.RNGCryptoServiceProvider]::Create().GetBytes($EncryptionKeyBytes)
$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"


#decryption:

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

$cleartext = ConvertFrom-SecureString $PasswordSecureString -AsPlainText
$cleartext

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)
#$decrypted

More on the Powershell encrytion topic here:

https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.security/convertto-securestring?view=powershell-7.2

Tip if using VScode and Powershell, I suggest switching to Powershell ISE https://docs.microsoft.com/en-us/powershell/scripting/dev-cross-plat/vscode/how-to-replicate-the-ise-experience-in-vscode?view=powershell-7.2

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