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

查看:24
本文介绍了从 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 and am doing 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 派生的任何类型,包括 MD5CryptoServiceProviderSHA1Managed.

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

HashAlgorithm 还定义了一个方法 ComputeHash,它接受一个 Stream 对象;但是,此方法将阻塞线程,直到流被消耗.使用 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天全站免登陆