EvilZone
Programming and Scripting => .NET Framework => : ande December 18, 2010, 10:14:03 PM
-
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:
dim MD5Str as string = getMD5Hash("abc")
dim FileMD5 as string = MD5CalcFile("c:\boot.ini")
-
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.