.NET 7文件加解密异常:The input data is not a complete block
问题原因及修复方案
错误根源
你在加密方法中犯了一个关键错误:直接将原文件流的内容写入输出文件流,完全没有通过CryptoStream进行加密处理。这导致输出文件实际上是原文件的未加密副本,而非AES加密后的密文。
当解密时,AES解密器要求输入数据必须是其块大小(默认16字节)的整数倍(AES是块加密算法,需要完整的块进行解密)。如果原文件长度不是16字节的整数倍,解密器读取到不完整的块时就会抛出「The input data is not a complete block」异常。
修复步骤
在Encryption方法中,需要将原文件流的数据写入CryptoStream而非直接写入输出文件流,这样数据才会经过AES加密器处理,生成符合块大小要求的密文。同时建议显式调用FlushFinalBlock()确保所有加密数据都被写入文件。
修正后的完整代码
using System; using System.Security.Cryptography; using System.IO; internal class Program { private static void Main(string[] args) { Console.WriteLine("Original file name"); string inputfilename = Console.ReadLine(); Console.WriteLine("Encrypted file"); string outputfilename = Console.ReadLine(); Console.WriteLine("Decrypt file name"); string decrypt = Console.ReadLine(); byte[] key; byte[] IV; (key, IV) = Encryption(inputfilename, outputfilename); Decryption(key, IV, outputfilename, decrypt); Console.WriteLine("Is ready!"); } public static (byte[], byte[]) Encryption(string inputfilename, string outputfilename) { using (var readStream = File.OpenRead(inputfilename)) using (var createstream = File.OpenWrite(outputfilename)) using (var aes = Aes.Create()) using (var encryptor = aes.CreateEncryptor()) using (var cstream = new CryptoStream(createstream, encryptor, CryptoStreamMode.Write)) { // 修正:将数据写入CryptoStream,由加密器处理后再写入文件 readStream.CopyTo(cstream); // 确保缓存的加密数据全部写入文件,添加必要的填充 cstream.FlushFinalBlock(); return (aes.Key, aes.IV); } } public static void Decryption(byte[] key, byte[] IV, string inputfile, string outputfile) { using (var readstream = File.OpenRead(inputfile)) using (var createstream = File.Create(outputfile)) using (var aes = Aes.Create()) { aes.Key = key; aes.IV = IV; using (var decryptor = aes.CreateDecryptor(aes.Key, aes.IV)) using (var cstream = new CryptoStream(readstream, decryptor, CryptoStreamMode.Read)) { cstream.CopyTo(createstream); } } } }
补充说明
FlushFinalBlock()会处理加密器缓存的数据,并自动添加填充(当原数据长度不是块大小整数倍时),保证生成的密文是完整的块结构,解密时不会出现块不完整的问题。- 你的解密方法逻辑是正确的,无需修改,只要加密后的密文格式正常,就能完成解密。
内容的提问来源于stack exchange,提问作者8K Tek
相关产品推荐
相关产品推荐

