In the previous page, we saw an example of a simple MD5 hashing algorithm and how it's easily implemented in your web application. The term "salt" is used to describe an addition. Some examples available on the web will use additional strings such as username or the url of the site. In this example, we'll use a double encryption technique, and the salt will be the outcome of the first encryption.
/// <summary>
/// Encrypts the string to a byte array using the MD5 Encryption
/// Algorithm with an additional Salted Hash.
/// <see cref="System.Security.Cryptography.MD5CryptoServiceProvider"/>
/// </summary>
/// <param name="ToEncrypt">System.String. Usually a password.</param>
/// <returns>System.Byte[]</returns>
public static byte[] MD5SaltedHashEncryption(string ToEncrypt)
{
// Create instance of the crypto provider.
MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
// Create a Byte array to store the encryption to return.
byte[] hashedbytes;
// Create a Byte array to store the salted hash.
byte[] saltedhash;
// let the show begin.
hashedbytes = md5.ComputeHash(
System.Convert.FromBase64String(ToEncrypt));
// Let's add the salt.
ToEncrypt += System.Convert.ToBase64String(hashedbytes);
// Get the new byte array after adding the salt.
saltedhash = md5.ComputeHash(textencoder.GetBytes(ToEncrypt));
// Destroy objects that aren't needed.
md5.Clear();
md5 = null;
// return the hased bytes to the calling method.
return saltedhash;
}
In this example, we use two System.Byte arrays to store our hash outputs. Furthermore, we use System.Convert.FromBase64 and System.Convert.ToBase64 rather than the Encoding class used in the previous example. You may apply other spices to this method by including another string and even the start and length of the first hash to use as salt. The more complicated you make the encryption, the harder it is to crack.
As you may have gathered, you can return a string value through the encrytion method by using the System.Convert.FromBase64 method. In some cases, it's optimal to store a string value; however, it is optimal to use the full byte array in storage for security purposes.
The output of the salted MD5 encryption method is:
MD5SaltedHashEncryption("MyPassw0rd1sTh1s")
212, 152, 90, 70, 106, 66, 10, 5, 25, 151, 21, 164, 143, 4, 128, 218
MD5SaltedHashEncryption("myPassw0rd1sTh1s")
231, 247, 149, 128, 190, 210, 57, 167, 39, 28, 223, 164, 48, 216, 88, 24
As you can see from this example, the output is further jumbled to give the encryption a little more flavor. To reiterate a previous point, it's best to further add to the salted scheme by adding an additional string (or more salt) to enhance the encryption further.