Skip to content

Instantly share code, notes, and snippets.

@bjarnef
Last active September 24, 2016 16:07
Show Gist options
  • Save bjarnef/c3b136b338cef6d7de1c59422b913d4c to your computer and use it in GitHub Desktop.
Save bjarnef/c3b136b338cef6d7de1c59422b913d4c to your computer and use it in GitHub Desktop.
using System.Security.Cryptography;
using System.Text;
namespace My.Library
{
public class GravatarHelper
{
public static string GetGravatarImage(string email)
{
string hash = HashEmailForGravatar(email);
return string.Format("https://www.gravatar.com/avatar/{0}", hash);
}
public static string GetGravatarImage(string email, int size)
{
return string.Format("{0}?size={1}", GetGravatarImage(email), size);
}
///
/// Hashes an email with MD5. Suitable for use with Gravatar profile
/// image urls
///
/// The email address to hash
///
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.
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment