Do you need to explicitly call CryptoStream.Close() to close your CryptoStream object after you are done using it?

You can verify this with a simple program, stated below that shows that CryptoStream.Close() is explicitly not required.

The expected result should be 104 since 13 bytes should be allocated. We get 104 with a call to Close() or without calling Close().

   1: using System;
   2: using System.IO;
   3: using System.Security;
   4: using System.Security.Cryptography;
   6: namespace TestCryptoStream
   7: {
   8:     class Program
   9:     {
  10:         static void Main(string[] args)
  11:         {
  12:             DESCryptoServiceProvider csp = new DESCryptoServiceProvider();
  13:             ICryptoTransform trans = csp.CreateEncryptor();
  14:             MemoryStream ms = new MemoryStream();
  16:             using (CryptoStream cs = new CryptoStream(ms, trans, CryptoStreamMode.Write))
  17:             {
  18:                 cs.Write(new byte[100], 0, 100);
  19:                 //cs.Close();
  20:             }
  21:             Console.WriteLine(ms.ToArray().Length);
  22:         }
  23:     }
  24: }

However if you look through the MSDN link at link, it states to explicitly call CryptoStream.Close().

The part which states this at the above MSDN link is:

"You should always explicitly close your CryptoStream object after you are done using it by calling the Close method. Doing so flushes the stream and causes all remain blocks of data to be processed by the CryptoStream object. However, if an exception occurs before you call the Close method, the CryptoStream object might not be closed. To ensure that the Close method always gets called, place your call to the Close method within the finally block of a try/catch statement."

This seems to contradict the following bug listed at, which states:

"The behavior change in v2.0 was that Closing and Disposing the CryptoStream should be semantically the same. (See related bug This change was done for two reasons. First, we have consistency with other BCL streams which act in the same way. Secondly, if Dispose() did not Close(), then we would end up where Disposing a CryptoStream does not cause the final block to be flushed, therefore giving incorrect results."

Shamik Misra

Windows SDK

Comments (0)

Skip to main content