Library code snippets

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

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.

Comments

  1. 27 Jul 2008 at 15:07

    I'm sure you've found the answer by now, but in case anybody else is on the same quest, maybe this will help:

    Porting the Equivalent of PHP’s MD5 to .NET platform in C#

     

  2. 27 Jul 2008 at 15:01

    Maybe you will find this post adds more light to the issue.

  3. 23 Nov 2007 at 22:37

     Hi just like jitz I am struggling to realise a result that matches the SHA1 result when using php can anybody help clarify how to get the same result pls

  4. 05 Feb 2007 at 02:57
    Is it possible to hash files instead of text? I know I can do it with MD5 and SHA1 (with a FileStream and "System.Security.Cryptography.MD5CryptoServiceProvider" and "System.Security.Cryptography.SHA1CryptoServiceProvider")

    but when I tried generated any others it gave me a diffrent hash every time(SHA256,SHA384 and SHA512)...



  5. 18 Sep 2006 at 14:29

    Hi,

    I'm using SHA1 to hash the some code in vb.net(desktop app). but when i create SHA1 in PHP it doesn't match with the one i created with vb.net.I filtered out all the special chars in hash generated using vb.net (like =,+ etc).The hash thus trimmed out is only 20-22 chars but when i used php itz above 30. Pls help me

    Tom

  6. 08 May 2006 at 18:48

    Thanks a lot

  7. 09 Nov 2004 at 18:05

    Note, the author wrote that the result of a Hash is unique.  This is NEVER the case for a hash function.  Hashes are consistent.  Given a hash function H and a value a, H(a) = H(a) (i.e., hashes aren't random in a way which varies invocation to invocation.


    But given a,b with a!=b it is not true that H(a) != H(b).  Indeed for any digest hash one can find a,b with a!=b and H(a) = H(b).


    BE WARNED.  Never hash something that is used as a primary key.  E.g., HASH passwords but never hash usernames.

  8. 23 Apr 2004 at 11:21

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


    Another note:
    Yes, there is a simpeler way to do md5 and sha1, but if i have a class for SHA256, 384 and 512, I'd like to combine all of them into one not doing 512 with the class and sha1 with something else.

  9. 21 Apr 2004 at 20:35

    For SHA1 and MD5 you can simply use:


    string hashedText = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile("some text", "sha1");

  10. 01 Jan 1999 at 00:00

    This thread is for discussions of Create Hashes - MD5, SHA1, SHA256, SHA384, SHA512 .

Leave a comment

Sign in or Join us (it's free).

David Cumps

Related podcasts

  • Object-Oriented Programming in Ruby

    In this episode, I talk with Scott Bellware about object-oriented programming in Ruby, and Ruby's object model. This is taken from a private conversation, and the audio quality suffers at times. Much thanks to Scott for allowing this to be released.This episode of the Alt.NET Podcast is bro...

We'd love to hear what you think! Submit ideas or give us feedback