如果我有一个的CryptoStream
,我想传递给用户,幼稚的做法是
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;
}
我知道,当我处置的CryptoStream
标的的FileStream
will还可以设置。我到运行的问题是该怎么办与 rmCrypto
和转换
? RijndaelManaged的
和 ICryptoTransform的
是一次性的类,但处理流的不配置这两个对象。
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).
public CryptoStreamWrapper : Stream, IDisposable
{
public CryptoStreamWrapper(CryptoStream stream, RijndaelManaged rmCrypto, IDisposable transform)
{
this.transform = transform;
this.rmCrypto = rmCrypto;
this.stream = stream;
}
public void Dispose()
{
this.transform.Dispose();
this.rmCrypto.Dispose();
this.stream.Dispose();
}
}