I'm able to display the two different MD5 values of two different files selected, however, the SHA-1 function displays the exact same value for both of them. Why is that?

I'm not a great programmer so I don't know if this code is particularly good or not but any help or advice would be much appreciated.

{

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.");
   }
有帮助吗?

解决方案

Because the MD5 hash has moved the stream to EOF for both file1 and file2. You need to rewind the streams back before reusing them:

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);

其他提示

Most likely, the SHA-1 hash you're seeing is that of the empty string:

da39a3ee5e6b4b0d3255bfef95601890afd80709

This is because the FileStream has already been read all the way to the end, during the previous calculation of the MD5 hash.

To re-use the FileStreams, you should "rewind" them, like this:

file1.Position = 0;
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top