简体   繁体   English

当被比较的两个字符串相同时,为什么会出现 md5 哈希不匹配?

[英]Why do I get an md5 hash mismatch when both strings being compared are identical?

I am working on a C# program that uses md5 hashing.我正在开发一个使用 md5 散列的 C# 程序。 A file is created using an older version of the program and the hash is saved in a field in the file.文件是使用旧版本的程序创建的,哈希值保存在文件的一个字段中。 Here is a code snippet showing the saving of the hash and the file:这是一个代码片段,显示了哈希和文件的保存:

using (MD5 md5Hash = MD5.Create())
{
     this.Hash = string.Empty;
     s = JsonConvert.SerializeObject(this, Formatting.Indented);
     string hash = MD5hash.GetMd5Hash(md5Hash, s);
     this.Hash = hash;
     s = JsonConvert.SerializeObject(this, Formatting.Indented);
 }

The string "s" is saved to a file in JSON format and "this" is the object that is serialized.字符串“s”以 JSON 格式保存到文件中,“this”是序列化的对象。

In a new version of the program I am attempting to load the above file but the md5 hashes don't match even though I compare the files and they are identical.在程序的新版本中,我试图加载上述文件,但即使我比较了这些文件并且它们是相同的,md5 哈希值也不匹配。 Here is a snippet:这是一个片段:

using (MD5 md5Hash = MD5.Create())
{
     hash = MD5hash.GetMd5Hash(md5Hash, s);
     if (fhash == hash)
     {
         return f;
     }
     else
     {
         throw new Exception("HashMismatch");
     }
 }

"fhash" is loaded from the file and is the hash that was saved in the older version. “fhash”是从文件中加载的,是在旧版本中保存的哈希值。 Since "s" in the the new version in the above code matches "s" in the older version "hash" and "fhash" should match but they don't.由于上面代码中新版本中的“s”匹配旧版本中的“s”,因此“hash”和“fhash”应该匹配但它们不匹配。 Any suggestions?有什么建议?

Thanks in advance for your help!在此先感谢您的帮助!

In the first block of code you generate a hash from the object that has a hash of string.empty but in the second block you are attempting to generate a hash from the file which was serialized with the Hash property set to the generated hash.在第一个代码块中,您从具有string.empty散列的对象生成一个散列,但在第二个块中,您尝试从使用设置为生成散列的Hash属性序列化的文件生成散列。

So when you generate the hash for the loaded file it will generate a different value because the Hash property is no longer the same value that was used when generated the original hash ie string.empty .因此,当您为加载的文件生成哈希时,它将生成不同的值,因为Hash属性不再是生成原始哈希时使用的值,即string.empty

When you load the file in the second block of code you need to set the Hash property to string.empty to get the hashes to match.当您在第二个代码块中加载文件时,您需要将Hash属性设置为string.empty以使哈希匹配。

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

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