我需要一个VBA例程来计算文件内容的MD5哈希值。我找到了一些示例(例如,这里),但我发现当文件名包含某些Unicode字符时,它们会崩溃,因此我正在尝试调整代码以避免出现问题。
这段代码没有出现错误,但也没有返回正确的MD5哈希值。有什么问题吗?
这段代码没有出现错误,但也没有返回正确的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
ADODB.Stream
而不是Open #F for Binary Read
和Get
)。然而,还有一个缺失的组件:你有没有加载连续字节块到单个哈希计算中的System.Security.Cryptography函数的示例? - Nigel HeffernanSAPI.spFileStream
实现非常契合。 - Nigel Heffernan