Recipe 12.22. Calculating a Checksum for a File


Problem

You want to ensure that the contents of a file have not changed, perhaps after transmitting that file over the Internet.

Solution

Sample code folder: Chapter 12\GenerateChecksum

Generate a checksum for the file. A checksum is a short value or string that is built using the contents of the file. Calculating a checksum on identical content will yield identical results, but different input produces different and varying checksums. A good checksum-generating algorithm is very sensitive to even the smallest change in the source data (a file, in this case).

Discussion

Create a new Windows Forms application, and add two TextBox controls named FileToCheck and HexChecksum and a Button control named GenerateChecksum to the form. Set the HexChecksum.ReadOnly property to TRue. Add some informational labels and arrange the controls to look like Figure 12-14.

Figure 12-14. Controls for the file checksum sample


Add the following source code to the form's class template. We've also included some needed Imports statements:

 Imports System.Text Imports System.Security.Cryptography Public Class Form1    Private Sub GenerateChecksum_Click( _          ByVal sender As System.Object, _          ByVal e As System.EventArgs) _          Handles GenerateChecksum.Click       ' ----- The hash value is ready, but I like things in       '       plain text when possible. Let's convert it to a       '       long hex string.       Dim checksum As Byte( )       Dim counter As Integer       Dim result As String       ' ----- Generate the checksum for the file.       Try          checksum = GenerateFileChecksum(FileToCheck.Text)       Catch ex As Exception          MsgBox("An error occurred while trying to " & _             "calculate the checksum:" & _             vbCrLf & vbCrLf & ex.Message)          Exit Sub       End Try       ' ----- Prepare the checksum for display.       If (checksum Is Nothing) Then          result = "No checksum result."       Else          ' ----- Convert the checksum into something readable.          result = ""          For counter = 0 To checksum.Length - 1             result &= String.Format("{0:X2}", _                checksum(counter))          Next counter       End If       ' ----- Show the result to the user.       HexChecksum.Text = result    End Sub    Public Function GenerateFileChecksum( _          ByVal filePath As String) As Byte( )       ' ----- Use the HMACSHA1 hashing function to generate       '       a checksum for a file.       Dim hashingFunction As HMACSHA1       Dim hasingBase( ) As Byte       Dim hashValue( ) As Byte       Dim inStream As IO.Stream       ' ----- Make sure the file exists.       If (My.Computer.  FileSystem.FileExists(filePath) _             = False) Then          Throw New IO.FileNotFoundException          Return Nothing       End If       ' ----- Prepare the   hashing key. You have to use       '       the same hashing key every time, or you       '       will get different results.       hasingBase = (New UnicodeEncoding).GetBytes("Cookbook")       ' ----- Create the hashing component using the Managed       '       SHA-1 function.       hashingFunction = New HMACSHA1(hasingBase, True)       ' ----- Open the file as a stream.       inStream = New IO.  FileStream(filePath, _          IO.FileMode.Open, IO.FileAccess.Read)       ' ----- Calculate the checksum value.       hashValue = hashingFunction.ComputeHash(inStream)       ' ----- Finished with the file.       inStream.Close( )       ' ----- Return the checksum as a byte array.       Return hashValue    End Function End Class 

To use the program, type in a file path, and click the Generate button. The resulting 40-hex-digit checksum will appear in the HexChecksum field. Figure 12-15 shows the results of a checksum calculation.

Figure 12-15. A checksum generated for an executable file


Checksums are especially useful when you want to know if two files, or two sets of data, contain identical content. They are typically generated using a hashing algorithm, a processing method that takes some original content and generates a summary value representing the full content. Hashing algorithms process the input data in blocks. As a hash is calculated for each block, the next block is brought in and applied to or overlaid on the existing hash. This constant merging of the data makes the algorithms very sensitive to any changes in the source content.

The .NET Framework includes several hashing algorithms and encryption features in the System.Security.Cryptography namespace. This recipe's code uses the HMACSHA1 class (Hash-based Message Authentication Code, or HMAC, via the SHA-1 hash function) in that namespace to generate the hash. Hash functions such as the SHA-1 function were developed by private organizations and government security agencies to help protect sensitive content. Several similar hash functions and related encryption algorithms are included in System.Security.Cryptography for your use.




Visual Basic 2005 Cookbook(c) Solutions for VB 2005 Programmers
Visual Basic 2005 Cookbook: Solutions for VB 2005 Programmers (Cookbooks (OReilly))
ISBN: 0596101775
EAN: 2147483647
Year: 2006
Pages: 400

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net