MD5 Hashing

By Sockreg on Dec 01, 2009

This snippet function hashes a string into an MD5. The function will throw an error if an empty string is provided. Just copy and paste this into a console application, set the Sub Main() as the start up object and run it! You will see how the same hash is created for the "Test" string and a different hash is created for the "Test1" string. If you've got any problems with this snippet just comment or private message me.

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

Class HashingClass

    'Testing your application
    Shared Sub Main()
        Dim objectInstance As New HashingClass
        Catch md5Exception As Exception
            Console.WriteLine(String.Format("Error encountered: {0} - Thrown by: {1}", _
                                            md5Exception.Message, _
        End Try
    End Sub

    'The following function hashes a given string using MD5 ...
    Function GetStringMD5(ByVal dataToHash As String) As String
        If dataToHash = String.Empty Then
            Throw New ApplicationException("Cannot hash empty string!")
            Dim hashMechanism As HashAlgorithm = HashAlgorithm.Create("MD5")
            Dim data = [Default].GetBytes(dataToHash)
            Dim finalHash = hashMechanism.ComputeHash(data)
            Return [Default].GetString(finalHash)
        End If
    End Function

End Class


Sign in to comment.
Sockreg   -  Dec 02, 2009

You are converted the dataToHash string inputted in the function to a set of bytes that can be hashed by the hashing algorithm. Once the byte array is hashed it is converted to a string and returned.

^Neptune   -  Dec 01, 2009

I'm gonna make it my mission to understand this.

Are you sure you want to unfollow this person?
Are you sure you want to delete this?
Click "Unsubscribe" to stop receiving notices pertaining to this post.
Click "Subscribe" to resume notices pertaining to this post.