How to compute and compare hash values by using Visual Basic .NET or Visual Basic 2005 (301053)



The information in this article applies to:

  • Microsoft Visual Basic 2005
  • Microsoft Visual Basic .NET (2003)
  • Microsoft Visual Basic .NET (2002)

This article was previously published under Q301053
For a Microsoft Visual C# .NET version of this article, see 307020.

IN THIS TASK

SUMMARY

The System.Security.Cryptography classes in the Microsoft .NET Framework make it easy to compute a hash value for your source data. This article shows how to obtain a hash value and how to compare two hash values to check whether they are identical.

<A NAME="bottom" HREF="#toc">back to the top</A>

Requirements

The following list outlines the recommended hardware, software, network infrastructure, and service packs that you will need:
  • Microsoft Visual Studio .NET or Microsoft Visual Studio 2005
back to the top

Compute a Hash Value

It is easy to generate and compare hash values using the cryptographic resources contained in the System.Security.Cryptography namespace. Because all hash functions take input of type Byte[], it might be necessary to convert the source into a byte array before it is hashed. To create a hash for a string value, follow these steps:
  1. Open Visual Studio .NET or Visual Studio 2005.
  2. Create a new Console Application in Visual Basic .NET or in Visual Basic 2005. Visual Studio .NET and Visual Studio 2005 create a Module for you along with an empty Main() procedure.
  3. Make sure that the project references the System and System.Security namespaces.
  4. Use the Imports statement on the System, System.Security, System.Security.Cryptographic, and System.Text namespaces so that you are not required to qualify declarations from these namespaces later in your code. These statements must be used prior to any other declarations.
    Imports System
    Imports System.Security
    Imports System.Security.Cryptography
    Imports System.Text
    					
  5. Declare a string variable to hold your source data, and two byte arrays (of undefined size) to hold the source bytes and the resulting hash value.
    Dim sSourceData As String
    Dim tmpSource() As Byte
    Dim tmpHash() As Byte
    					
  6. Use the GetBytes() function, which is part of the System.Text.ASCIIEncoding.ASCII class, to convert your source string into an array of bytes (required as input to the hashing function).
    sSourceData = "MySourceData"
    'Create a byte array from source data.
    tmpSource = ASCIIEncoding.ASCII.GetBytes(sSourceData)
    					
  7. Compute the MD5 hash for your source data by calling ComputeHash on an instance of the MD5CryptoServiceProvider class. Note that to compute another hash value, you will need to create another instance of the class.
    'Compute hash based on source data.
    tmpHash = New MD5CryptoServiceProvider().ComputeHash(tmpSource)
    					
  8. The tmpHash byte array now holds the computed hash value (128-bit value=16 bytes) for your source data. It is often useful to display or store a value like this as a hexadecimal string, which the following code accomplishes:
    Console.WriteLine(ByteArrayToString(tmpHash))
    
    Private Function ByteArrayToString(ByVal arrInput() As Byte) As String
        Dim i As Integer
        Dim sOutput As New StringBuilder(arrInput.Length)
        For i = 0 To arrInput.Length - 1
            sOutput.Append(arrInput(i).ToString("X2"))
        Next
        Return sOutput.ToString()
    End Function
    					
  9. Save and then run your code to see the resulting hexadecimal string for the source value.
back to the top

Compare Two Hash Values

One of the purposes of creating a hash from source data is to provide a way to see if data has changed over time, or to compare two values without ever working with the actual values. In either case, you need to compare two computed hashes, which is easy if they are both stored as hexadecimal strings (as in the last step of the above section). However, it is quite possible that they will both be in the form of byte arrays. The following code, which continues from the code created in the previous section, shows how to compare two byte arrays.
  1. Just below the creation of a hexadecimal string, create a new hash value based on new source data.
    sSourceData = "NotMySourceData"
    tmpSource = ASCIIEncoding.ASCII.GetBytes(sSourceData)
    
    Dim tmpNewHash() As Byte
    Dim bEqual As Boolean = False
    tmpNewHash = New MD5CryptoServiceProvider().ComputeHash(tmpSource)
    					
  2. The most straightforward way to compare two byte arrays is to loop through the arrays, comparing each individual element to its counterpart from the second value. If any elements are different, or if the two arrays are not the same size, the two values are not equal.
    If tmpNewHash.Length = tmpHash.Length Then
        Dim i As Integer
        Do While (i < tmpNewHash.Length) AndAlso (tmpNewHash(i) = tmpHash(i))
            i += 1
        Loop
        If i = tmpNewHash.Length Then
            bEqual = True
        End If
    End If
    
    If bEqual Then
        Console.WriteLine("The two hash values are the same")
    Else
        Console.WriteLine("The two hash values are not the same")
    End If
    Console.ReadLine()
    					
  3. Save and then run your project to view the hexadecimal string created from the first hash value, and to find out if the new hash is equal to the original.
back to the top

Complete Code Listing

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

Module Module1

    Sub Main()
        Dim sSourceData As String
        Dim tmpSource() As Byte
        Dim tmpHash() As Byte
        sSourceData = "MySourceData"
        'Create a byte array from source data.
        tmpSource = ASCIIEncoding.ASCII.GetBytes(sSourceData)

        'Compute hash based on source data.
        tmpHash = New MD5CryptoServiceProvider().ComputeHash(tmpSource)
        Console.WriteLine(ByteArrayToString(tmpHash))

        sSourceData = "NotMySourceData"
        tmpSource = ASCIIEncoding.ASCII.GetBytes(sSourceData)

        Dim tmpNewHash() As Byte
        Dim bEqual As Boolean = False
        tmpNewHash = New MD5CryptoServiceProvider().ComputeHash(tmpSource)

        If tmpNewHash.Length = tmpHash.Length Then
            Dim i As Integer
            Do While (i < tmpNewHash.Length) AndAlso (tmpNewHash(i) = tmpHash(i))
                i += 1
            Loop
            If i = tmpNewHash.Length Then
                bEqual = True
            End If
        End If

        If bEqual Then
            Console.WriteLine("The two hash values are the same")
        Else
            Console.WriteLine("The two hash values are not the same")
        End If
        Console.ReadLine()
    End Sub


    Private Function ByteArrayToString(ByVal arrInput() As Byte) As String
        Dim i As Integer
        Dim sOutput As New StringBuilder(arrInput.Length)
        For i = 0 To arrInput.Length - 1
            sOutput.Append(arrInput(i).ToString("X2"))
        Next
        Return sOutput.ToString()
    End Function
End Module
				
back to the top

REFERENCES

For more information on using the cryptographic features of the Microsoft .NET Framework, and on cryptography in general, see the following links: back to the top

Modification Type:MinorLast Reviewed:10/3/2006
Keywords:kbvs2005applies kbvs2005swept kbCrypt kbSecurity kbHOWTOmaster KB301053 kbAudDeveloper