能否CryptoStream的退还,仍然一切正常处置? [英] Can a CryptoStream be returned and still have everything dispose correctly?

查看:166
本文介绍了能否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 <一个href="http://stackoverflow.com/questions/19736631/can-a-cryptostream-leave-the-base-stream-open">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();
    }
}

这篇关于能否CryptoStream的退还,仍然一切正常处置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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