I'm getting an MDA after running this code for the second time in a loop (with a different file
parameter:
byte[] encryptedData = File.ReadAllBytes(file); // before this line it throws, see exception below
long dataOffset;
using (var stream = new MemoryStream(encryptedData))
using (var reader = new BinaryReader(stream))
{
// ... read header information which is not encrypted
}
using (var stream = new MemoryStream(encryptedData))
{
stream.Seek(dataOffset, SeekOrigin.Begin);
using (var aesAlg = new AesCryptoServiceProvider())
using (var decryptor = aesAlg.CreateDecryptor(key, iv))
using (var csDecrypt = new CryptoStream(stream, decryptor, CryptoStreamMode.Read))
using (var reader = new BinaryReader(csDecrypt))
{
decrypted = reader.ReadBytes((int)(encryptedData.Length - dataOffset));
}
}
The MDA is the following:
A SafeHandle or CriticalHandle of type 'Microsoft.Win32.SafeHandles.SafeCapiKeyHandle' failed to properly release the handle with value 0x000000001BEA9B50. This usually indicates that the handle was released incorrectly via another means (such as extracting the handle using DangerousGetHandle and closing it directly or building another SafeHandle around it.)
The stacktrace is not too informative:
mscorlib.dll!System.Runtime.InteropServices.SafeHandle.Dispose(bool disposing) + 0x10 bytes mscorlib.dll!System.Runtime.InteropServices.SafeHandle.Finalize() + 0x1a bytes
I suspect that one of the streams or the CryptoServiceProvider is not released for some reason. Apart from this, the code runs fine and does what's expected. The MDA occurs before the control reached the first line of the method.
How can I do it properly? What is the root cause of the problem?