【问题标题】:Why is my SHA-1 function displaying the same output for both files in C#?为什么我的 SHA-1 函数在 C# 中为两个文件显示相同的输出?
【发布时间】:2014-04-26 21:26:54
【问题描述】:

我能够显示所选两个不同文件的两个不同 MD5 值,但是,SHA-1 函数为它们显示完全相同的值。这是为什么呢?

我不是一个优秀的程序员,所以我不知道这段代码是否特别好,但非常感谢任何帮助或建议。

{

System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5.Create();
System.Security.Cryptography.SHA1 sha1 = System.Security.Cryptography.SHA1.Create();

FileStream file1 = new FileStream(lblBrowse1.Text, FileMode.Open);
FileStream file2 = new FileStream(lblBrowse2.Text, FileMode.Open);


byte[] hash1 = md5.ComputeHash(file1);
byte[] hash2 = md5.ComputeHash(file2);
byte[] hash3 = sha1.ComputeHash(file1);
byte[] hash4 = sha1.ComputeHash(file2);

file1.Close();
file2.Close();


textBox1.Text = BitConverter.ToString(hash1).Replace("-", "");
textBox2.Text = BitConverter.ToString(hash2).Replace("-", "");
textBox6.Text = BitConverter.ToString(hash3).Replace("-", "");
textBox7.Text = BitConverter.ToString(hash4).Replace("-", "");



if (textBox1.Text == textBox2.Text)
   {
MessageBox.Show("These two files are identical.");
   }
else
   {
MessageBox.Show("These two files are different.");
   }

【问题讨论】:

  • 虽然不太可能,但不能说匹配的哈希等于匹配的数据。哈希确实会发生冲突,因此如果哈希匹配,您应该采取辅助措施来确保匹配数据。

标签: c# hash cryptography md5


【解决方案1】:

因为 MD5 散列已将文件 1 和文件 2 的流移动到 EOF。您需要在重用流之前将流倒回:

byte[] hash1 = md5.ComputeHash(file1);
byte[] hash2 = md5.ComputeHash(file2);

file1.Seek(0, SeekOrigin.Begin);
file2.Seek(0, SeekOrigin.Begin);

byte[] hash3 = sha1.ComputeHash(file1);
byte[] hash4 = sha1.ComputeHash(file2);

【讨论】:

  • 我在尝试计算文件的校验和时遇到了同样的问题,首先使用 MD5,然后使用 SHA1、SHA256 等。MD5 哈希总是正确的,因为它首先是正确的,然后产生了后续的 SHA 算法每次都出现完全相同的错误输出,我想知道发生了什么!
【解决方案2】:

您看到的 SHA-1 哈希很可能是 空字符串

da39a3ee5e6b4b0d3255bfef95601890afd80709

这是因为 FileStream 在之前计算 MD5 哈希的过程中已经一直读到最后。

要重复使用FileStreams,您应该“倒带”它们,如下所示:

file1.Position = 0;

【讨论】:

    猜你喜欢
    • 2023-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多