MD5 Hash Keys with C#

Did you ever try to compute a md5 hash key with C# .NET? No? Lucky guy.

When you think of PHP there’s one command called md5(). When you think of C#, you need an MD5CryptoServiceProvider, Streams and other things like byte arrays that holds the computed hash code and so on.

You see – that’s a job for a helper class. I called it the Md5CryptHelper class. The goal was to offer a simple method like md5() known from PHP.

So here it is:

const string KEY = "MoonWalk";

string keyHash = Md5CryptHelper.ComputeHash(KEY);
Console.WriteLine(KEY + " Hash: " + keyHash);

If you’re interessted you can download the source code using the following link:
Download the source code of md5 Hash Keys with C#.

6 Responses to “MD5 Hash Keys with C#”

  1. Gavin Kendall Says:

    public static string MD5Hash(string text)
    {
    System.Security.Cryptography.MD5 md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
    byte[] md5password = md5.ComputeHash(Encoding.ASCII.GetBytes(text));
    StringBuilder result = new StringBuilder();
    foreach (byte b in md5password)
    result.Append(b.ToString(“x2″));
    return result.ToString();
    }

  2. Gavin Kendall Says:

    and yet another way to do it…

    public static string MD5Hash(string text)
    {
    System.Security.Cryptography.MD5 md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
    return System.Text.RegularExpressions.Regex.Replace(BitConverter.ToString(md5.ComputeHash(ASCIIEncoding.Default.GetBytes(text))), “-”, “”);
    }

    whatever works *shrugs*

  3. Gerhard Says:

    Hi Gavin,
    your version is the most elegant I ever seen. Respect!

    Cheers
    Gerhard

  4. Harvey Says:

    Hi Gavin,

    How would you add into the above method a way of using a key for the MD5 Hash? Only I would like to decrypt the string at the other end using a known key.

    Many thanks,

  5. Gerhard Says:

    A Md5 Encryption is a one way street. You can’t decrypt it. That’s why it’s safe. For example. You store the password, given by the user, md5 encrypted in database. No one can decrypt it, but if the user enteres the password in order to log in, you can encrypt the entered password again and check if the encrypted password matches the encrypted password stored in database.

    That’s the hint.


Leave a Reply