2. Instantiating the Algorithm
The first step toward creating a
hash code is to create an instance of an implementation class for the
algorithm that you want to use. The simplest way of doing this is to
use the name of the class directly:
# C#
SHA1Managed x_hash_alg = new SHA1Managed( );
# Visual Basic .NET
Dim x_hash_alg As SHA1Managed = New SHA1Managed( )
This statement creates an instance of the managed-code implementation
of the SHA-1 algorithm. This is the clearest and most direct approach
to instantiating hashing algorithms. Another approach is to use the
static HashAlgorithm.Create method to instantiate
the class indirectly:
# C#
HashAlgorithm x_hash_alg = HashAlgorithm.Create("SHA1");
# Visual Basic .NET
Dim x_hash_alg As HashAlgorithm = HashAlgorithm.Create("SHA1")
The Create
method instantiates an algorithm based on the value of the string
argument. Table 2 lists the mapping between
string values and implementation classes.
Table 2. Mapping string values to algorithm classes
String value
|
Algorithm-implementation class
|
---|
MD5
|
MD5CryptoServiceProvider
|
System.Security.Cryptography.MD5
|
MD5CryptoServiceProvider
|
SHA
|
SHA1CryptoServiceProvider
|
SHA1
|
SHA1CryptoServiceProvider
|
System.Security.Cryptography.SHA1
|
SHA1CryptoServiceProvider
|
SHA256
|
SHA256Managed
|
SHA-256
|
SHA256Managed
|
System.Security.Cryptography.SHA256
|
SHA256Managed
|
SHA384
|
SHA384Managed
|
SHA-384
|
SHA384Managed
|
System.Security.Cryptography.SHA384
|
SHA384Managed
|
SHA512
|
SHA512Managed
|
SHA-512
|
SHA512Managed
|
System.Security.Cryptography.SHA512
|
SHA512Managed
|
If you do not supply a string as an argument to the Create method or
the string is not one of the values listed in Table 13-3, then the
System.Security.Cryptography.SHA1CryptoServiceProvider algorithm will be used as a default.
|
|
This approach is less direct but does have a number of benefits.
First, we only have to change the value of the string to change the
algorithm that is used. Second, the systems administrator can alter
the mappings listed in Table 2 by editing the
.NET configuration files, potentially allowing a customer to use a
different algorithm for specific tasks. For example, a customer may
want to use specialized hardware to generate hash codes rather than
relying on the default software implementations. We recommend that
you use the HashAlgorithm.Create method for the
flexibility that it offers.