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
Byte[] HashVal = (new MD5CryptoServiceProvider()).ComputeHash(Input);
C#
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.
Byte[] HashVal = (new SHA1CryptoServiceProvider()).ComputeHash(Input);
C#
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 C:\DevFusion.Data\legacy\quickstart.developerfusion.co.uk\QuickStart\howto\samples\cryptography\hash\]
Microsoft .NET Framework SDK QuickStart Tutorials Version 2.0
Copyright � 2004 Microsoft Corporation. All rights reserved.
|