Question

I found the following VBA code which succesfully generates a SHA1 hash. But I would like to modify it to ignore the first 8 bytes of the target file. I'm sure there is a small modification that is needed but I have researched and cannot find an answer.

Activecell.Value = FileToSHA1Hex(SomeFileName)`

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

Thanks in advance.

Was it helpful?

Solution

You can add a parameter to the GetFileBytes function so that you can let it skip a number of bytes at the beginning. Use the Seek function to skip to a specific place in the file:

Private Function GetFileBytes(ByVal path As String, ByVal skip as Integer) 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
    Seek lngFileNum, skip + 1
    ReDim bytRtnVal(LOF(lngFileNum) - skip - 1&) As Byte
    Get lngFileNum, , bytRtnVal
    Close lngFileNum
  Else
    Err.Raise 53
  End If
  GetFileBytes = bytRtnVal
  Erase bytRtnVal
End Function

Now you can specify that the first eight bytes should be skipped when you read the file:

bytes = GetFileBytes(sFileName, 8)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top