.net MD5正在上传

时间:2012-12-11 21:39:38

标签: .net io md5

让我说我做的事情是:

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?

我希望能够计算MD5校验和,因为我正在通过流...这可能吗?

1 个答案:

答案 0 :(得分:1)

您要查找的两种方法是TransformBlockTransformFinalBlock。他们会完全按照你的意愿行事。

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;