Cryptography
  Encrypt and decrypt a file
  Compare a hash value

Get URL for this page

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

[Run Sample] | [View Source]


Copyright 2001 Microsoft Corporation. All rights reserved.