C# “Bad Data” exception when decrypting encrypted file

前端 未结 3 1472
眼角桃花
眼角桃花 2021-01-15 05:06

Hey I\'m very new to encryption and decryption, or even the c# language to be honest. Basically, I have a tcp chat server that \"saves\" logs and encrypts the text file. Thi

3条回答
  •  隐瞒了意图╮
    2021-01-15 05:33

    Here:

        cryptostream.Write(byteArrayInput, 0, byteArrayInput.Length);
        fsIn.Close();
        fsOut.Close();
    

    You're closing fsOut directly, without closing cryptostream. That means the crypto stream doesn't get the chance to flush any final blocks etc.

    Additionally:

    • Use using statements instead of manually calling Close or Dispose
    • You're currently calling Read once, and assuming it will read all the data - you're not checking the return value. (You're also removing the last byte of the input file for some reason... why?) In general, you should loop round, reading into a buffer and then writing out however many bytes you read, until the Read method returns 0. If you're using .NET 4, Stream.CopyTo is your friend.

提交回复
热议问题