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

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

本文介绍了VBA计算文件内容的MD5哈希值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一个VBA例程来计算文件内容的MD5哈希值.我找到了一些示例(例如,此处),但是我发现当文件名包含某些Unicode字符时它们崩溃了,所以我试图调整代码以避免这种情况.

I need a VBA routine to calculate the MD5 hash of a file's contents. I located some examples (e.g., here) but I found that they crashed when the filename contained certain Unicode characters, so I am trying to tweak the code to avoid that.

此代码不会导致错误,但也不会返回正确的MD5哈希值.怎么了?

This code does not result in an error, but it also doesn't return the correct MD5 hash. What's wrong?

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

推荐答案

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

There are some chars sequences that Scripting.FileSystemObject can't process properly as TextStream.

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

Use ADODB.Stream ActiveX to retrieve array of bytes from file. It works perfectly with both text and binary types of data, also it allows to change charset of the string (FSO only works with ASCII and Unicode, and only with files).

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).

Another one ActiveX processing binary data is SAPI.spFileStream. One of the most significant advantages - it allows to load only the part of the file to the memory (in some cases when comparing large files it can help drastically increase performance, checking md5 by chunks).

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

这篇关于VBA计算文件内容的MD5哈希值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 14:38