【发布时间】:2015-11-14 03:05:20
【问题描述】:
我需要一个 VBA 例程来计算文件内容的 MD5 哈希值。我找到了一些示例(例如,here),但我发现当文件名包含某些 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
【问题讨论】:
标签: vba ms-access md5 ms-access-2013