How Do I...? Common Tasks QuickStart Tutorial
How Do I...Generate and compare a hash value?
It is easy to generate and compare hash values using the cryptographic resources contained
in the System.Security.Cryptography namespace. Because all hash functions take input of
type Byte[], it might be necessary to convert the source into a byte array before it is
hashed.
To generate a hash value, create an instance of a hash algorithm and call
ComputeHash() on it. The following code creates an instance of the MD5 hash
algorithm and calls ComputeHash() on it. The hash function returns a byte array
containing the hash value of the byte array Input
Dim HashVal As Byte() = New MD5CryptoServiceProvider().ComputeHash(Input)
VB
Note that ComputeHash() is the final operation performed on an instance of a hash
object. If another hash value needs to be generated, a new instance of a hash algorithm must
be created.
System.Security.Cryptography contains implementations of MD5, SHA1,
SHA256, SHA384, and SHA512. The following code computes a SHA1 hash value.
Dim HashVal As Byte() = New SHA1CryptoServiceProvider().ComputeHash(Input)
VB
To compare hash values, perform an element-by-element comparison of the hash value byte
arrays.
Example
VB hash.exe
[This sample can be found at H:\Home\WU_000036_efe47225c86ca62f325a01d8519bc002\Webs\aspnet.sk\quickstarts\QuickStartv20\howto\samples\cryptography\hash\
To build this sample, open the SDK command prompt and navigate to the above path. Build the sample using the build tool msbuild
passing the solution file as the first parameter: msbuild mySample.sln. The compiled executable will be found in the sub directory \bin
directory.]
Microsoft .NET Framework SDK QuickStart Tutorials Version 2.0
Copyright � 2005 Microsoft Corporation. All rights reserved.
|