MD5 in C# - works like php md5() example

chris (2004-10-06 13:40:13)
24471 views
2 replies
This example shows an example method written in C# which will calculate an MD5 checksum and return a string. This works like the PHP md5() function. The code is fairly simple - just cut and paste it and it will work, but don't forget to use the System.Security.Cryptography namespace in your source code.

So the method actually looks like this:
public static string MD5(string password) {
   byte[] textBytes = System.Text.Encoding.Default.GetBytes(password);
   try {
      System.Security.Cryptography.MD5CryptoServiceProvider cryptHandler;
      cryptHandler = new System.Security.Cryptography.MD5CryptoServiceProvider();
      byte[] hash = cryptHandler.ComputeHash (textBytes);
      string ret = "";
      foreach (byte a in hash) {
         if (a<16)
            ret += "0" + a.ToString ("x");
         else
            ret += a.ToString ("x");
      }
      return ret ;
   }
   catch {
      throw;
   }
}
And here is an example of a full application which uses it. Cut and paste all of the source code below into your editor, compile and run.
using System;
using System.Text;
using System.Security.Cryptography;

class md5demo {
	static void Main(string[] args) {
		string plain, hashed;
                
		plain = "secretword";
		hashed = MD5(plain);

		Console.WriteLine("plain version is "+plain);
		Console.WriteLine("hashed version is "+hashed);
	}

	public static string MD5(string password) {
		byte[] textBytes = System.Text.Encoding.Default.GetBytes(password);
		try {
			System.Security.Cryptography.MD5CryptoServiceProvider cryptHandler;
			cryptHandler = new System.Security.Cryptography.MD5CryptoServiceProvider();
			byte[] hash = cryptHandler.ComputeHash (textBytes);
			string ret = "";
			foreach (byte a in hash) {
				if (a<16)
					ret += "0" + a.ToString ("x");
				else
					ret += a.ToString ("x");
			}
			return ret ;
		}
		catch {
			throw;
		}
	}
}
I hope you find that useful. If you would like to see how to do that in Java, then please follow the java md5 example.


christo

comment
timg
2007-02-20 09:20:27

ta very muchly

4462 views and no thanks....thats a bit tight ;) easiest example I found.

thanks
t
reply icon
Josh
2008-05-12 16:55:11


if (a<16)
    ret += "0" + a.ToString ("x");
else
    ret += a.ToString ("x");


This can be reduced to:
ret += a.ToString("x2");

Hope that helps someone.
reply iconedit reply