Memory leaks???

Jun 1, 2012 at 4:02 PM

I think this project suffer some kind of memory leak. I created an application to perform as many AES encryption/decryption per second as the machine can, but the memory consumption increase without stop.

 

My code to decryptthat is repeated:

 

                using (var encryptionObject = ClrSecurity.Cryptography.AesCng.Create())
                using (MemoryStream ms = new MemoryStream())
                using (CryptoStream cs = new CryptoStream(ms, encryptionObject.CreateDecryptor(key.Key, key.IV), CryptoStreamMode.Write))
                {
                    cs.Write(data, 0, data.Length);
                    cs.FlushFinalBlock();
                    return ms.ToArray();
                }

 

and to encrypt:

                using (var encryptionObject = ClrSecurity.Cryptography.AesCng.Create())
                using (MemoryStream ms = new MemoryStream())
                using (CryptoStream cs = new CryptoStream(ms, encryptionObject.CreateEncryptor(key.Key, key.IV), CryptoStreamMode.Write))
                {
                    cs.Write(data, 0, data.Length);
                    cs.FlushFinalBlock();
                    return ms.ToArray();
                }

Am I using in a wrong way the library?

 

Coordinator
Jun 12, 2012 at 5:29 PM

While your code is disposing of the CryptoStreams, it's not disposing of the ICryptoTransforms that the stream uses.   Specifically, the encryptionObject.CreateEncryptor and CreateDecryptor objects are never disposed, which means their underlying resources will not be cleaned up until the GC kicks in.

To fix this, you can create those outside of the cryptostream and dispose of them explciitly after closing down the stream.

-Shawn