簡體   English   中英

為什么 SHA256Managed().ComputeHash() 返回的 hash 與外部工具產生的不同?

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

作為個人練習,我一直在嘗試在我正在編寫的一個小程序中生成 SHA256 哈希。 我的計算機上有一個任意 bitmap 文件,我已將其加載到我的程序中。 某處有問題,我無法識別。 The hash returned by my program is 5EFFCC89AEA1922485CFA721194320D8895A4F31AC4AA5134AC2104C528033BA but when I run 7-Zip's SHA256 tool on the exact same file, it returns D78859AD5651EB23A771C4763D03E65D64550C0660F7E182668586398CF02BF9 . 這是我的代碼:

var image = new Bitmap(@"C:\Users\1\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 object。 但如果我理解正確,這實際上只是一個字節數組,所以它似乎不應該改變任何數據。

我的代碼有什么問題?

將映像寫入 memory stream 后,其 position 將設置為 ZF7B754CAFFD5C68A2EZ 的末尾如果你將它傳遞給 state 中的ComputeHash() ,它將沒有字節到 hash。

因此,在將 stream 傳遞給ComputeHash()之前,您必須將 position 重置為零:

var image  = new Bitmap(@"C:\Users\1\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")));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM