我正面临AES填充问题。 我正在使用Alcides Soares FIlho在(generate a 128-bit string in C#)中建议的代码。 请注意我的加密端代码是......
private string Encrypt(string clearText)
{
string EncryptionKey = "I love chocolate";
byte[] clearBytes =
System.Text.Encoding.Unicode.GetBytes(clearText);
using (Aes encryptor = Aes.Create())
{
Rfc2898DeriveBytes pdb = new
Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e,
0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
encryptor.Key = pdb.GetBytes(32);
encryptor.IV = pdb.GetBytes(16);
using (MemoryStream ms = new MemoryStream())
{
using (CryptoStream cs = new CryptoStream(ms,
encryptor.CreateEncryptor(), CryptoStreamMode.Write))
{
cs.Write(clearBytes, 0, clearBytes.Length);
cs.Close();
}
clearText = Convert.ToBase64String(ms.ToArray());
}
}
return clearText;
}
另外,我传递给明文的价值是" Z4YAZZSQ 001F295E2589AWAN HANS"。加密正在发生。但解密失败了。
解密边码
private string Decrypt(string cipherText)
{
string EncryptionKey = "I love chocolate";
byte[] cipherBytes = Convert.FromBase64String(cipherText);
using (Aes encryptor = Aes.Create())
{
Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey,
new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65,
0x64, 0x65, 0x76 });
encryptor.Key = pdb.GetBytes(32);
encryptor.IV = pdb.GetBytes(16);
using (MemoryStream ms = new MemoryStream())
{
using (CryptoStream cs = new CryptoStream(ms,
encryptor.CreateDecryptor(), CryptoStreamMode.Write))
{
cs.Write(cipherBytes, 0, cipherBytes.Length);
cs.Close();
}
cipherText =
System.Text.Encoding.Unicode.GetString(ms.ToArray());
}
}
return cipherText;
}
我应该能够回来了#34; Z4YAZZSQ 001F295E2589AWAN HANS"
但是会出现以下错误"填充无效,无法删除" 请提出解决方案。
答案 0 :(得分:0)
每当你使用填充时,都需要进行最后一次调用,让代码知道是时候添加填充了。这就是你需要致电FlushFinalBlock
。