Create Hashes - MD5, SHA1, SHA256, SHA384, SHA512

Posted Saturday, February 28, 2004 6:40 PM by CumpsD
Today I'll talk about hash functions.

A hash algorithm takes a piece of text and gives a hash as result. This hash is unique for the given text. If you use the hash function on the same text again, you'll get the same hash. But there is no way to get the given text from the hash. This is great for storing passwords.

Now, in PHP it's as easy as using md5() or sha1(). But in C# it takes a bit more work. This is what we want to simplify.

So we'll create a Hash class to create hashes.

Create a new project and add a class (Hash).

using System;

using System.Security.Cryptography;

using System.Text;

 

namespace Hash {

      public class Hash {

            public Hash() { }

           

      } /* Hash */

} /* Hash */


Let's start by adding an enum representing all the hash functions we are going to support.

public enum HashType :int { MD5, SHA1, SHA256, SHA384, SHA512 }


Our class will have 2 public methods, one for creating a hash and one for checking a hash against a given text.

First we'll create the GetHash method:

public static string GetHash(string strPlain, HashType hshType) {

      string strRet;

      switch (hshType) {

            case HashType.MD5: strRet = GetMD5(strPlain); break;

            case HashType.SHA1: strRet = GetSHA1(strPlain); break;

            case HashType.SHA256: strRet = GetSHA256(strPlain); break;

            case HashType.SHA384: strRet = GetSHA384(strPlain); break;

            case HashType.SHA512: strRet = GetSHA512(strPlain); break;

            default: strRet = "Invalid HashType"; break;

      }

      return strRet;

} /* GetHash */


And our CheckHash will depend on this so we might as well add it now.

public static bool CheckHash(string strOriginal, string strHash, HashType hshType) {

      string strOrigHash = GetHash(strOriginal, hshType);

      return (strOrigHash == strHash);

} /* CheckHash */


As you can see, I created 5 seperate methods to create hashes. I'll explain one for this article, the others are the same but use another hashing class. You'll find them in the source at the end of this article.

A hash function works on a byte array, so we will create two arrays, one for our resulting hash and one for the given text.

UnicodeEncoding UE = new UnicodeEncoding();

byte[] HashValue, MessageBytes = UE.GetBytes(strPlain);


Now we create an object that will hash our text:

SHA1Managed SHhash = new SHA1Managed();


And finally we calculate the hash and convert it to a hexadecimal string. Which we can store in a database for example.

string strHex = "";

 

HashValue = SHhash.ComputeHash(MessageBytes);

foreach(byte b in HashValue) {

      strHex += String.Format("{0:x2}", b);

}

return strHex;


This is how we test it:

static void Main(string[] args) {

      String hash = Hash.Hash.GetHash("This is a sample text :p", Hash.Hash.HashType.SHA256);

      Console.WriteLine(hash);

      Console.WriteLine(Hash.Hash.CheckHash("This is a sample text :p", hash, Hash.Hash.HashType.SHA256));

      Console.WriteLine(Hash.Hash.CheckHash("This is a wrong text.", hash, Hash.Hash.HashType.SHA256));

} /* Main */


Now we have our sweet and simple methods available as a class, ready to be used in any project.

I've uploaded the sources again, you will see I documented it as well. When you use NDoc on the generated .xml file you get a very sweet MSDN like documentation.

Important Update:
To get the same result as the md5() function in PHP, use ASCIIEncoding!
As in: ASCIIEncoding UE = new ASCIIEncoding();

Filed under:

Comments

# Just a thought..

Saturday, February 28, 2004 1:19 PM by Gilad Goldberg

Why convert the hashed value to a string? It is still storable - be it a binary field in a DB, or a binary file :)

# re: Create Hashes - MD5, SHA1, SHA256, SHA384, SHA512

Saturday, February 28, 2004 1:32 PM by Dhoore

nice done, yeah in php it's indeed easier :)

# re: Create Hashes - MD5, SHA1, SHA256, SHA384, SHA512

Saturday, February 28, 2004 2:38 PM by David Cumps

Why, well, to make it resemble the PHP function :)

But also, I don't know if cookies can store binary data? But I'm sure they can work with strings, so to be 'universal' (read: in my projects) I made it as a string. Because you kinda have a guarantee that you always can get away with strings. And I don't know if you have the same as a binary array?

If you have the same garantee, than I'd like to know :) Because I create my classes in image of what I know at that time, which can change in the future.

# re: Create Hashes - MD5, SHA1, SHA256, SHA384, SHA512

Monday, March 08, 2004 11:37 AM by Tom Mertens

There is actually a static method in ASP.NET's form authentication class that allows you to do it somewhat easier. Have a look at "FormsAuthentication.HashPasswordForStoringInConfigFile". It takes two arguments: the password and a string containing "md5" or "sha1" which states the hashing algorithm to use. But I must admit that the method's name in PHP is somewhat shorter. :)
More info at http://msdn.microsoft.com/library/en-us/cpref/html/frlrfSystemWebSecurityFormsAuthenticationClassHashPasswordForStoringInConfigFileTopic.asp

# re: Create Hashes - MD5, SHA1, SHA256, SHA384, SHA512

Monday, March 08, 2004 1:18 PM by David Cumps

Thanks for pointing that out!

I'll remember that when I need md5/sha1. In our current project I went a bit paranoid and used sha512 ;)

# Using .NET Cryptographic Hash Classes

Saturday, March 13, 2004 5:12 PM by TrackBack

Using .NET Cryptographic Hash Classes

# re: MD5, SHA1, SHA256, SHA384, SHA512 Hash class article.

Saturday, March 27, 2004 2:56 AM by TrackBack

# re: Create Hashes - MD5, SHA1, SHA256, SHA384, SHA512

Sunday, May 16, 2004 1:11 AM by a

How create a verify for web form?