AES解密输入数据不是完整的块

时间:2017-02-03 19:49:20

标签: c# encryption aes

我尝试加密string并使用AES对其进行描述。加密工作正常但我收到The input data is not a complete block的解密错误。我的填充是否有问题?

var aes = System.Security.Cryptography.Aes.Create();
aes.GenerateKey();
aes.GenerateIV();
aes.Mode = CipherMode.CBC;
aes.Padding = PaddingMode.PKCS7;

var desEncrypter = aes.CreateEncryptor();
var buffer = System.Text.ASCIIEncoding.ASCII.GetBytes(text);

finalV = Convert.ToBase64String(desEncrypter.TransformFinalBlock(buffer, 0, buffer.Length));

var desDecrypter = aes.CreateDecryptor();
var buff = System.Text.Encoding.ASCII.GetBytes(finalV);

var origValue = desDecrypter.TransformFinalBlock(buff , 0, buff .Length);

1 个答案:

答案 0 :(得分:5)

您通过将字节转换为Base64来创建finalV。要将其转换回字节,您需要调用Convert.FromBase64String(finalV)

您正在调用ASCII.GetBytes(finalV),它会获取表示Base64文本的字节,而不是原始字节。

修改

不知道你遇到了什么问题,但这里的代码是基于你的代码,所以你可以将其区分开来,看看你收到错误的地方:

string text = "ABC";

var aes = System.Security.Cryptography.Aes.Create();
aes.GenerateKey();
aes.GenerateIV();
aes.Mode = CipherMode.CBC;
aes.Padding = PaddingMode.PKCS7;

var desEncrypter = aes.CreateEncryptor();
var buffer = System.Text.ASCIIEncoding.ASCII.GetBytes(text);

var finalV = Convert.ToBase64String(desEncrypter.TransformFinalBlock(buffer, 0, buffer.Length));

var desDecrypter = aes.CreateDecryptor();
var buff = Convert.FromBase64String(finalV);

var origValue = desDecrypter.TransformFinalBlock(buff, 0, buff.Length);
string result = Encoding.ASCII.GetString(origValue);
Console.WriteLine(result);