vba的一种变相md5实现

原创文章,欢迎转载:http://miao.blog/article/vba-md5-1

vba要实现md5必须引用外部库,导致vba程序交付安装不是很方便。很多时候我们并不是想要取真正的md5,只是取一个加密字符串,比如保存密码的时候。本文中的代码直接利用windows系统内置命令certutil -hashfile实现了一种变相的md5函数。代码要读写本地文件两次,因此效率不高,不过在登陆验证一下密码等场景并没有影响。

效果如下:

代码:
' md5
Function Md5(str As String) As String
    On Error GoTo ErrorHandler
    
    Dim md5_file_path As String: md5_file_path = Environ("temp") & "\" & "md5_str.txt"
    Open Environ("temp") & "\" & "md5_str.txt" For Output As #1
        Print #1, str
    Close #1
    
    Md5 = ExecuteCmdForString("certutil -hashfile " & md5_file_path & " MD5")
    Md5 = Split(Md5, vbLf)(1)
    Md5 = Replace(Md5, vbCr, "")
    Exit Function
ErrorHandler:
    Md5 = ""
    Debug.Print Err.Description
End Function

' Execute command and get string result
' Import Microsoft Scripting Runtime, Windows Script Host Object Model
Function ExecuteCmdForString(command As String) As String
    On Error GoTo ErrorHandler
    
    ' execute command
    Dim tmp_file  As String: tmp_file = Environ("tmp") & "\cmdResult.txt"
    With CreateObject("WScript.Shell")
        .Run "cmd /c " & command & " > " & tmp_file, WshHide, True
    End With
        
    ' get result
    Dim fso, txtStream
    Set fso = CreateObject("Scripting.FileSystemObject")
    Set txtStream = fso.OpenTextFile(tmp_file)
    
    If Not txtStream.AtEndOfStream Then
        ExecuteCmdForString = txtStream.ReadAll
    End If
    
    Exit Function
ErrorHandler:
    ExecuteCmdForString = ""
    Debug.Print Err.Description
End Function
推荐阅读
VBA发送GET、POST请求的方法
评论