Create a cryptographic MD5 hash in VB.NET Programming 29 AUG 2007

You’ve often seen these long, seemingly random numbers in secured web pages and perhaps wondered just what the heck that is meant to be. Well, usually these long numbers are hash codes, a system used to perform one-way data authentication. The MD5 hash algorithm is one of the most commonly used hashing functions, mainly because of its ease of implementation and the fact that it is a fairly secure one direction hash (In fact, this is basically how Windows authenticates its passwords).

Creating hash codes in VB6 was quite a mission, possible, but a mission. Then came along VB.NET to make things a little easier, providing a fairly decent set of classes under its System.Security.Cryptography namespace.

As an example, below is a generic function that returns an MD5 hash, formatted as a String, from the contents of a string you pass into the function:

Imports System.Text
Imports System.Security.Cryptography

Private Function GenerateHash(ByVal SourceText As String) As String
' Create an encoding object to ensure the encoding standard for the source text

Dim Ue As New UnicodeEncoding()
' Retrieve a byte array based on the source text

Dim ByteSourceText() As Byte = Ue.GetBytes(SourceText)
' Instantiate an MD5 Provider object

Dim Md5 As New MD5CryptoServiceProvider()
' Compute the hash value from the source

Dim ByteHash() As Byte = Md5.ComputeHash(ByteSourceText)
' And convert it to String format for return

Return Convert.ToBase64String(ByteHash)
End Function


Related link:

Related Posts:

About Craig Lotter

Software developer, husband and dad to two little girls. Writer behind An Exploring South African. I don't have time for myself any more.