Last active
September 24, 2016 16:07
-
-
Save bjarnef/c3b136b338cef6d7de1c59422b913d4c to your computer and use it in GitHub Desktop.
GravatarHelper - inspired from http://www.danesparza.net/2010/10/using-gravatar-images-with-c-asp-net/
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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