. net中AES加密的填充问题
本文关键字:填充 问题 加密 AES net | 更新日期: 2023-09-27 18:16:27
我开始使用ECB,因为我听说它是最容易开始的,所以我创建了一个控制台应用程序,它接受输入加密,然后将其解密,并输出加密文本和解密文本。这一切都很完美。我去尝试使用CBC从头开始创建一个新程序,我得到一个错误:"填充无效,无法删除。"从我看来,我做的每件事都是正确的,有人能告诉我我的问题是什么吗?我在博客和这个网站上试过了所有我能找到的东西,但都无济于事。异常发生在DecryptData方法中的:DecryptedText = srDecrypt.ReadToEnd()
行。
RijndaelManaged rijm = new RijndaelManaged();
//more variables here
protected void Page_Load(object sender, EventsArgs e)
{
//Convert Key from string to Byte Array Here
rijm.BlockSize = 128;
rijm.KeySize = 256;
rijm.Key = keyByteArray;
rijm.Mode = CipherMode.CBC;
rijm.Padding = PaddingMode.PKCS7;
ICryptoTransform crypt = rijm.CreateEncryptor(keyByteArray, null);
using(crypt)
{
byte[] value1Cipher = EncryptData(crypt, value1);
byte[] value2Cihper = EncryptData(crypt, value2);
encryptedValue1 = Convert.ToBase64String(vaue1Cipher);
encrpytedValue2 = Convert.ToBase64String(value1Cipher);
}
ICryptoTransform decrypt = rijm.CreateDecryptor(keyByteArray, null);
using (decrypt)
{
decryptedValue1 = DecryptData(decrypt, encryptedValue1); //string
decryptedValue2 = DecryptData(decrypt, encrpytedValue2); //string
}
//... Do something with the values here.
}
private byte[] EncryptData(ICryptoTransform encrypt, string text)
{
var stream = new MemoryStream();
using (var cryptoStream = new CryptoStream(stream, encrypt, CryptoStreamMode.Write))
{
using (var writer = new StreamWriter(cryptoStream))
{
writer.Write(text);
}
}
return stream.ToArray();
}
private string DecryptData(ICryptoTransform decrypt, string cipherText)
{
string decryptedText = null;
byte[] text = Convert.FromBase64String(cipherText);
using (MemoryStream msDecrypt = new MemoryStream(text))
using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decrypt, CryptoStreamMode.Read))
using (StreamReader srDecrypt = new StreamReader(csDecrypt))
decryptedText = srDecrypt.ReadToEnd();
return decryptedText;
}
要么使用无参数的CreateEncryptor()
/CreateDecryptor()
方法,要么传递一个IV。如果使用无参数的版本,您应该调用CreateIV
并将结果值存储在.IV
中。