Search code examples
.netiomd5

.net MD5 on stream


Lets say I'm doing something like:

FileStream fs = File.OpenRead("xxx.xxx");
byte[] buffer = new byte[1024];
int count;
long pos = 0, length = fs.Length;

MD5 md5 = MD5.Create();

while(pos < length && (count = fs.Read(buffer, 0, 1024)) > 0)
{
  doWork(buffer, count);
  md5.AddBlock(buffer, count); // <- Is this possible?
}

byte[] checksum = md5.GetChecksum(); // <- Possible?

I would like to be able to calculate the MD5 Checksum as I'm going through the stream... is this possible?


Solution

  • The two methods you are looking for are TransformBlock and TransformFinalBlock. They will do exactly what you are looking for.

    FileStream fs = File.OpenRead("xxx.xxx");
    byte[] buffer = new byte[1024];
    int count;
    long pos = 0, length = fs.Length;
    
    MD5 md5 = MD5.Create();
    
    while(pos < length && (count = fs.Read(buffer, 0, 1024)) > 0)
    {
      pos += count;
      doWork(buffer, count);
      int md5Offset = 0;
    
      //The while loop may be unnessasary, I don't know if it will ever process less than the length you pass in. The MSDN is unclear about that.
      while(md5Offset < count)
          md5Offset += md5.TransformBlock(buffer, md5Offset , count - md5Offset, buffer, md5Offset);
    }
    
    md5.TransformFinalBlock(buffer, 0, 0);
    byte[] checksum = md5.Hash;