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 FileStream
s, you should "rewind" them, like this:
file1.Position = 0;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With