The member methods of cryptostream are indeed a bit confusing. It is not very confusing to study it carefully. It is also in line with some naming rules in. net.
Let's talk about flush. I think this is more important.
First, the flush method inherited from the stream class does not execute the flush operation of the stream. The flush method of the cryptostream rewrite base class is empty:
Cryptostream uses its own flushfinalblock to perform the so-called flush operation (does Microsoft want to use this method to remind developers that the flush operation of cryptostream is very important ?), This operation will write data in the internal buffer zone and clear the Buffer Zone. Note that because cryptostream contains sensitive security information, the buffer zone should be cleared as soon as possible. (Like stream, flushfinalblock is also called to end cryptostream. The operation to end cryptostream will be detailed later ).
The code can also be used for verification:
// + Using system. IO;
// + Using system. Security. cryptography;
Using (var aes = AES. Create ())
Using (var ms = new memorystream ())
Using (VAR cs = new cryptostream (MS, AES. createencryptor (), cryptostreammode. Write ))
{
CS. writebyte (1 );
Console. writeline (Ms. Length );
Ms. Flush ();
Console. writeline (Ms. Length );
CS. flushfinalblock ();
Console. writeline (Ms. Length );
}
The code above will be output on my computer (. NET 4.0:
0
0
16
Data is actually written only after flushfinalblock is called, and the stream. Flush method is invalid!
Next, let's take a look at the method for clearing cryptostream resources:
Class cryptostream
// Stream inherits idisposable
// Call flushfinalblock () and call close () of the internal stream ()
Protected void dispose ();
// Inherits from the stream class and calls dispose (protected)
Public void close ();
// Call close ()
Public void clear ();
// Call close ()
Public void dispose ();
In fact, the dispose, clear, and close operations of cryptostream are the same operation. So why are there so many methods? This may be related to the built-in class library name of. net. First, cryptostream inherits from stream, and the latter inherits the idisposable interface, which naturally requires the dispose method. Next, the stream class-related classes (such as filestream, streamreader ......) Both have the close method, which is equivalent to the dispose method. Finally, all cryptographic classes in. Net Security have the clear method, which is equivalent to dispose. Cryptostream belongs to both stream and cryptography types, so the equivalent methods of so many dispose methods are strange.
Query the clear method in ilspy. We can see that many types of system. Security. cryptography have this method. (Generally, idisposable is inherited)