
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
Verifying that a String Remains Uncorrupted Following Transmission
|
963
The output of this method is shown here when the string is corrupted:
False
The string: This is the string that we'll #$%^(&&*2 be testing.
has become corrupted.
Discussion
You can use a hash, checksum, or cyclic redundancy check (CRC) to calculate a value
based on a message. This value is then used at the destination to determine whether
the message has been modified during transmission between the source and
destination.
This recipe uses a hash value as a reliable method of determining whether a string
has been modified. The hash value for this recipe is calculated using the
SHA256Managed class. This hash value is 256 bits in size and produces greatly differing
results when calculated from strings that are very similar, but not exactly the same.
In fact, if a single letter is removed or even capitalized, the resulting hash value will
change.
By appending this value to the string, both the string and hash values can be sent to
their destination. The destination then removes the hash value and calculates a hash
value of its own based on the received string. These two hash values are then com-
pared. If they are equal, the strings are exactly the same. If they are not equal, you
can be sure that somewhere between the