Set an image for Gravatars - Globally Recognized Avatar

Sign In or Register

Gravatars - Globally Recognized Avatar

Connect: Features
PUBLIC PROFILE

Gravatars - Globally Recognized Avatar Home

http://en.gravatar.com/site/implement/java

Java

Things are a little complex in Java. The following class will provide you with a static method that returns the hex format md5 of an input string:

<code>
  import java.util.*;
  import java.io.*;
  import java.security.*;
  public class MD5Util {    
    public static String hex(byte[] array) {        
        StringBuffer sb = new StringBuffer();        
        for (int i = 0; i < array.length; ++i) {            
     sb.append(Integer.toHexString((array[i] 
         & 0xFF) | 0x100).substring(1,3));        
        }        
        return sb.toString();    
    }    
    public static String md5Hex (String message) {         
        try {             
     MessageDigest md = 
         MessageDigest.getInstance("MD5");             
     return hex (md.digest(message.getBytes("CP1252")));         
        } catch (NoSuchAlgorithmException e) {         
        } catch (UnsupportedEncodingException e) {         
        }         
        return null;    
    }    
  }
  </code>

This class can then be used to return the MD5 hash of an email address like this:

String email = "someone@somewhere.com";
 String hash = MD5Util.md5Hex(email);

With the hex string that is returned, you can construct your gravatar URL.

Sign in to add your comment.