Search code examples
c#cng

CA2202: Object can be disposed of more than once


I'm getting the following warning in the following code snippet but I cannot understand why

warning CA2202: Microsoft.Usage : Object 'memStream' can be disposed more than once in method 'Encrypt(string)'. To avoid generating a System.ObjectDisposedException you should not call Dispose more than one time on an object.

Code:

string Encrypt(string toEncrypt)
{
    byte[] key = ...
    byte[] iv = ...

    using (AesCng aes = new AesCng())
    using (ICryptoTransform encryptor = aes.CreateEncryptor(key, iv))
    using (MemoryStream memStream = new MemoryStream())
    using (CryptoStream cryptoStream = new CryptoStream(memStream, encryptor, CryptoStreamMode.Write))
    {
        UTF7Encoding encoder = new UTF7Encoding();
        byte[] bytes = encoder.GetBytes(toEncrypt);

        cryptoStream.Write(bytes, 0, bytes.Length);
        cryptoStream.FlushFinalBlock();

        return Convert.ToBase64String(memStream.ToArray());
    }
}

The CryptoStream object, to the best of my knowledge, does not dispose of the passed in Stream when it itself is disposed. So how is it possible that the variable memStream can be disposed of more than once?

Many thanks.


Solution

  • CryptoStream.Dispose() will, by default, dispose the underlying stream. If you don't want that behavior you need to use the constructor overload that explicitly makes the underlying stream remain open when the CryptoStream is disposed.

    You can see how that's implemented here.