Working of Hash Provider

The Cryptography Application Block is developed with same principles as for other application blocks it separates the implementation from the usage. So it means the hash provider configuration can be updated without impacting the application code. But how does this work? The application block provides an interface called IHashProvider, which is part of Microsoft.Practices.EnterpriseLibrary.Security.Cryptography namespace; this contract defines two methods, CreateHash, and CompareHash to create and compare hashes respectively. These methods accept both input and hash value as byte arrays; any class implementing this interface is required to provide the implementation for both the CreateHash and CompareHash methods.

The following screenshot shows the definition of the IHashProvider interface:

Working of Hash Provider

The HashAlgorithmProvider class, which inherits from the IHashProvider interface, is a hash provider implementation for hash algorithms derived from the System.Security.Cryptography.HashAlgorithm class. This class internally utilizes the HashCryptographer class, which provides basic cryptographic services for a hash algorithm. It also has another hash provider named KeyedHashAlgorithmProvider apparently inheriting from the HashAlgorithmProvider class; as the name suggests this is a hash provider for hash algorithms deriving from the System.Security.Cryptography.KeyedHashAlgorithm class.

The following diagram shows the definition of the HashAlgorithmProvider class:

Working of Hash Provider

The following diagram shows the members and inheritance hierarchy of the KeyedHashAlgorithmProvider class.

Working of Hash Provider

The first step in leveraging the hash functionality is to configure a hash provider in the configuration file using the configuration editor. Once we have the configuration in place, we can access the required functionality either using the static facade, service locator, or using Unity container directly. Regardless of approach, the application block identifies the configured hash provider and loads it to be used while creating and comparing hash value.

Creating CryptographyManager and IHashProvider instances

We have several options at hand; while utilizing the static facade we can either use the static Cryptographer class or we can create CryptographyManager or IHashProvider implementation objects using Unity service locator or using Unity container directly. A few approaches such as configuring the container through a configuration file or code are not listed here but the recommended approach is either to use the Unity service locator for applications with few dependencies or create objects using Unity container by loading through configuration or programmatically to leverage the benefits of this approach. Use of the static factory class is not recommended.

Using the static facade

Static factory classes were the default approach to creating objects with versions prior to 5.0. This approach is no longer recommended and is still available for backwards compatibility. The Cryptography Application Block provides a static class called Cryptographer available in the Microsoft.Practices.EnterpriseLibrary.Security.Cryptography namespace. This static facade class provides methods to generate and compare hashes, and also encrypt and decrypt data using the configured providers; this approach does not require creation of any object to perform the required actions.

Using Unity service locator

This approach is recommended for applications with few dependencies; the EnterpriseLibraryContainer class exposes a static property called Current of type IServiceLocator, which resolves and gets an instance of the specified type.

The following code snippet creates an instance of CryptographyManager:

CryptographyManager cryptoManager = EnterpriseLibraryContainer.Current.GetInstance<CryptographyManager>();

The following is a code snippet to create a deafult IHashProvider implementation instance using Unity service locator:

IHashProvider defaultHashProvider = EnterpriseLibraryContainer.Current.GetInstance<IHashProvider>();

The following is a code snippet to create a named IHashProvider implementation instance using Unity service locator:

IHashProvider hashProvider = EnterpriseLibraryContainer.Current.GetInstance<IHashProvider>("SHA256Managed");

Using Unity container directly

Larger complex applications demand looser coupling. This approach leverages the dependency injection mechanism to create objects instead of explicitly creating instances of concrete implementations. Unity container resolves objects using the type registrations and mappings; these can be configured programmatically or through a configuration file. Based on the configuration, it resolves the appropriate type whenever requested. The following example instantiates a new Unity container object and adds the Enterprise Library Core Extension. This loads the configuration and makes registrations and mappings of the Enterprise Library available.

The following is a code snippet to create a default CryptographyManager instance using UnityContainer:

var container = new UnityContainer();
container.AddNewExtension<EnterpriseLibraryCoreExtension>();
CryptographyManager cryptoManager = container.Resolve<CryptographyManager>();

The following is a code snippet to create a deafult IHashProvider implementation instance using UnityContainer:

var container = new UnityContainer();
container.AddNewExtension<EnterpriseLibraryCoreExtension>();
IHashProvider defaultHashProvider = container.Resolve<IHashProvider>();

The following is a code snippet to create a named IHashProvider implementation instance using UnityContainer:

var container = new UnityContainer();
container.AddNewExtension<EnterpriseLibraryCoreExtension>();
IHashProvider hashProvider = container.Resolve<IHashProvider>("SHA256Managed");

Configuring Hash Provider

We have already learned to add Cryptography Settings to the configuration file; click on the plus symbol provided on the top right-corner of the Hash Providers section, navigate, and click Add Hash Providers | Add Hash Algorithm Provider. This action will display the Hash Algorithm selection dialog box. For the purposes of this demonstration, we will select SHA256Managed, which is part of System.Security.Cryptography namespace, and hit the OK button.

The following screenshot shows the menu option Add Hash Algorithm Provider:

Configuring Hash Provider

Once we click on the menu option Add Hash Algorithm Provider, the following HashAlgorithm selection dialog is displayed:

Configuring Hash Provider

The previous action will result in addition of SHA256Managed hash provider in the configuration as shown in the following screenshot.

Configuring Hash Provider

Note

By default the property Salt Enabled is set to True; this property determines whether a random string (salt value) is generated and pre-pended to the plain text before hashing. Salt values help in protecting against dictionary attacks by making it difficult to generate the hash.

Generating a hash value

Generating the hash for a given string or byte[] is pretty simple; we create an instance of either CryptographyManager or IHashProvider using the methods described in the section Creating CryptographyManager and IHashProvider instances. Once we have the respective object, we can invoke the CreateHash method. While creating a hash using IHashProvider the CreateHash method accepts and returns a byte[] whereas CryptographyManager provides an overloaded CreateHash method that accepts and returns string objects as well. IHashProvider allows us to leverage the Default Hash Provider configuration and additionally a named instance can also be constructed.

The following code snippet shows the creation of the hash for the given text using a CryptographyManager instance:

CryptographyManager cryptoManager = EnterpriseLibraryContainer.Current.GetInstance<CryptographyManager>();
string hashValue = cryptoManager.CreateHash("SHA256Managed", "Some text to be hashed");

In the above code snippet, we have created an instance of CryptographyManager or rather its real implementation the CryptographyManagerImpl class. Next, we invoke the CreateHash method, passing the configured hash provider name SHA256Managed and the plain text that must be hashed. Although the generated hash value will not make any sense, it will definitely give you an idea of its gibberish nature.

The following text is the generated hash value:

4yieYiwA9YXAbGiIme1GWtjKJtXUpbKOiQl6Q6VApL30zCXtuL1UfQgTTAA1TItq

Comparing hash values

Comparing hash values for a given string or byte[] is also a simple affair. We follow the same process of creating an instance of either CryptographyManager or IHashProvider using the methods described in the section Creating CryptographyManager and IHashProvider instances. Next, we invoke the CompareHash method; depending on the object, we may or may not pass the hash instance name as the first parameter; the other two parameters accepts plain text and the hashed value for comparison.

The following code snippet shows the comparison of a hash value with the given text:

CryptographyManager cryptoManager = EnterpriseLibraryContainer.Current.GetInstance<CryptographyManager>();
string hashValue = "4yieYiwA9YXAbGiIme1GWtjKJtXUpbKOiQl6Q6VApL30zCXtuL1UfQgTTAA1TItq";
bool result = cryptoManager.CompareHash("SHA256Managed", "Some text to be hashed", hashValue);

The CompareHash method for the above given code snippet will result in a return value of true.

Implementing a custom Hash Provider

Although the .NET Framework provides implementation of several hash algorithms, there might be a scenario in which we will need to use a custom hash provider to meet certain proprietary or statutory requirements. The Cryptography block provides extensibility points that allow us to configure a custom hash provider without re-compiling the code. Apart from the assemblies listed in section referencing required and optional assemblies, we will have to add an additional reference of System.Configuration.dll. This assembly is used to indicate the configuration object type specified using the ConfigurationElementType attribute. As pointed out previously, the IHashProvider interface is the contract that every hash provider must implement. This interface provides two methods, CreateHash and CompareHash.

Adding the following namespaces will help in saving IDE real estate and improve readability of the code and so it is recommended to add these namespaces.

  • System.Collections.Specialized
  • Microsoft.Practices.EnterpriseLibrary.Common.Configuration
  • Microsoft.Practices.EnterpriseLibrary.Security.Cryptography
  • Microsoft.Practices.EnterpriseLibrary.Security.Cryptography.Configuration

Although the following code is self explanatory, we will attempt to make a quick walkthrough of the code snippet. We have a written a class named CustomHashProvider, which inherits from the IHashProvider interface and provides a stub implementation for demonstration purposes. Just in case you are wondering what the first line of code is all about, the attribute ConfigurationElementType attribute indicates the configuration object CustomHashProviderData used for CustomHashProvider. We also have to provide a constructor that accepts a parameter of type NameValueCollection.

The following code snippet demonstrates the implementation of a custom hash provider:

[ConfigurationElementType(typeof(CustomHashProviderData))]
public class CustomHashProvider : IHashProvider
{
public CustomHashProvider(NameValueCollection attributes)
{
}
public bool CompareHash(byte[] plaintext, byte[] hashedtext)
{
// Create hash of plain text and compare with hashed text
}
public byte[] CreateHash(byte[] plaintext)
{
// Implementing Custom Hashing Logic
}
}

Configuring a Custom Hash Provider

While leveraging the custom hash provider implementation, we have to follow a slightly different route for configuration. In the Hash Providers of Cryptography Settings click on the plus symbol; navigate and click Add Hash Providers | Add Custom Hash Provider. This action will display a types browsing dialog box listing the types derived from the IHashProvider interface. For the purposes of this demonstration, we will select the CustomHashProvider implementation. Post selection, we will have the custom hash provider configured; the configuration editor allows us to add custom key/value attributes, which will be passed on to the constructor of CustomHashProvider.

The following screenshot shows the menu option Add Custom Hash Provider:

Configuring a Custom Hash Provider

Once we click on the Add Custom Hash Provider menu option, custom hash provider selection dialog is displayed as shown in the given screenshot:

Configuring a Custom Hash Provider

Once we select the custom hash provider type and click the OK button, the configuration editor adds the selected hash provider as shown in the following screenshot:

Configuring a Custom Hash Provider

With these simple steps, the custom hash provider is configured and is ready to be used.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.117.188.138