Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/309.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
为什么我的SHA-1函数在C#中为两个文件显示相同的输出?_C#_Hash_Cryptography_Md5 - Fatal编程技术网

为什么我的SHA-1函数在C#中为两个文件显示相同的输出?

为什么我的SHA-1函数在C#中为两个文件显示相同的输出?,c#,hash,cryptography,md5,C#,Hash,Cryptography,Md5,我能够显示所选两个不同文件的两个不同MD5值,但是,SHA-1函数为这两个文件显示完全相同的值。为什么呢 我不是一个伟大的程序员,所以我不知道这段代码是否特别好,但任何帮助或建议都将不胜感激 { System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5.Create(); System.Security.Cryptography.SHA1 sha1 = System.Security.Cryptography

我能够显示所选两个不同文件的两个不同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.");
   }

很可能,您看到的SHA-1散列是空字符串的散列:

这是因为在上一次计算MD5散列时,
FileStream
已经一直读取到最后

要重新使用
FileStream
s,您应该“倒带”它们,如下所示:

file1.Position = 0;

因为MD5哈希已将file1和file2的流移动到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算法每次都产生完全相同的错误输出,我想知道发生了什么!
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);