加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 23:43:22 所属栏目:百科 来源:网络整理
导读:我能够显示所选的两个不同文件的两个不同的MD5值,但是,SHA-1函数显示两者的完全相同的值.这是为什么? 我不是一个优秀的程序员,所以我不知道这个代码是否特别好,但任何帮助或建议将不胜感激. {System.Security.Cryptography.MD5 md5 = System.Security.Crypt
我能够显示所选的两个不同文件的两个不同的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.");
   }

解决方法

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读