I am trying to hash a file by reading 1024 bytes from a FileStream in a loop and using TransformBlock function. I need this to understand the mechanics of hashing multiple byte arrays into one hash. This would allow me to hash not only files, but also folders. I used this stackoverflow question: Hashing multiple byte[]'s together into a single hash with C#? and this msdn example: http://msdn.microsoft.com/en-us/library/system.security.cryptography.hashalgorithm.transformblock.aspx
Here is the code I have now:
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;
}
Unfortunately the hash which it calculates doesnt correspond to the one which I calculated using fciv.
Just to be sure: hexing algorithm which I use on the returned byte array:
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();
}