Create a file hash

  • Thread starter Thread starter John Wright
  • Start date Start date
J

John Wright

I want to create a file hash on my exe files and store the hash signature in
a database so I can retrieve the value to compare the file hash to ensure I
have an untampered file. How can this be done in VB.NET 2005

john
 
John Wright said:
I want to create a file hash on my exe files and store the hash signature
in a database so I can retrieve the value to compare the file hash to
ensure I have an untampered file. How can this be done in VB.NET 2005

john

Public Shared Sub Main(ByVal Args As String())
Try
If Args.Length <> 1
Console.WriteLine("Missing path argument.")
Return
End If

Dim filePath As String = Args(0)
Dim outPath As String = filePath & ".hash"

' Read the file into a byte-array.
Dim reader As FileStream = File.OpenRead(filePath)
Dim length As Integer = CInt(reader.Length)
Dim bytes As Byte() = New Byte(length) { }
reader.Read(bytes, 0, length)
reader.Close()

' Calculate the file's hash.
Dim md5 As MD5 = MD5.Create()
Dim hash As Byte() = md5.ComputeHash(bytes)

' Write the hashed byte-array to the hash file.
If File.Exists(outPath)
File.Delete(outPath)
End If
Dim writer As FileStream = New FileStream(outPath,
FileMode.CreateNew)
writer.Write(hash, 0, hash.Length)
writer.Close()

Console.Write("Press any key to continue...")
Catch ex As Exception
Console.WriteLine(ex.ToString())
Finally
Console.Read()
End Try
End Sub

Quick tested (although slightly modified since testing, so may wanna check
again :P )

This creates an MD5 hash of the file specified as the only argument on the
command-line. It then writes this hash to another file with the same name
with a ".hash" added to the name of the file. You should be able to take
this and use it to store into a database instead of a file :)

Cheers!

HTH,
Mythran
 
Back
Top