我正在尝试通过循环从FileStream中读取1024字节并使用TransformBlock函数对文件进行哈希处理。我需要这样做来理解将多个字节数组哈希到一个哈希值的机制。这将使我不仅可以哈希文件,还可以哈希文件夹。我使用了这个stackoverflow问题: Hashing multiple byte[]'s together into a single hash with C#?和这个msdn示例:http://msdn.microsoft.com/en-us/library/system.security.cryptography.hashalgorithm.transformblock.aspx
这是我现在的代码:
public static byte[] createFileMD5(string path){
MD5 md5 = MD5.Create();
FileStream fs = File.OpenRead(path);
byte[] buf = new byte[1024];
byte[] newbuf = new byte[1024];
int num; int newnum;
num = fs.Read(buf,0,buf.Length);
while ((newnum = fs.Read(newbuf, 0, newbuf.Length))>0)
{
md5.TransformBlock(buf, 0, buf.Length, buf, 0);
num = newnum;
buf = newbuf;
}
md5.TransformFinalBlock(buf, 0, num);
return md5.Hash;
}
很不幸,它计算出来的哈希值与我使用fciv计算出来的哈希值不相符。
为了确保:我在返回的字节数组上使用的十六进制算法:
public static string byteArrayToString(byte[] ba)
{
StringBuilder hex = new StringBuilder(ba.Length * 2);
foreach (byte b in ba)
hex.AppendFormat("{0:x2}", b);
return hex.ToString();
}
TransformBlock
。然后,您会在最后一个块上调用TransformFinalBlock
。然而,在未知长度的流中,直到太晚您才可能知道是否已处理了最后一个块。因此,一个正确实现的算法被期望在以空数组调用TransformFinalBlock
时,完成哈希处理。然而,在理想情况下,TransformFinalBlock
应该被期望使用来自流的最后一个数据块进行调用。 附言: 我使用了MD5和SHA256测试了这两种方法,并确认它们有效。 - Alex Essilfie