2017-07-30 81 views
1

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

此外,即使我不处置CryptoStream可能它的GC处置,如果超出范围,然后同时处理底层Stream,(这将是太早了,因为我仍然需要Stream)?

+0

你确定你需要基础流保持打开吗?因为它是这样设计的。 –

+0

最安全的方法是在处理cryptostream之后加密到内存流并使用其缓冲区。建议少量数据。 –

+0

@HenkHolterman是的。我需要散列一些流,并继续处理其余的没有散列CryptoStream。 – ispiro

回答

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); 
      } 
     } 
    } 

正如你可以看到你应该调用FlushFinalBlock方法是公共的,如果你不想处理一个CryptoStream。此方法清除输入和输出缓冲区,因此在使用的CryptoStream中不存储敏感信息。

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