可以返回CryptoStream,还能正确处理一切吗? [英] Can a CryptoStream be returned and still have everything dispose correctly?

查看:167
本文介绍了可以返回CryptoStream,还能正确处理一切吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个 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 也将被处理。我正在运行的问题是如何使用 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();
    }
}

这篇关于可以返回CryptoStream,还能正确处理一切吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆