Skip to content

Instantly share code, notes, and snippets.

@danesparza
Created May 16, 2011 04:02
Show Gist options
  • Save danesparza/973923 to your computer and use it in GitHub Desktop.
Save danesparza/973923 to your computer and use it in GitHub Desktop.
Gravatar in C# - creating the hash
using System.Security.Cryptography;
/// Hashes an email with MD5. Suitable for use with Gravatar profile
/// image urls
public static string HashEmailForGravatar(string email)
{
// Create a new instance of the MD5CryptoServiceProvider object.
MD5 md5Hasher = MD5.Create();
// Convert the input string to a byte array and compute the hash.
byte[] data = md5Hasher.ComputeHash(Encoding.Default.GetBytes(email));
// Create a new Stringbuilder to collect the bytes
// and create a string.
StringBuilder sBuilder = new StringBuilder();
// Loop through each byte of the hashed data
// and format each one as a hexadecimal string.
for(int i = 0; i < data.Length; i++)
{
sBuilder.Append(data[i].ToString("x2"));
}
return sBuilder.ToString(); // Return the hexadecimal string.
}
@rawnsley
Copy link

rawnsley commented Oct 9, 2013

A very useful snippet. Note that the email address should be trimmed and forced lower case before hashing according to the Gravatar hash guidelines: https://en.gravatar.com/site/implement/hash/

@jaredfaris
Copy link

Helpful gist. Thanks!

@mbonell
Copy link

mbonell commented Oct 30, 2014

Nice, thanks

@azabluda
Copy link

md5Hasher is IDisposable, so I would also recommend using to avoid leaks.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment