How to generate md5-hashes for large files with VBA?

前端 未结 2 846
耶瑟儿~
耶瑟儿~ 2021-01-13 05:07

I have the following functions to generate md5-hashes for files. The functions work great for small files, but crashes and generate Run-time error 7 - Out of memory<

2条回答
  •  执笔经年
    2021-01-13 05:40

    It looks like you reached the memory limit. A better way would be to compute the MD5 of the file by block:

    Public Function ComputeMD5(filepath As String) As String
      Dim buffer() As Byte, svc As Object, hFile%, blockSize&, i&
      blockSize = 2 ^ 16
    
      ' open the file '
    
      If Len(Dir(filepath)) Then Else Err.Raise 5, , "file not found" & vbCr & filepath
    
      hFile = FreeFile
      Open filepath For Binary Access Read As hFile
    
      ' allocate buffer '
    
      If LOF(hFile) < blockSize Then blockSize = ((LOF(hFile) + 1024) \ 1024) * 1024
      ReDim buffer(0 To blockSize - 1)
    
      ' compute hash '
    
      Set svc = CreateObject("System.Security.Cryptography.MD5CryptoServiceProvider")
    
      For i = 1 To LOF(hFile) \ blockSize
        Get hFile, , buffer
        svc.TransformBlock buffer, 0, blockSize, buffer, 0
      Next
    
      Get hFile, , buffer
      svc.TransformFinalBlock buffer, 0, LOF(hFile) Mod blockSize
      buffer = svc.Hash
    
      ' cleanup '
    
      svc.Clear
      Close hFile
    
      ' convert to an hexa string '
    
      ComputeMD5 = String$(32, "0")
    
      For i = 0 To 15
         Mid$(ComputeMD5, i + i + 2 + (buffer(i) > 15)) = Hex(buffer(i))
      Next
    
    End Function
    

提交回复
热议问题