C#AES:加密文件的原因"数据长度加密无效"。错误 [英] C# AES: Encrypt a file causes "Length of the data to encrypt is invalid." error
问题描述
我有一个PDF文件。
当我想用下面的代码的它来加密加密数据的长度是无效的。
错误发生了:
I have a PDF File.
When I want to encrypt it using codes below the Length of the data to encrypt is invalid.
error occurred:
string inputFile = @"C:\sample.pdf";
string outputFile = @"C:\sample_enc.pdf";
try
{
using (RijndaelManaged aes = new RijndaelManaged())
{
byte[] key = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 };
byte[] iv = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 };
aes.Key = key;
aes.IV = iv;
aes.Mode = CipherMode.CFB;
aes.Padding = PaddingMode.None;
aes.KeySize = 128;
aes.BlockSize = 128;
using (FileStream fsCrypt = new FileStream(outputFile, FileMode.Create))
{
using (ICryptoTransform encryptor = aes.CreateEncryptor(key,iv))
{
using (CryptoStream cs = new CryptoStream(fsCrypt, encryptor, CryptoStreamMode.Write))
{
using (FileStream fsIn = new FileStream(inputFile, FileMode.Open))
{
int data;
while ((data = fsIn.ReadByte()) != -1)
{
cs.WriteByte((byte)data);
}
}
}
}
}
}
}
catch (Exception ex)
{
// Length of the data to encrypt is invalid.
Console.WriteLine(ex.Message);
}
使用 CipherMode .CBC
和 PaddingMode.PKCS7
,我没有任何错误。
但是因为我的客户,我必须使用文件加密的 AES / CFB 是没有填充
With CipherMode.CBC
and PaddingMode.PKCS7
, I don't have any errors.
But because of my client, I have to encrypt the file using AES/CFB with No Padding.
任何想法这里发生了什么?
Any ideas what's happening here?
推荐答案
一个分组密码输入期望用长度是块大小的倍数。随着AES,输入的长度必须是16的倍数。
A block cipher expects input with a length that is a multiple of the block size. With AES, the length of the input must be a multiple of 16.
您必须向明文某种填充,使这一要求得到满足。 PKCS#7填充是最好的选择。
You must apply some sort of padding to the plaintext so that this requirement is satisfied. PKCS#7 padding is the best choice.
不过,经过再三考虑,CFB模式将块加密成一个流密码。流密码不需要填充。的.NET实现似乎在这方面被打破。
However, on second thought, CFB mode turns a block cipher into a stream cipher. Stream ciphers don't need padding. The .NET implementation seems to be broken in this regard.
这篇关于C#AES:加密文件的原因"数据长度加密无效"。错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!