Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is my SHA-1 function displaying the same output for both files in C#?

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.");
   }
like image 505
user3576039 Avatar asked Dec 15 '22 23:12

user3576039


2 Answers

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);
like image 197
Remus Rusanu Avatar answered May 27 '23 20:05

Remus Rusanu


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;
like image 20
Jonathon Reinhart Avatar answered May 27 '23 20:05

Jonathon Reinhart