简体   繁体   English

C# .NET 6 中的不同文件SHA256、SHA512、MD5生成完全相同的hash

[英]SHA256, SHA512, MD5 generates exactly the same hash for different files in C# .NET 6

I have a strange issue.我有一个奇怪的问题。 I have the following very basic code:我有以下非常基本的代码:

private async Task<string> _CalculateChecksum(Stream strm)
    {
        System.Security.Cryptography.MD5 sha = System.Security.Cryptography.MD5.Create();
        byte[] checksum = await sha.ComputeHashAsync(strm);
        //return BitConverter.ToString(checksum).Replace("-", "");
        return Convert.ToBase64String(checksum);
    }

I would like to calculate hash values for files.我想计算文件的 hash 值。 I tried it with SHA256 first.我先用 SHA256 试了一下。 It doesn't matter if I change the hash algorithm from MD5 to either SHA256 or SHA512, the generated hash values for different files are always the same.无论我将 hash 算法从 MD5 更改为 SHA256 还是 SHA512,不同文件生成的 hash 值始终相同。 Eg: one of test file's size is approx.例如:其中一个测试文件的大小约为。 4. bigger than the other file. 4. 比其他文件大。 The hash is the same with all algorithms. hash 与所有算法相同。 I also tried using BitConverter.ToString instead of Convert.ToBase64String , but it does not matter because the content of checksum byte array is exactly the same.我也尝试使用BitConverter.ToString而不是Convert.ToBase64String ,但这并不重要,因为校验和字节数组的内容完全相同。

I also tried using normal (non-async) method, but the result is the same.我也尝试使用普通(非异步)方法,但结果是一样的。

Does anyone have any idea why is this happening?有谁知道为什么会这样?

Here is the code where the hashing part is called:这是调用散列部分的代码:

MemoryStream ms = new MemoryStream();
await file.CopyToAsync(ms);
string hash = await _CalculateChecksum(ms);

"file" is an IFormFile object which contains the correct value. “文件”是一个包含正确值的 IFormFile object。

After the await file.CopyToAsync(ms) , the position of the memory stream is at its end.await file.CopyToAsync(ms)之后,memory stream 的 position 结束了。 sha.ComputeHashAsync(strm) calculates the hash of the data after the current position, so basically that of an empty stream. sha.ComputeHashAsync(strm)计算当前 position 之后数据的 hash,所以基本上是一个空的 stream。

Try resetting the position of the stream to the start before the call to _CalculateChecksum:尝试在调用 _CalculateChecksum 之前将 stream 的 position 重置为开始:

MemoryStream ms = new MemoryStream();
await file.CopyToAsync(ms);
ms.Seek(0, SeekOrigin.Begin);
string hash = await _CalculateChecksum(ms);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM