我从使用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;
}
答案 0 :(得分:1)
使用无参数CreateEncryptor()
/ CreateDecryptor()
方法,或传递IV。如果您使用no-param版本,则应拨打CreateIV
并将结果值存储在.IV
中。