我需要计算相当大的文件(千兆字节)的校验和。这可以使用以下方法来完成:
private byte[] calcHash(string file)
{
System.Security.Cryptography.HashAlgorithm ha = System.Security.Cryptography.MD5.Create();
FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read);
byte[] hash = ha.ComputeHash(fs);
fs.Close();
return hash;
}
然而,这些文件通常是预先以缓冲方式写入的(例如一次写入 32mb)。我确信我看到了哈希函数的重写,它允许我在写入的同时计算 MD5(或其他)哈希,即:计算一个缓冲区的哈希,然后将所得哈希输入下一次迭代。
像这样的东西:(伪代码)
byte [] hash = new byte [] { 0,0,0,0,0,0,0,0 };
while(!eof)
{
buffer = readFromSourceFile();
writefile(buffer);
hash = calchash(buffer, hash);
}
hash 现在类似于在整个文件上运行 calcHash 函数所完成的操作。
现在,我在 .Net 3.5 Framework 中找不到任何类似的覆盖,我是在做梦吗?它是否从未存在过,或者我只是不擅长搜索?之所以同时进行写入和校验和计算,是因为由于文件较大,因此这是有意义的。