.NET Framework 4.8环境下VS2022无法找到AesGcm类求助
问题根源
.NET Framework 4.8 并不原生支持 AesGcm 类,即便你安装了 System.Security.Cryptography.Algorithms NuGet包也无法使用——这个类是在.NET Core 3.0、.NET 5及以上版本才引入的,.NET Framework系列从未提供该类的官方实现。
解决方案
方案1:迁移到.NET 6+(推荐)
VS2022完全支持.NET 6及更高版本,迁移后可以直接使用原生的AesGcm类,无需额外依赖:
- 在VS2022中右键项目 → 属性 → 应用程序 → 目标框架,选择.NET 6或更高版本
- 移除原有的
System.Security.Cryptography.AlgorithmsNuGet包(.NET 6+已内置该类) - 直接使用
AesGcm编写加密逻辑,示例代码:
using System.Security.Cryptography; public static byte[] EncryptWithAesGcm(byte[] key, byte[] nonce, byte[] plaintext, byte[] associatedData) { using var aesGcm = new AesGcm(key); byte[] ciphertext = new byte[plaintext.Length]; byte[] tag = new byte[AesGcm.TagByteSizes.MaxSize]; aesGcm.Encrypt(nonce, plaintext, ciphertext, tag, associatedData); // 将密文和标签合并(Instagram的enc_password通常需要此格式) byte[] result = new byte[ciphertext.Length + tag.Length]; Buffer.BlockCopy(ciphertext, 0, result, 0, ciphertext.Length); Buffer.BlockCopy(tag, 0, result, ciphertext.Length, tag.Length); return result; }
方案2:在.NET Framework 4.8中使用第三方库实现AES-GCM
如果无法迁移框架,可以使用BouncyCastle库来实现AES-GCM加密:
- 通过NuGet安装
BouncyCastle包 - 编写加密逻辑,示例代码:
using Org.BouncyCastle.Crypto; using Org.BouncyCastle.Crypto.Engines; using Org.BouncyCastle.Crypto.Modes; using Org.BouncyCastle.Crypto.Parameters; using Org.BouncyCastle.Security; public static byte[] EncryptAesGcmWithBouncyCastle(byte[] key, byte[] nonce, byte[] plaintext, byte[] associatedData) { var gcmCipher = new GcmBlockCipher(new AesEngine()); var aeadParams = new AeadParameters(new KeyParameter(key), 128, nonce, associatedData); gcmCipher.Init(true, aeadParams); byte[] outputBuffer = new byte[gcmCipher.GetOutputSize(plaintext.Length)]; int processedLength = gcmCipher.ProcessBytes(plaintext, 0, plaintext.Length, outputBuffer, 0); gcmCipher.DoFinal(outputBuffer, processedLength); // 返回合并了密文和标签的结果,符合Instagram加密需求 return outputBuffer; }
内容的提问来源于stack exchange,提问作者Storm
相关产品推荐
相关产品推荐

