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.
}
@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