C# Programming > Data

C# Compute Hash

Hash Values

Computing hash values in C# can be efficiently done with the System.Security.Cryptography namespace.

Hash values have many applications in .NET programs that are not ony related to cryptography. Of course, hash values are a secure way to store passwords for example. But hash values can also be used to compare class objects or files too.

Computing Hash Values

There is no single way to compute a hash value. Any algorithm that can take a set of data and produce a string representation is considering a hashing algorithm. This means that there are good hashing functions and bad ones. Generally hash values do not fully represent the original data, which means that you cannot turn a hash value back into the original data.

Another factor is what the hash value will be used for. A hash value might be compared to verify the validity of a file. For this purpose, the hash value should be considerably smaller than the file in most cases. On the other hand, a hash value used to compare passwords do not have to be smaller than the password.

C# developers can write their own hashing algorithm, but luckily they don't have to. The System.Security.Cryptography namespace contains several .NET classes that implement some popular hashing algorithms.

.NET ComputeHash

The following classes have the ComputeHash function: SHA1CryptoServiceProvider, SHA1Managed, SHA256Managed, SHA384Managed, SHA512Managed, MD5CryptoServiceProvider, SHA1, SHA256, SHA384, SHA512, MD5.

There are a lot of classes, however the ones listed are variations of the SHA1 and MD5 algorithms. All of them have the ComputeHash function which takes an array of bytes and returns the hash value in an array of bytes.

So for example, a function to calculate the MD5 hash value of a string, would look something like this:

private string MD5(string input)
{
    MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();

    byte[] originalBytes = ASCIIEncoding.Default.GetBytes(input);
    byte[] encodedBytes = md5.ComputeHash(originalBytes);

    return BitConverter.ToString(encodedBytes).Replace("-", "");
}

GetHashCode

You may also notice that every class object in C# has a GetHashCode function. This function returns an integer hash value that represents the class object. The concept is still the same, hash values are used to compare instances of a class. Thus GetHashCode usually goes hand in hand with the Equals function.

All in all, computing hash codes in C# is useful across a number of scenarios.

Back to C# Article List