在C#中使用AES算法进行解密时,如果遇到“填充无效且无法删除”的错误,通常是因为解密过程中使用的密钥、初始化向量(IV)或加密模式与加密时使用的不一致,或者数据在传输过程中被篡改。
AES(Advanced Encryption Standard)是一种对称加密算法,它使用相同的密钥进行加密和解密。AES支持多种密钥长度(128位、192位和256位)和多种加密模式,如CBC(Cipher Block Chaining)、ECB(Electronic Codebook)等。填充是加密过程中的一个重要步骤,用于确保数据块的完整性。
以下是解决“填充无效且无法删除”错误的一些步骤:
以下是一个使用AES进行加密和解密的C#示例代码:
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
public class AesEncryptionExample
{
private static readonly byte[] Key = Encoding.UTF8.GetBytes("YourSecretKey123"); // 16 bytes for AES-128
private static readonly byte[] IV = Encoding.UTF8.GetBytes("InitializationVe"); // 16 bytes
public static string Encrypt(string plainText)
{
using (Aes aesAlg = Aes.Create())
{
aesAlg.Key = Key;
aesAlg.IV = IV;
ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);
using (MemoryStream msEncrypt = new MemoryStream())
{
using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
{
using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
{
swEncrypt.Write(plainText);
}
return Convert.ToBase64String(msEncrypt.ToArray());
}
}
}
}
public static string Decrypt(string cipherText)
{
using (Aes aesAlg = Aes.Create())
{
aesAlg.Key = Key;
aesAlg.IV = IV;
ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);
using (MemoryStream msDecrypt = new MemoryStream(Convert.FromBase64String(cipherText)))
{
using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
{
using (StreamReader srDecrypt = new StreamReader(csDecrypt))
{
return srDecrypt.ReadToEnd();
}
}
}
}
}
}
class Program
{
static void Main()
{
string original = "Hello, World!";
string encrypted = AesEncryptionExample.Encrypt(original);
string decrypted = AesEncryptionExample.Decrypt(encrypted);
Console.WriteLine($"Original: {original}");
Console.WriteLine($"Encrypted: {encrypted}");
Console.WriteLine($"Decrypted: {decrypted}");
}
}
通过以上步骤和示例代码,通常可以解决C# AES解密时遇到的“填充无效且无法删除”的问题。
领取专属 10元无门槛券
手把手带您无忧上云