在 C# 中,使用 AES 算法以 CBC 模式进行解密需要提供密钥(Key)和初始化向量(IV)。以下是一个使用 System.Security.Cryptography 命名空间中的类实现 AES CBC 模式解密的基本示例。
示例代码
csharp
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;public class AesCbcDecryptor{
public static string DecryptStringFromBytes_Aes(byte[] cipherText, byte[] Key, byte[] IV)
{
if (cipherText == null || cipherText.Length <= 0)
throw new ArgumentNullException(“cipherText”);
if (Key == null || Key.Length <= 0)
throw new ArgumentNullException(“Key”);
if (IV == null || IV.Length <= 0)
throw new ArgumentNullException(“IV”);
string plaintext = null;
using (Aes aesAlg = Aes.Create())
{
aesAlg.Key = Key;
aesAlg.IV = IV;
aesAlg.Mode = CipherMode.CBC;
aesAlg.Padding = PaddingMode.PKCS7;
ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);
using (MemoryStream msDecrypt = new MemoryStream(cipherText))
{
using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
{
using (StreamReader srDecrypt = new StreamReader(csDecrypt))
{
plaintext = srDecrypt.ReadToEnd();
}
}
}
}
return plaintext;
}
}
如何使用这个方法
csharp
byte[] myKey = Encoding.UTF8.GetBytes("YourKeyHere___16Bytes"); // 密钥 (16, 24 或 32 字节)
byte[] myIV = Encoding.UTF8.GetBytes("YourIVHere__16Bytes"); // 初始化向量 (16 字节)
byte[] cipherText = Convert.FromBase64String("YourEncryptedText"); // 加密文本(字节数组)string decryptedText = AesCbcDecryptor.DecryptStringFromBytes_Aes(cipherText, myKey, myIV);Console.WriteLine(“Decrypted text: “ + decryptedText);
注意事项
- 确保
Key和IV的长度符合 AES 的要求。AES 支持 128 位(16 字节)、192 位(24 字节)和 256 位(32 字节)长的密钥,而 IV 总是 128 位(16 字节)长。 - 这个例子中假设加密文本是以 Base64 编码的。如果你的加密文本是以其他方式编码的,确保正确地转换为字节数组。
PaddingMode.PKCS7是解密时使用的填充模式,它应与加密时使用的填充模式一致。- 错误的
Key或IV会导致解密失败,可能会抛出异常,例如CryptographicException。 - 此代码仅用于演示目的,在生产环境中使用时,请确保密钥和 IV 的安全性,避免硬编码在代码中。
Aes类是 IDisposable 的,所以使用using语句确保资源被正确释放。
在使用此代码进行 AES CBC 模式解密时,请确保你理解所涉及的密码学原理,以及在实际应用中涉及的安全考虑。
主题授权提示:请在后台主题设置-主题授权-激活主题的正版授权,授权购买:RiTheme官网
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。客服QQ:2350288510

