【问题标题】:Create SHA1 hash in VBA, ignoring the first 8 bytes of a file在 VBA 中创建 SHA1 哈希,忽略文件的前 8 个字节
【发布时间】:2014-05-01 13:13:45
【问题描述】:

我发现以下 VBA 代码成功生成了 SHA1 哈希。但我想修改它以忽略目标文件的前 8 个字节。我确信需要进行一些小修改,但我已经研究过,找不到答案。

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

提前致谢。

【问题讨论】:

    标签: vba hash sha1


    【解决方案1】:

    您可以向GetFileBytes 函数添加一个参数,这样您就可以让它在开始时跳过一些字节。使用Seek 函数跳转到文件中的特定位置:

    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
    

    现在您可以指定在读取文件时应跳过前八个字节:

    bytes = GetFileBytes(sFileName, 8)
    

    【讨论】:

      猜你喜欢
      • 2020-12-22
      • 2011-11-26
      • 1970-01-01
      • 2010-09-07
      • 1970-01-01
      • 1970-01-01
      • 2020-03-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多