use*_*039 4 c# hash md5 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.");
}
Run Code Online (Sandbox Code Playgroud)
因为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);
Run Code Online (Sandbox Code Playgroud)
最有可能的是,您看到的SHA-1哈希值是空字符串:
da39a3ee5e6b4b0d3255bfef95601890afd80709
Run Code Online (Sandbox Code Playgroud)
这是因为FileStream在上一次计算MD5哈希期间,已经一直读到最后.
要重新使用FileStreams,你应该"回放"它们,如下所示:
file1.Position = 0;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
73 次 |
| 最近记录: |