在VB.NET中检查文件的MD5 [英] Checking the MD5 of file in VB.NET
问题描述
当用户单击按钮时,它将要求他选择特定文件.它会检查MD5哈希值,以了解这是否是正确的文件.
When a user clicks on the button, it will ask him to choose a specific file. It checks the MD5 hash to know if this is the right file.
代码的问题是它给我错误的文件"消息,并且我完全确定该文件的MD5哈希为"3982908442F37245B305EDCF4D834494"
The problem with the code is that it gives me "Wrong File" message, and I'm totally sure that the MD5 hash for the file is "3982908442F37245B305EDCF4D834494"
Private Sub Button3_Click(sender As System.Object, e As System.EventArgs) Handles Button3.Click
dim md5code as string
OpenFileDialog1.ShowDialog()
Dim md5 As MD5CryptoServiceProvider = New MD5CryptoServiceProvider
Dim f As FileStream = New FileStream(OpenFileDialog1.FileName, FileMode.Open, FileAccess.Read, FileShare.Read, 8192)
f = New FileStream(OpenFileDialog1.FileName, FileMode.Open, FileAccess.Read, FileShare.Read, 8192)
md5.ComputeHash(f)
Dim ObjFSO As Object = CreateObject("Scripting.FileSystemObject")
Dim objFile = ObjFSO.GetFile(OpenFileDialog1.FileName)
Dim hash As Byte() = md5.Hash
Dim buff As StringBuilder = New StringBuilder
Dim hashByte As Byte
For Each hashByte In hash
buff.Append(String.Format("{0:X1}", hashByte))
Next
md5code = buff.ToString()
If md5code = "3982908442F37245B305EDCF4D834494" Then
TextBox2.Text = OpenFileDialog1.FileName
Else
MessageBox.Show("Wrong File")
End If
End Sub
推荐答案
请参阅以下MS KB文章:
Please see the following MS KB articles:
HashAlgorithm.ComputeHash方法(流)
如何使用Visual Basic .NET或Visual Basic 2005计算和比较哈希值
基本上,您需要将MD5字符串的生成方式更改为这两篇文章中概述的内容.引用第二个:
Basically, you need to change your generation of the MD5 string to that outlined in either of the articles. To quote the second:
Private Function ByteArrayToString(ByVal arrInput() As Byte) As String
Dim i As Integer
Dim sOutput As New StringBuilder(arrInput.Length)
For i = 0 To arrInput.Length - 1
sOutput.Append(arrInput(i).ToString("X2"))
Next
Return sOutput.ToString()
End Function
您将以md5.Hash作为参数调用此方法,并将结果存储在md5code变量中:
You would call this method with md5.Hash as the parameter and store the result in your md5code variable:
md5Code = ByteArrayToString(md5.Hash)
这篇关于在VB.NET中检查文件的MD5的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!