
Generating Hash Codes form Streamed Data
• The ComputeHash() method has been overloaded to receive a System.IO.Stream derived type.
• This makes it very simple to obtain a hash code for a file, incoming bit-stream or a directory on the hard
drive.
• Assume you wish to obtain the hash value for a text file which contains the following data:
• Notice that the name of this file is myData.txt.
• The following code will yield a hash code based on the file contents using the SAH1 hash algorithm:
• If the content of this file is altered in anyway, it will yield a completely different hash code.
• Recall, hash codes are used to ensure the integrity of a message.
• If Bob discovers a unique hash code from the original, Bob knows Eve has tampered with the file.
// C# code (VB code would be similar)
static void Main(string[] args)
{
// Hash the myData.txt file.
FileStream fs = new FileStream("myData.txt", FileMode.Open);
SHA1 sha = SHA1.Create();
byte[] fileHashValue = sha.ComputeHash(fs);
Console.WriteLine("Hash code of myData.txt");
foreach(byte x in fileHashValue)
Console.Write("{0:X2} ", x);
fs.Close();
}
Streamed Data
Table of Contents
Copyright (c) 2008. Intertech, Inc. All Rights Reserved. This information is to be used exclusively as an
online learning aid. Any attempts to copy, reproduce, or use for training is strictly prohibited.
Courseware
Training Resources
Tutorials