如何使用VBA获取文件的MD5十六进制哈希?
我需要一个适用于文件的版本。
像Python代码一样简单:
import hashlib
def md5_for_file(fileLocation, block_size=2**20):
f = open(fileLocation)
md5 = hashlib.md5()
while True:
data = f.read(block_size)
if not data:
break
md5.update(data)
f.close()
return md5.hexdigest()
但在VBA。
答案 0 :(得分:14)
可以使用更好答案的旧问题。这些函数专门用于散列文件,而不适用于散列密码。作为奖励,我包括SHA1的功能。如果你摆脱了类型声明,这些函数也可以在VBScript中工作,除了需要将GetFileBytes函数更改为使用FileSystemObject(或可能是ADO Stream),因为VBScript中不存在Free File。
Private Sub TestMD5()
Debug.Print FileToMD5Hex("C:\test.txt")
Debug.Print FileToSHA1Hex("C:\test.txt")
End Sub
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
Public Function FileToSHA1Hex(sFileName As String) As String
Dim enc
Dim bytes
Dim outstr As String
Dim pos As Integer
Set enc = CreateObject("System.Security.Cryptography.SHA1CryptoServiceProvider")
'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
FileToSHA1Hex = outstr 'Returns a 40 byte/character hex string
Set enc = Nothing
End Function
Private Function GetFileBytes(ByVal path As String) As Byte()
Dim lngFileNum As Long
Dim bytRtnVal() As Byte
lngFileNum = FreeFile
If LenB(Dir(path)) Then ''// Does file exist?
Open path For Binary Access Read As lngFileNum
ReDim bytRtnVal(LOF(lngFileNum) - 1&) As Byte
Get lngFileNum, , bytRtnVal
Close lngFileNum
Else
Err.Raise 53
End If
GetFileBytes = bytRtnVal
Erase bytRtnVal
End Function
答案 1 :(得分:3)
答案 2 :(得分:-1)
这应该这样做:
Dim fileBytes() As Byte = File.ReadAllBytes(path:=fullPath)
Dim Md5 As New MD5CryptoServiceProvider()
Dim byteHash() As Byte = Md5.ComputeHash(fileBytes)
Return Convert.ToBase64String(byteHash)