13 Jul

C# Create A MD5 Hash From A String

This example shows how to create a MD5 hash from a string.

Usage:

            string hash = CreateMD5Hash("http://www.csharpexamples.com");
            Console.WriteLine(hash);
            //Output: 
            //E426A83F137FA324C3412B92193EED1F
        public string CreateMD5Hash(string input)
        {
            // Step 1, calculate MD5 hash from input
            MD5 md5 = System.Security.Cryptography.MD5.Create();
            byte[] inputBytes = System.Text.Encoding.ASCII.GetBytes(input);
            byte[] hashBytes = md5.ComputeHash(inputBytes);
            
            // Step 2, convert byte array to hex string
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < hashBytes.Length; i++)
            {
                sb.Append(hashBytes[i].ToString("X2"));
            }
            return sb.ToString();
        }

2 thoughts on “C# Create A MD5 Hash From A String

  1. You should use UTF8 not ASCII for the input normalization as well as normalizing the input string for consistent hashing of strings with special/joint characters…

    Encoding.UTF8.GetBytes(input.Normalize(NormalizationForm.FormKC))

Leave a Reply to Hifni Cancel reply

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