Created
May 16, 2011 04:02
-
-
Save danesparza/973923 to your computer and use it in GitHub Desktop.
Gravatar in C# - creating the hash
This file contains 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; | |
/// 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. | |
} |
Helpful gist. Thanks!
Nice, thanks
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
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/