【问题标题】:Disposing CryptoStream vs disposing underlying Stream?处置 CryptoStream 与处置底层流?
【发布时间】:2018-01-06 04:34:06
【问题描述】:

我有一个 CryptoStream 和一个基础 Stream。我不能使用using 块来处理CryptoStream,因为这也会处理我需要保持打开状态的底层Stream。解决方案似乎只是忽略CryptoStream 并在需要时处理Stream。但也许保留对CryptoStream 的引用并处理它以防止某些资源泄漏很重要?

此外,即使我不处置CryptoStream,如果它超出范围,GC 也会处置它,然后还处置底层的Stream,(这还为时过早,因为我仍然需要@ 987654331@)?

【问题讨论】:

  • 您确定需要基本流保持打开状态吗?因为它被设计成这样是有原因的。
  • 最安全的方法是加密到内存流并在处理完加密流后使用其缓冲区。推荐用于小数据。
  • @HenkHolterman 是的。我需要对一些流进行哈希处理,并在没有哈希 CryptoStream 的情况下继续处理其余部分。
  • 否则,请确保调用 FlushFinalBuffer 和 Flush 并保留对 CryptoStgream 的引用,直到完成。
  • @HenkHolterman 我确实刷新了 CryptoStream。

标签: c# .net encryption stream garbage-collection


【解决方案1】:

来自CryptoStream.cs (ln 695)

    protected override void Dispose(bool disposing) {
        try {
            if (disposing) {
                if (!_finalBlockTransformed) {
                    FlushFinalBlock();
                }
                _stream.Close();
            }                
        }
        finally {
            try {
                // Ensure we don't try to transform the final block again if we get disposed twice
                // since it's null after this
                _finalBlockTransformed = true;
                 // we need to clear all the internal buffers
                 if (_InputBuffer != null)
                     Array.Clear(_InputBuffer, 0, _InputBuffer.Length);
                 if (_OutputBuffer != null)
                     Array.Clear(_OutputBuffer, 0, _OutputBuffer.Length);

                 _InputBuffer = null;
                 _OutputBuffer = null;
                 _canRead = false;
                 _canWrite = false;
            }
            finally {
                 base.Dispose(disposing);
            }
        }
    }

如您所见,如果您不想处置CryptoStream,则应调用公共的FlushFinalBlock 方法。此方法会清除输入和输出缓冲区,因此在使用的CryptoStream 中不会存储敏感信息。

GC 是否会关闭底层的Stream?没有。为此,必须使用true 作为其参数值调用Dispose 方法,但这只能在Stream.Close 方法中完成(从Stream.Dispose 调用)。即使CryptoStream 会实现终结器,在执行Finalize 时对引用的对象调用Dispose 也不是一个好习惯。终结器只能用于释放非托管资源。

【讨论】:

    猜你喜欢
    • 2011-03-31
    • 1970-01-01
    • 2017-06-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-24
    • 1970-01-01
    • 1970-01-01
    • 2018-11-01
    相关资源
    最近更新 更多