If I have a CryptoStream
that I want to pass back to the user, the naïve approach would be
public Stream GetDecryptedFileStream(string inputFile, byte[] key, byte[] iv)
{
var fsCrypt = new FileStream(inputFile, FileMode.Open, FileAccess.Read, FileShare.Read);
var rmCrypto = new RijndaelManaged();
var transform = rmCrypto.CreateDecryptor(key, iv);
var cs = new CryptoStream(fsCrypt, transform, CryptoStreamMode.Read);
return cs;
}
I know that when I dispose the CryptoStream
the underlying FileStream
will also be disposed. The issue I am running in to is what do I do with rmCrypto
and transform
? RijndaelManaged
and ICryptoTransform
are disposable classes, but disposing of the stream does not dispose those two objects.
What is the correct way to handle this situation?
I'd consider creating your own class that wraps the stream and then you can manage the disposal of these. Somethings along these lines (sorry - don't know the type of the transform object off top of my head).
Ian beat me to the basic concept (go upvote him), but CryptoStream itself is not sealed so it is trivial to make a derived class that wraps the things that need to be disposed.
Used like