Create a String from a Hash

Have you ever wanted to create a hash from an input and then convert the hash back to a string for storing? It's fairly simple to do with the .NET Framework. But why not create your own class to encapsulate the logic for easy use later on. Read on to learn how to create a simple class to perform this task.

First start by creating a class which in this example I will call HashProvider. The purpose behind this class is to expose a method to generate a hash and convert it back to string for each of hash algorithms included in the .NET Framework. In this class we will create one method called "GetHashString" which will take two inputs. The first input will be the text that you want to encrypt. The second will be an instance of the HashAlgorithm class. It is in this method that the meat of the work will be performed.

public virtual string GetHashString(string plainText, HashAlgorithm algorithm)

{

// Convert the plain text to a byte array

byte[] byteArray = Encoding.ASCII.GetBytes(plainText);

 

// Call the algorithm's ComputeHash method to encrypt the byte array

algorithm.ComputeHash(byteArray);

 

// Convert the encrypted byte array back to a string

string encryptedText = BitConverter.ToString(algorithm.Hash);

 

// Return the string to the caller

return encryptedText;

}

With this method in place it is very easy to generate a hash as a string. But let's take a step further. Let's create methods for a couple of the algorithms. Here I will create two methods - one to create an MD5 hash and another for an SHA1 hash. Each one will only contain one line of code that will make a call to the GetHashString method we just created.

public virtual string GetMd5Hash(string plainText)

{

return GetHashString(plainText, new MD5CryptoServiceProvider());

}

 

public virtual string GetSha1Hash(string plainText)

{

return GetHashString(plainText, new SHA1CryptoServiceProvider());

}

Summary

As you can see with the GetHashString in place it is very easy to create a hash of any type. You can also build on this example and create methods for all of the algorithms that are included in the framework.

New Comment

  
  
  
  
Download Source Code
Email Print