title: C# Hashing multiple byte array blocks
body: <p>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: <a href="https://stackoverflow.com/questions/5805106/hashing-multiple-bytes-together-into-a-single-hash-with-c">Hashing multiple byte[]&#39;s together into a single hash with C#?</a> and this msdn example: <a href="http://msdn.microsoft.com/en-us/library/system.security.cryptography.hashalgorithm.transformblock.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/system.security.cryptography.hashalgorithm.transformblock.aspx</a></p>
  
  <p>Here is the code I have now:</p>
  
  <pre><code>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))&gt;0)
      {
          md5.TransformBlock(buf, 0, buf.Length, buf, 0);
          num = newnum;
          buf = newbuf;
      }
  
      md5.TransformFinalBlock(buf, 0, num);
  
      return md5.Hash;
  }
  </code></pre>
  
  <p>Unfortunately the hash which it calculates doesnt correspond to the one which I calculated using fciv.</p>
  
  <p>Just to be sure: hexing algorithm which I use on the returned byte array:</p>
  
  <pre><code>    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();
      }
  </code></pre>