gpt4 book ai didi

c# - 能否返回 CryptoStream 并仍然正确处理所有内容?

转载 作者:太空狗 更新时间:2023-10-29 20:04:38 26 4
gpt4 key购买 nike

如果我有一个 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 .我遇到的问题是如何处理 rmCryptotransformRijndaelManagedICryptoTransform 是一次性类,但处理流不会处理这两个对象。

处理这种情况的正确方法是什么?

最佳答案

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com