来自未知长度在C#中的流计算哈希 [英] Compute a hash from a stream of unknown length in C#

查看:131
本文介绍了来自未知长度在C#中的流计算哈希的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是C#中的最佳解决方案用于计算对飞MD5像一个未知长度的流的哈希?具体地讲,我要计算从通过网络接收的数据的散列。我知道我做了接收数据时,发送方终止连接,所以我不知道提前长度

What is the best solution in C# for computing an "on the fly" md5 like hash of a stream of unknown length? Specifically, I want to compute a hash from data received over the network. I know I am done receiving data when the sender terminates the connection, so I don't know the length in advance.

- 现在我使用MD5 ,但是这需要在数据第二遍之后它被保存和写入磁盘。我宁愿哈希它在的地方,因为它从网络的用武之地。

- Right now I am using md5, but this requires a second pass over the data after it's been saved and written to disk. I'd rather hash it in place as it comes in from the network.

推荐答案

MD5,像其他散列函数,不。需要两个通行证

MD5, like other hash functions, does not require two passes.

要启动:

HashAlgorithm hasher = ..;
hasher.Initialize();



由于每个数据块到达:

As each block of data arrives:

byte[] buffer = ..;
int bytesReceived = ..;
hasher.TransformBlock(buffer, 0, bytesReceived, null, 0);

要完成和检索哈希:

hasher.TransformFinalBlock(new byte[0], 0, 0);
byte[] hash = hasher.Hash;

本模式适用于从的HashAlgorithm ,其中 MD5CryptoServiceProvider SHA1Managed

This pattern works for any type derived from HashAlgorithm, including MD5CryptoServiceProvider and SHA1Managed.

的HashAlgorithm 还定义了一个方法 ComputeHash 这需要一个对象;然而,这种方法会阻塞线程,直到流被消耗。使用 TransformBlock 办法允许异步散,即计算为数据到达,而无需使用一个线程。

HashAlgorithm also defines a method ComputeHash which takes a Stream object; however, this method will block the thread until the stream is consumed. Using the TransformBlock approach allows an "asynchronous hash" that is computed as data arrives without using up a thread.

这篇关于来自未知长度在C#中的流计算哈希的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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