为什么 SHA256Managed().ComputeHash() return 与外部工具生成的哈希不同?

Why does SHA256Managed().ComputeHash() return a different hash than from what external tools produce?

作为个人练习,我一直在尝试在我编写的一个小程序中生成 SHA256 哈希。我的计算机上有一个任意位图文件,我已将其加载到我的程序中。我无法确定某处存在问题。我的程序返回的散列是 5EFFCC89AEA1922485CFA721194320D8895A4F31AC4AA5134AC2104C528033BA,但是当我 运行 7-Zip 的 SHA256 工具处理完全相同的文件时,它 returns D78859AD5651EB23A771C4763D03E65D64550C0660F7E182668586398CF02BF9。这是我的代码:

var image = new Bitmap(@"C:\Users\image.bmp");
var stream = new MemoryStream();
image.Save(stream, ImageFormat.Bmp);
var hashedBytes = new SHA256Managed().ComputeHash(stream);
var hash = string.Concat(hashedBytes.Select(x => x.ToString("X2")));

唯一看起来可能导致问题的代码是将图像转换为 MemoryStream 对象。但如果我理解正确的话,这实际上只是一个字节数组,所以它似乎不应该更改任何数据。

我的代码有什么问题?

将图像写入内存流后,其位置将设置为流的末尾。如果您在该状态下将它传递给 ComputeHash(),它将没有要散列的字节。

因此在将流传递给ComputeHash()之前必须将位置重置为零:

var image  = new Bitmap(@"C:\Users\image.bmp");
var stream = new MemoryStream();
image.Save(stream, ImageFormat.Bmp);
stream.Position = 0;
var hashedBytes = new SHA256Managed().ComputeHash(stream);
var hash        = string.Concat(hashedBytes.Select(x => x.ToString("X2")));