Visual Basic错误生成文件夹SHA256哈希

时间:2014-11-18 18:38:02

标签: vb.net hash

我想为visual basic中的文件夹中的所有文件生成一个SHA256哈希值。我尝试了以下代码,但它生成了文件夹中所有文件的单独哈希值,但没有单个哈希值。任何人都可以帮忙。

 Private Sub Button5_Click(sender As Object, e As EventArgs) Handles Button5.Click
        Dim directory As String
        If TextBox2.Text.Length < 1 Then
            Dim fdb As New FolderBrowserDialog
            Dim dr As DialogResult = fdb.ShowDialog()
            If (dr = DialogResult.OK) Then
                directory = fdb.SelectedPath
            Else
                MsgBox("No directory selected")
                Return
            End If
        Else
            directory = TextBox2.Text
        End If
        Try
            ' Create a DirectoryInfo object representing the specified directory. 
            Dim dir As New DirectoryInfo(directory)
            ' Get the FileInfo objects for every file in the directory. 
            Dim files As FileInfo() = dir.GetFiles()
            ' Initialize a SHA256 hash object. 
            Dim mySHA256 As SHA256 = SHA256Managed.Create()
            Dim hashValue() As Byte
            ' Compute and print the hash values for each file in directory. 
            Dim fInfo As FileInfo
            For Each fInfo In files
                ' Create a fileStream for the file. 
                Dim fileStream As FileStream = fInfo.Open(FileMode.Open)
                ' Be sure it's positioned to the beginning of the stream.
                fileStream.Position = 0
                ' Compute the hash of the fileStream.
                hashValue = mySHA256.ComputeHash(fileStream)
                ' Write the name of the file to the Console.
                MsgBox(fInfo.Name + ": ")
                ' Write the hash value to the Console.
                PrintByteArray(hashValue)
                ' Close the file.
                fileStream.Close()
            Next fInfo
            Return
        Catch DExc As DirectoryNotFoundException
            MsgBox("Error: The directory specified could not be found.")
        Catch IOExc As IOException
            MsgBox("Error: A file in the directory could not be accessed.")
        End Try
    End Sub
    Public Function PrintByteArray(ByVal array() As Byte)
        Dim i As Integer
        For i = 0 To array.Length - 1
            Label3.Text = (String.Format("{0:X2}", array(i)))
            If i Mod 4 = 3 Then
                Label3.Text = (" ")
            End If
        Next i
        Return Label3.Text

    End Function 'PrintByteArray

1 个答案:

答案 0 :(得分:0)

您可以将散列与XOR组合以提供一个256位散列(32个字节)。因为XOR是关联的(A XOR B = B XOR A),所以将文件散列在一起的XOR的顺序无关紧要。您必须对每个哈希的各个字节进行异或运算:Most efficient way to xor byte array in vb.net