- Back to Home »
- Say what? Hash in my code?!
At some point you will eventually find the need to implement a way of either verifying or securing part of your data with the use of cryptographic hash functions. Luckily .NET offers a comprehensive set of classes for this task found in the System.Security.Cryptography namespace.
What is a cryptographic hash function? Well, for a meaningful explanation do refer to this Wikipedia article and afterwards think of it as a digital fingerprint (or checksum if you prefer).
Like i said, .NET offers a comprehensive set of classes to accommodate the need for hashing, and although simple to work with out-of-the-box, it can be rather cumbersome in the long run as you have to remember which algorithm type to use, create a byte array and last but not least; remember to dispose your object afterwards. This is one of the reasons why I introduced the static HashUtility class; to ease the usage while offering a flexible way of hashing your objects.
The overloads taking either a string or a string array in the above mentioned class, all uses UTF-16 as the backing encoding by design, where as most online hashing generators uses UTF-8. However, this can easily be overridden by using of the many overloads of the ComputeHash method.
Supported hash algorithm types per April 24th 2013 is:
- MD5 (default)
Let's get on with the show; in Figure 1 you can see an example of a simple PasswordHashExample class that will use a SHA256 hash algorithm using UTF-8 for backing encoding, where Figure 2 show an equally simple test method that uses this class. Figure 3 shows the output of the test.
Figure 1: A simple class to show a potential usage of the HashUtility class
Figure 2: An equally simple test method that utilizes the class in Figure 1
Figure 3: The output of the test in Figure 2
As you can see, the usage is very simple and the only thing you need to consider is the encoding should you choose to use one of the overloads where a string or an array of strings needs hashing. Since all strings in .NET "per se" is UTF-16 encoded, this is also the default here; but only for the string overloads.
I hope you liked this little sneak preview into the HashUtility class. Happy coding.