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
[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 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"
#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($PasswordSecureString)
#$decrypted = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($decrypted)
#$decrypted
More on the Powershell encrytion topic here:
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.