• Home
  • Tutorials
  • Development Tools
  • Contact Us

Developing Software

Mastering Software Craftsmanship

How to Create an MD5 Hash of a String in C# and Displaying a Gravatar Image

13th March 2016 by @developingsoft

The MD5 (message-digest algorithm) in used in a wide variety of cryptographic applications, and is commonly used to verify data integrity.

The following code will show you how to create a simple utility class that converts strings into MD5 hashes, and an example of its usage by creating a Gravatar image link.

The HashUtil class

public class HashUtil
{
    public static string CreateMD5(string input)
    {
        if (string.IsNullOrEmpty(input))
        {
            throw new ArgumentNullException("input");
        }

        using (var md5 = MD5.Create())
        {
            byte[] inputBytes = Encoding.ASCII.GetBytes(input);
            byte[] hash = md5.ComputeHash(inputBytes);

            // convert byte array to hex string
            var sb = new StringBuilder();
            for (int i = 0; i < hash.Length; i++)
            {
                sb.Append(hash[i].ToString("X2"));
            }

            return sb.ToString();
        }
    }
}

Example usage

The following example creates an MD5 hash of an email address and then builds a Gravatar URL.

string hash = HashUtil.CreateMD5("[email protected]");
string url = String.Format("//www.gravatar.com/avatar/{0}?d=mm", hash);
Share this on:

Filed Under: Tutorials Tagged With: C#

Search

Advertisement

Newsletter

Subscribe now to receive practical tips on how to become a better software developer.

Free - No Spam - 100% Email Privacy

Featured Posts

Abstract Factory Pattern: C# Example Using the Unity Game Engine

23 Software Design Patterns That Will Make You a More Effective Programmer

How to Deploy an ASP.NET Core Website to Ubuntu with Git

How to Run an ASP.NET Core Website in Production on Ubuntu Linux

How to Install the Edimax Wireless nano USB Adapter on Windows IoT Core for Raspberry Pi

How to Convert a Post Title into a Friendly URL (Slug) in C#

How to Convert Markdown to HTML in ASP.NET Core

How to Send an E-Mail with ASP.NET Core and Mailgun

How to Generate a Sitemap in ASP.NET MVC and ASP.NET Core

How to Create an MD5 Hash of a String in C# and Displaying a Gravatar Image

© 2014–2023 Developing SoftwareTerms • Privacy