Author Topic: [VB.NET] MD5 - File and string  (Read 2845 times)

0 Members and 1 Guest are viewing this topic.

Offline ande

  • Owner
  • Titan
  • *
  • Posts: 2664
  • Cookies: 256
    • View Profile
[VB.NET] MD5 - File and string
« on: December 18, 2010, 10:14:03 pm »
Code: (vb) [Select]
Public Function MD5CalcFile(ByVal filepath As String) As String
    Using reader As New System.IO.FileStream(filepath, IO.FileMode.Open, IO.FileAccess.Read)
        Using md5 As New System.Security.Cryptography.MD5CryptoServiceProvider
            Dim hash() As Byte = md5.ComputeHash(reader)
            Return ByteArrayToString(hash)
        End Using
    End Using
End Function

Private Function ByteArrayToString(ByVal arrInput() As Byte) As String
    Dim sb As New System.Text.StringBuilder(arrInput.Length * 2)
    For i As Integer = 0 To arrInput.Length - 1
        sb.Append(arrInput(i).ToString("X2"))
    Next
    Return sb.ToString().ToLower
End Function

Function getMD5Hash(ByVal strToHash As String) As String
    Dim md5Obj As New Security.Cryptography.MD5CryptoServiceProvider
    Dim bytesToHash() As Byte = System.Text.Encoding.ASCII.GetBytes(strToHash)
    bytesToHash = md5Obj.ComputeHash(bytesToHash)
    Dim strResult As String = ""
    For Each b As Byte In bytesToHash
        strResult += b.ToString("x2")
    Next
    Return strResult
End Function

Dump from my Visual Studio folder. Most likely I got it off the net, so credits to whoever originally created it. I use it alot ;)

Usage:
Code: (vb) [Select]
dim MD5Str as string = getMD5Hash("abc")
dim FileMD5 as string = MD5CalcFile("c:\boot.ini")
« Last Edit: December 18, 2010, 10:14:14 pm by ande »
if($statement) { unless(!$statement) { // Very sure } }
https://evilzone.org/?hack=true

Offline Polynomial

  • /dev/null
  • *
  • Posts: 8
  • Cookies: 4
    • View Profile
Re: MD5 - File and string
« Reply #1 on: January 27, 2011, 01:48:40 pm »
You should use UTF8, not ASCII. The reason ASCII was useful in ye olden days was that it perfectly fit into 127 characters, which was 7 bits. The problem was that old legacy 8-bit hardware did annoying things to ASCII characters when you took up the 8th bit too, since this was considered the signing bit (i.e. 0xFF is -1). These days you're much better off using UTF8 since modern processors don't screw this kind of thing up, and it provides compatibility when someone puts an ß (0xDF) or something in their string.

Just as another quick idea for those reading this, you can actually replace MD5CryptoServiceProvider with any of the standard hash functions in the .NET framework. For example, the whole SHA family will work here - just replace MD5CryptoServiceProvider with SHA1Managed, SHA256Managed, SHA384Managed or SHA512Managed and it'll work perfectly.