0

I need a way of natively calculate a MD5 HASH of a file in vbscript, and MD5 class has a property called GetMd5Hash which seems that can help me. I just have to read a file into a byte array and then apply this method. I found a script code in web page http://msdn.microsoft.com/en-us/library/system.security.cryptography.md5(v=vs.110).aspx?cs-save-lang=1&cs-lang=vb#code-snippet-2 which is exactly what I need but when I run it with command cscript /E:vbs md5.vbs if fails with error code:

md5.vbs(7,5) Microsoft VBScript compilation error: Syntax error. Can someone help me solve this error please?

The code is:

Imports System
Imports System.Security.Cryptography
Imports System.Text

Class Program

Shared Sub Main(ByVal args() As String)
    Dim [source] As String = "Hello World!" 
    Using md5Hash As MD5 = MD5.Create()

        Dim hash As String = GetMd5Hash(md5Hash, source)

        Console.WriteLine("The MD5 hash of " + source + " is: " + hash + ".")

        Console.WriteLine("Verifying the hash...")

        If VerifyMd5Hash(md5Hash, [source], hash) Then
            Console.WriteLine("The hashes are the same.")
        Else
            Console.WriteLine("The hashes are not same.")
        End If 
    End Using 
End Sub 'Main



Shared Function GetMd5Hash(ByVal md5Hash As MD5, ByVal input As String) As String 

    ' Convert the input string to a byte array and compute the hash. 
    Dim data As Byte() = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(input))

    ' Create a new Stringbuilder to collect the bytes 
    ' and create a string. 
    Dim sBuilder As New StringBuilder()

    ' Loop through each byte of the hashed data  
    ' and format each one as a hexadecimal string. 
    Dim i As Integer 
    For i = 0 To data.Length - 1
        sBuilder.Append(data(i).ToString("x2"))
    Next i

    ' Return the hexadecimal string. 
    Return sBuilder.ToString()

End Function 'GetMd5Hash


' Verify a hash against a string. 
Shared Function VerifyMd5Hash(ByVal md5Hash As MD5, ByVal input As String, ByVal hash As String) As Boolean 
    ' Hash the input. 
    Dim hashOfInput As String = GetMd5Hash(md5Hash, input)

    ' Create a StringComparer an compare the hashes. 
    Dim comparer As StringComparer = StringComparer.OrdinalIgnoreCase

    If 0 = comparer.Compare(hashOfInput, hash) Then 
        Return True 
    Else 
        Return False 
    End If 

End Function 'VerifyMd5Hash
End Class 'Program 
' This code example produces the following output: 
' 
' The MD5 hash of Hello World! is: ed076287532e86365e841e92bfc50d8c. 
' Verifying the hash... 
' The hashes are the same.
JustMe
  • 11
  • 3
  • This is ragged .NET :P – Jobbo Dec 23 '13 at 18:10
  • This is also called vbscript. Did you look at the error provided by the operating system? Microsoft >>VBScript<<. http://technet.microsoft.com/en-us/library/ee692938.aspx – JustMe Dec 24 '13 at 17:49

2 Answers2

2

This md5_of_file.vbs works for me (tested on Win10 Ent N):

' md5_of_file.vbs - Prints md5 hashes of specified files
' Combined at least from following sources:
'    md5 from https://stackoverflow.com/a/31453654
'    https://support.microsoft.com/en-us/help/276488/how-to-use-the-adodb-stream-object-to-send-binary-files-to-the-browser

Dim md5obj
set md5obj = CreateObject("System.Security.Cryptography.MD5CryptoServiceProvider")

md5obj.Initialize()

Set fso = CreateObject("Scripting.FileSystemObject")

Const adTypeBinary = 1
Set objStream = CreateObject("ADODB.Stream") 

Function bytesToHex(aBytes)
    Dim hexStr, x
    For x=1 To lenb(aBytes)
        hexStr= LCase(hex(ascb(midb( (aBytes) ,x,1))))
        if len(hexStr)=1 then hexStr="0" & hexStr
        bytesToHex=bytesToHex & hexStr
    Next
end Function

' read bytes from fileName
Function LoadFile(fileName)
    objStream.Open
    objStream.Type = adTypeBinary
    objStream.LoadFromFile( fileName )
    LoadFile = objStream.Read
    objStream.Close
End Function

' returns hex value of md5 hash from content of fileName
Function HashOfFile(fileName)
    fileBytes = LoadFile(fileName)
    ' Do NOT omit braces around fileBytes - it will not work...
    md5hashBytes = md5obj.ComputeHash_2( (fileBytes) )
    HashOfFile = bytesToHex(md5hashBytes)
End Function

If WScript.Arguments.Count < 1 Then
    WScript.Echo("Script to compute md5 hash of specified files...")
    WScript.Echo("Usage: " & WScript.ScriptName & " file1 ...")
    WScript.Quit(1)
End If

For i = 0 To Wscript.Arguments.Count-1
    fileName = WScript.Arguments.Item(i)
    WScript.Echo( HashOfFile(fileName) & " " & fileName )
Next

Example usage from cmd:

cscript //nologo md5_of_file.vbs c:\windows\explorer.exe
    e4a81eddff8b844d85c8b45354e4144e c:\windows\explorer.exe

Copyright disclaimer - most code comes from https://stackoverflow.com/a/31453654

0

Get Microsoft's File Checksum Integrity Verifier for md5/sha1 code, it's command line mode and very fast. Just extract it to System32 folder.

fciv

PatricK
  • 6,375
  • 1
  • 21
  • 25
  • I will try this tool but I would still like to know if there is a way to calculate MD5HASH natively using the functions in the vbscript code I provided. I need to deploy a tool in many thousand computers so the native option is preferred. – JustMe Dec 24 '13 at 17:56