How to call Security.Cryptography.AesGcm and its method in PowerShell

Viewed 788

I want to encrypt some content by AES/GCM/No padding approach. I checked .NET 5 provide the class AesGcm

After install PowerShell 7, I am able to call this object:

PS C:\> [Security.Cryptography.AesGcm]

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     False    AesGcm                                   System.Object

However I cannot call its Encrypt method:

PS C:\> [Security.Cryptography.AesGcm].Encrypt()
InvalidOperation: Method invocation failed because [System.RuntimeType] does not contain a method named 'encrypt'.

Did I miss some library or my syntax is wrong?

1 Answers

You'll want to create an new instance of the AesGcm class

$aesGcm = [Security.Cryptography.AesGcm]::new($key)

I'm relatively new to the world of encryption however this seems to be the general flow here


# Use Rfc2898DerivedBytes class to generate a key
$keygen = [System.Security.Cryptography.Rfc2898DeriveBytes]::new("password", 64, 10000)
$key = $keygen.GetBytes(32)

# Initialize a new instance of AesGcm passing in the $key to the constructor
$aesGcm = [Security.Cryptography.AesGcm]::new($key)

# Create some secret message
$messageToEncrypt = "Some secret message"

# Convert the message to bytes
$messageBytes = [System.Text.Encoding]::UTF8.GetBytes($messageToEncrypt)

# Generate the nonce
$nonce = $keygen.GetBytes(12)

# Generate the empty byte arrays which will be filled with data during encryption
$tag = [byte[]]::new(16)
$assocData = [byte[]]::new(12)
$cipherText = [byte[]]::new($messageBytes.Length)

# Give Encrypt method everything it needs
$aesGcm.Encrypt($nonce, $messageBytes, $cipherText, $tag, $assocData)

# View the ciphertext in Base64
[System.Convert]::ToBase64String($cipherText)

# Generate the empty byte array for the unecrypted data which will be filled with data during decryption
$unecryptedText = [byte[]]::new($cipherText.Length)

# Give Decrypt everything it needs
$aesGcm.Decrypt($nonce, $cipherText, $tag, $unecryptedText, $assocData)

# View the unencrypted message
[System.Text.Encoding]::UTF8.GetString($unecryptedText)

# Don't forget to dispose
$aesGcm.Dispose()
$keygen.Dispose()
Related