This utility class can generate md5 of any string and is also compatible with PHP.

import java.security.MessageDigest;
 
/**
 * @author Sudhaker Raj (http://sudhaker.com)
 */
public class Md5Util {
 
  /**
   * @param value
   * @return
   */
  public static String encodeMd5(String value) {
    StringBuffer encoded = new StringBuffer();
    if (value != null) {
      try {
        MessageDigest md5 = MessageDigest.getInstance("MD5");
        md5.update(value.getBytes());
        byte[] digest = md5.digest();
        for (int i = 0; i < digest.length; ++i) {
          int b = (int) digest[i] & 0xFF;
          if (b < 16)
            encoded.append("0");
          encoded.append(Integer.toHexString(b));
        }
      } catch (Exception e) {
        // ignore exceptions
      }
    }
    return encoded.toString();
  }
}

Posted Friday, September 19th, 2008 at 1:11 pm
Filed Under Category: Java Technologies
You can skip to the end and leave a response. Pinging is currently not allowed.

1

Response to “Java Easy MD5”

Sudhaker

In case you need stronger hash,

import java.security.MessageDigest;
 
/**
 * @author Sudhaker Raj
 */
public class HashUtil {
 
  private static final String ALGORITHM = "SHA-256";
  /**
   * @param value
   * @return
   */
  public static String encode(String value) {
    StringBuffer encoded = new StringBuffer();
    if (value != null) {
      try {
        MessageDigest md = MessageDigest.getInstance(ALGORITHM);
        md.update(value.getBytes());
        byte[] digest = md.digest();
        for (int i = 0; i < digest.length; ++i) {
          int b = (int) digest[i] & 0xFF;
          if (b < 16)
            encoded.append("0");
          encoded.append(Integer.toHexString(b));
        }
      } catch (Exception e) {
        // ignore exceptions
      }
    }
    return encoded.toString();
  }
}

Leave a Reply

CAPTCHA image