3. Hashing Data from Memory
The simplest way to generate a hash code is to use
data held in memory. The overloaded ComputeHash
method is able to create a hash code from a byte array, as shown by
the following signature:
# C#
public byte[] ComputeHash(
byte[] buffer
);
# Visual Basic .NET
Overloads Public Function ComputeHash( _
ByVal buffer( ) As Byte _
) As Byte( )
The ComputeHash returns a byte array that contains
the hash code for the message data. The following class demonstrates
how to create a hash code for a StringSystem.Text.Encoding class
to convert the string to a byte array: value; note
that you should use the
# C#
using System;
using System.Text;
using System.Security.Cryptography;
class StringHash {
static void Main(string[] args) {
// define the string that we will
// create a hash code for
String x_str = "Programming .NET Security";
// create a byte array from the string
byte[] x_message_data = Encoding.Default.GetBytes(x_str);
// create an instance of the MD5 hashing algorithm
HashAlgorithm x_hash_alg = HashAlgorithm.Create("MD5");
// obtain the hash code from the HashAlgorithm by
// using the ComputeHash method
byte[] x_hash_code = x_hash_alg.ComputeHash(x_message_data);
// print out the hash code to the console
foreach (byte x_byte in x_hash_code) {
Console.Write("{0:X2} ", x_byte);
}
}
}
# Visual Basic .NET
Imports System
Imports System.Text
Imports System.Security.Cryptography
Module StringHash
Sub Main( )
' define the string that we will
' create a hash code for
Dim x_str As String = "Programming .NET Security"
' create a byte array from the string
Dim x_message_data( ) As Byte = Encoding.Default.GetBytes(x_str)
' create an instance of the MD5 hashing algorithm
Dim x_hash_alg As HashAlgorithm = HashAlgorithm.Create("MD5")
' obtain the hash code from the HashAlgorithm by
' using the ComputeHash method
Dim x_hash_code( ) As Byte = x_hash_alg.ComputeHash(x_message_data)
' print out the hash code to the console
Dim x_byte As Byte
For Each x_byte In x_hash_code
Console.Write("{0:X2} ", x_byte)
Next
End Sub
End Module
The output from this example is:
E1 62 9F C2 96 85 C3 A4 5B 94 97 57 D8 9C 65 78
To make the hash code easier to read, convert each byte to a
hexadecimal value and print a space between each one. When you used
the ComputeHash method in the previous example,
you wanted to process an entire byte array; however, the
HashAlgorithm class includes a different version
of the method, which can process a region of a byte array:
# C#
public byte[] ComputeHash(
byte[] buffer,
int offset,
int count
);
# Visual Basic .NET
Overloads Public Function ComputeHash( _
ByVal buffer( ) As Byte, _
ByVal offset As Integer, _
ByVal count As Integer _
) As Byte( )