Does disposing a CryptoStream flush the final block?

Issue

From the Microsoft .NET API the following information can be extracted:

  • using will call the implementation of IDisposable.Dispose();
  • IDisposable.Dispose() should call Flush() on any Stream instance;
  • CryptoStream.Close() will call CryptoStream.FlushFinalBlock().

However, this seems to leave a gap in the specification: will disposing of a CryptoStream instance also call CryptoStream.FlushFinalBlock(), and if so, where is this documented?

Solution

Dispose() calls FlushFinalBlock() if it has not already been called. This is also in the documentation, however not centrally, but distributed:

CryptoStreams does not overload Close() or the (parameterless) public Dispose(), so the implementations of the Stream class are called.

The documentation of Stream#Dispose() (s. Remarks) states:

This method disposes the stream, by writing any changes to the backing store and closing the stream to release resources.

This is consistent with the source code (from .NET Framework 4.8). Stream#Dispose() calls Stream#Close().

The documentation of CryptoStream#FlushFinalBlock() (s. Remarks) says (as already described by you):

Calling the Close method will call FlushFinalBlock.

This is again consistent with the source code (from .NET Framework 4.8). Close() calls (among other things) the protected (virtual) overload Dispose(true), which is overridden in CryptoStream, see CryptoStream#Dispose(bool disposing), and which calls FlushFinalBlock() if it has not already been called (i.e. depending on _finalBlockTransformed),

These details are described in CryptoStream#Dispose(Boolean) (s. Remarks):

This method is called by the public Dispose() method and the Finalize method. Dispose() invokes the protected Dispose(Boolean) method with the disposing parameter set to true…

Answered By – Topaco

Answer Checked By – Jay B. (AngularFixing Admin)

Leave a Reply

Your email address will not be published.