0

当用户点击按钮时,它会要求他选择一个特定的文件。它检查 MD5 哈希以了解这是否是正确的文件。

代码的问题是它给了我“错误的文件”消息,我完全确定该文件的 MD5 哈希是“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
4

3 回答 3

2

粘贴以下代码进行设置:

Imports System.IO
Imports System.Security.Cryptography

Function md5(ByVal file_name As String)
    Dim hash = MD5.Create()
    Dim hashValue() As Byte
    Dim fileStream As FileStream = File.OpenRead(file_name)
    fileStream.Position = 0
    hashValue = hash.ComputeHash(fileStream)
    Dim hash_hex = PrintByteArray(hashValue)
    fileStream.Close()
    Return hash_hex
End Function

Public Function PrintByteArray(ByVal array() As Byte)
    Dim hex_value As String = ""
    Dim i As Integer
    For i = 0 To array.Length - 1
        hex_value += array(i).ToString("X2")
    Next i
    Return hex_value.ToLower
End Function

当您要检索 MD5 哈希时,只需使用md5(file_name)并替换file_name为文件的路径。

例如:

TextBox1.Text = md5("C:\Desktop\foo.txt")
于 2017-10-28T07:10:23.503 回答
1

请参阅以下 MS 知识库文章:

HashAlgorithm.ComputeHash 方法(流)

如何使用 Visual Basic .NET 或 Visual Basic 2005 计算和比较哈希值

基本上,您需要将生成的 MD5 字符串更改为任何一篇文章中概述的内容。引用第二个:

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 变量中:

md5Code = ByteArrayToString(md5.Hash)
于 2011-10-29T02:34:03.823 回答
0

改变这个:buff.Append(String.Format("{0:X1}", hashByte))

至:buff.Append(String.Format("{0:X2}", hashByte))

您可以在代码中删除它:

Dim ObjFSO As Object = CreateObject("Scripting.FileSystemObject")  
Dim objFile = ObjFSO.GetFile(OpenFileDialog1.FileName)
于 2013-01-02T09:47:12.277 回答