C# AES:加密文件会导致“要加密的数据长度无效”。错误

Sab*_*eti 2 c# encryption aes rijndael

我有一个PDF文件。
当我想使用下面的代码对其进行加密时,Length of the data to encrypt is invalid.发生了错误:

  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);
  }
Run Code Online (Sandbox Code Playgroud)


使用CipherMode.CBCand PaddingMode.PKCS7,我没有任何错误。
但是由于我的客户,我必须使用AES/CFBNo Padding来加密文件。

任何想法这里发生了什么?

nto*_*rnl 5

块密码期望输入的长度是块大小的倍数。使用 AES,输入的长度必须是 16 的倍数。

您必须对明文应用某种填充,以便满足此要求。PKCS#7 填充是最佳选择。

然而,转念一想,CFB 模式将分组密码转换为流密码。流密码不需要填充。.NET 实现在这方面似乎被破坏了。