如果我有一个 CryptoStream
我想传回给用户,天真的方法是
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 also be disposed .我遇到的问题是如何处理 rmCrypto
和 transform
? RijndaelManaged
和 ICryptoTransform
是一次性类,但处理流不会处理这两个对象。
处理这种情况的正确方法是什么?
最佳答案
Ian 在基本概念 (go upvote him) 上先于我,但 CryptoStream 本身不是密封的,因此创建一个派生类来包装需要处理的东西是微不足道的。
/// <summary>
/// Creates a class that creates a <see cref="CryptoStream"/> and wraps the disposing action of all the associated objects
/// </summary>
class ReturnableCryptoStream : CryptoStream
{
private readonly ICryptoTransform _transform;
private readonly IDisposable _algorithm;
public ReturnableCryptoStream(Stream stream, ICryptoTransform transform, CryptoStreamMode mode)
: this(stream, transform, mode, null)
{
}
public ReturnableCryptoStream(Stream stream, ICryptoTransform transform, CryptoStreamMode mode, IDisposable algorithm)
: base(stream, transform, mode)
{
_transform = transform;
_algorithm = algorithm;
}
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
if (disposing)
{
if (_transform != null)
_transform.Dispose();
if (_algorithm != null)
_algorithm.Dispose();
}
}
}
像这样使用
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 ReturnableCryptoStream(fsCrypt, transform, CryptoStreamMode.Read, rmCrypto);
return cs;
}
关于c# - 能否返回 CryptoStream 并仍然正确处理所有内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24188644/