Skip to content

Instantly share code, notes, and snippets.

@ctigeek
Last active March 25, 2024 23:16
Show Gist options
  • Star 45 You must be signed in to star a gist
  • Fork 19 You must be signed in to fork a gist
  • Save ctigeek/2a56648b923d198a6e60 to your computer and use it in GitHub Desktop.
Save ctigeek/2a56648b923d198a6e60 to your computer and use it in GitHub Desktop.
Aes Encryption using powershell.
function Create-AesManagedObject($key, $IV) {
$aesManaged = New-Object "System.Security.Cryptography.AesManaged"
$aesManaged.Mode = [System.Security.Cryptography.CipherMode]::CBC
$aesManaged.Padding = [System.Security.Cryptography.PaddingMode]::Zeros
$aesManaged.BlockSize = 128
$aesManaged.KeySize = 256
if ($IV) {
if ($IV.getType().Name -eq "String") {
$aesManaged.IV = [System.Convert]::FromBase64String($IV)
}
else {
$aesManaged.IV = $IV
}
}
if ($key) {
if ($key.getType().Name -eq "String") {
$aesManaged.Key = [System.Convert]::FromBase64String($key)
}
else {
$aesManaged.Key = $key
}
}
$aesManaged
}
function Create-AesKey() {
$aesManaged = Create-AesManagedObject
$aesManaged.GenerateKey()
[System.Convert]::ToBase64String($aesManaged.Key)
}
function Encrypt-String($key, $unencryptedString) {
$bytes = [System.Text.Encoding]::UTF8.GetBytes($unencryptedString)
$aesManaged = Create-AesManagedObject $key
$encryptor = $aesManaged.CreateEncryptor()
$encryptedData = $encryptor.TransformFinalBlock($bytes, 0, $bytes.Length);
[byte[]] $fullData = $aesManaged.IV + $encryptedData
$aesManaged.Dispose()
[System.Convert]::ToBase64String($fullData)
}
function Decrypt-String($key, $encryptedStringWithIV) {
$bytes = [System.Convert]::FromBase64String($encryptedStringWithIV)
$IV = $bytes[0..15]
$aesManaged = Create-AesManagedObject $key $IV
$decryptor = $aesManaged.CreateDecryptor();
$unencryptedData = $decryptor.TransformFinalBlock($bytes, 16, $bytes.Length - 16);
$aesManaged.Dispose()
[System.Text.Encoding]::UTF8.GetString($unencryptedData).Trim([char]0)
}
$key = Create-AesKey
$key
$unencryptedString = "blahblahblah"
$encryptedString = Encrypt-String $key $unencryptedString
$backToPlainText = Decrypt-String $key $encryptedString
@D3vil0p3r
Copy link

D3vil0p3r commented Jun 27, 2021

Very nice project in PowerShell.
As block cipher mode, I see that we can only use the following: CBC,ECB,OFB,CFB,CTS.
How can we implement the GCM in this code?

@D3vil0p3r
Copy link

@alan-null
Copy link

@D3vil0p3r I created AES+GCM wrapper for my own purposes

You might find this helpful:
https://github.com/PowerShellLibrary/Crypto.AES

@D3vil0p3r
Copy link

@D3vil0p3r I created AES+GCM wrapper for my own purposes

You might find this helpful: https://github.com/PowerShellLibrary/Crypto.AES

Thank you @alan-null I appreciate this. I will give a look to it in the next days.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment