Stopping decryption before EOF throws exception: Padding is invalid and cannot be removed

前端 未结 5 1776
刺人心
刺人心 2021-02-14 12:01

This is the scenario we have: We have huge encrypted files, in the order of gigabytes that we can decrypt correctly if we read them until the end. The problem arises when we ar

5条回答
  •  情话喂你
    2021-02-14 12:50

    Close calls Dispose(true) which calls FlushFinalBlock which throws the exception, because this is not really the final block.

    You can prevent this by overriding the Close method so that it doesn't call FlushFinalBlock:

    public class SilentCryptoStream : CryptoStream {
        public SilentCryptoStream(Stream stream, ICryptoTransform transform, CryptoStreamMode mode) :
            base(stream, transform, mode) {
        }
    
        public override void Close() {
            this.Dispose(false);
            GC.SuppressFinalize(this);
        }
    }
    

    (You also need to manually close the underlying stream.)

    is it valid to check if reader.EndOfStream is false and then capture the CryptographicException

    I think it's OK.

提交回复
热议问题