VBA计算文件内容的MD5哈希值

3
我需要一个VBA例程来计算文件内容的MD5哈希值。我找到了一些示例(例如,这里),但我发现当文件名包含某些Unicode字符时,它们会崩溃,因此我正在尝试调整代码以避免出现问题。
这段代码没有出现错误,但也没有返回正确的MD5哈希值。有什么问题吗?
Public Function FileToMD5Hex(sFileName As String) As String
    Dim enc
    Dim bytes
    Dim outstr As String
    Dim pos As Integer
    Set enc = CreateObject("System.Security.Cryptography.MD5CryptoServiceProvider")
    'Convert the string to a byte array and hash it
    bytes = GetFileBytes(sFileName)
    bytes = enc.ComputeHash_2((bytes))
    'Convert the byte array to a hex string
    For pos = 1 To LenB(bytes)
        outstr = outstr & LCase(Right("0" & Hex(AscB(MidB(bytes, pos, 1))), 2))
    Next
    FileToMD5Hex = outstr
    Set enc = Nothing
End Function

Private Function GetFileBytes(path As String) As Byte()
    Dim fso As Object
    Set fso = CreateObject("scripting.FileSystemObject")

    Dim fil As Object
    Set fil = fso.GetFile(path)

'    Dim fpga As Variant
    GetFileBytes = fil.OpenAsTextStream().Read(fil.Size)

    Set fil = Nothing
    Set fso = Nothing
End Function
1个回答

3

有一些字符序列,Scripting.FileSystemObject无法正确地处理为TextStream

使用ADODB.Stream ActiveX从文件中检索字节数组。它可以完美地处理文本和二进制类型的数据,同时允许更改字符串的字符集(FSO仅适用于ASCII和Unicode,并且仅适用于文件)。

Function GetFileBytes(strPath As String) As Byte()
    With CreateObject("ADODB.Stream")
        .Type = 1 ' adTypeBinary
        .Open
        .LoadFromFile (strPath)
        GetFileBytes = .Read()
    End With
End Function

另一个处理二进制数据的ActiveX是SAPI.spFileStream。其最重要的优点之一是它允许仅将文件的部分加载到内存中(在比较大文件时,这可以在检查MD5时通过块帮助显着提高性能)。

Function GetFileBytes(strPath As String) As Byte()
    Dim arrContent As Variant
    With CreateObject("SAPI.spFileStream")
        .Open strPath, 0
        .Read arrContent, CreateObject("Scripting.FileSystemObject").GetFile(strPath).Size
        .Close
    End With
    GetFileBytes = arrContent
End Function

好的代码(我将使用ADODB.Stream而不是Open #F for Binary ReadGet)。然而,还有一个缺失的组件:你有没有加载连续字节块到单个哈希计算中的System.Security.Cryptography函数的示例? - Nigel Heffernan
更新:用户Florent B.在此StackOverflow答案中提供了将数据分块传递给MD5哈希服务的解决方案 - 这与您的SAPI.spFileStream实现非常契合。 - Nigel Heffernan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接