4. Hashing Streamed Data
You can also
create a hash code from a stream of data; this is useful for
processing datafiles or for reading data from a network connection.
The HashAlgorithm class contains an overloaded
version of the ComputeHash method for working with
streams:
# C#
public byte[] ComputeHash(
Stream inputStream
);
# Visual Basic .NET
Overloads Public Function ComputeHash( _
ByVal inputStream As Stream _
) As Byte( )
The following class demonstrates how to create a hash code using a
stream, in this case streaming data from a file called
myfile.txt, which contains the string
"Programming .NET Security":
# C#
using System;
using System.IO;
using System.Security.Cryptography;
class StreamHash {
static void Main(string[] args) {
// create the file stream
Stream x_stream = new FileStream("mydata.txt", FileMode.Open);
// 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_stream);
// print out the hash code to the console
foreach (byte x_byte in x_hash_code) {
Console.Write("{0:X2} ", x_byte);
}
// close the stream
x_stream.Close( );
}
}
# Visual Basic .NET
Imports System
Imports System.IO
Imports System.Security.Cryptography
Module StreamHash
Sub Main( )
' create the file stream
Dim x_stream As Stream = New FileStream("mydata.txt", FileMode.Open)
' 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_stream)
' 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
' close the stream
x_stream.Close( )
End Sub
End Module
As you might expect, the output from the example, shown below, is the
same hash code produced by our first example:
E1 62 9F C2 96 85 C3 A4 5B 94 97 57 D8 9C 65 78