How to create a md5 hash in C#

Here a quick example how to create from an string an md5 hash in c# and output it as string. The only difficult is to convert from string to byte array and back again. So i have to method, one accept the byte array direct and returns a byte array, the second method handles the convert from string to byte array and back again.

		using System.Security.Cryptography;
		
        public static string GetMD5(string text)
        {
            if (text == null)
            {
                return string.Empty;
            }

            byte[] message = System.Text.Encoding.ASCII.GetBytes(text);
            byte[] hashValue = GetMD5(message);

			string hashString = string.Empty;
            foreach (byte x in hashValue)
            {
                hashString += string.Format("{0:x2}", x);
            }

            return hashString;

        }

        private static byte[] GetMD5(byte[] message)
        {
            MD5 hashString = new MD5CryptoServiceProvider();
            return hashString.ComputeHash(message);
        }

If you only need a quick convert a md5 string, you can use my md5 online tool.


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.