如何在 PowerShell 中调用 Security.Cryptography.AesGcm 及其方法

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

我想通过 AES/GCM/No 填充方法加密一些内容。我检查了 .NET 5 提供了 class AesGcm

安装 PowerShell 7 后,我可以调用这个对象:

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

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

但是我不能调用它的加密方法:

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

我是不是错过了一些库或者我的语法有误?

您需要创建 AesGcm 的新实例 class

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

我对加密世界还比较陌生,但这似乎是这里的一般流程


# 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()