如何在PowerShell中调用Security.Cryptography.AesGcm及其方法 [英] How to call Security.Cryptography.AesGcm and its method in PowerShell

查看:18
本文介绍了如何在PowerShell中调用Security.Cryptography.AesGcm及其方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过 AES/GCM/No padding 方法加密一些内容.我检查了 .NET 5 提供的类 AesGcm

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

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

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?

推荐答案

您需要创建 AesGcm 类的新实例

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

这篇关于如何在PowerShell中调用Security.Cryptography.AesGcm及其方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆