Java tutorial
//package com.java2s; import java.io.UnsupportedEncodingException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; public class Main { public static synchronized String md5(MessageDigest md5) { StringBuffer strBuf = new StringBuffer(); byte[] result16 = md5.digest(); char[] digit = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' }; for (int i = 0; i < result16.length; i++) { char[] c = new char[2]; c[0] = digit[result16[i] >>> 4 & 0x0f]; c[1] = digit[result16[i] & 0x0f]; strBuf.append(c); } return strBuf.toString(); } public static String md5(String string) { if (isEmptyStr(string)) { return ""; } try { return getMD5(string.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e.getMessage(), e); } } public static boolean isEmptyStr(String str) { if (str == null || str.trim().length() == 0) { return true; } else { return false; } } private static String getMD5(byte[] source) { try { MessageDigest md5 = MessageDigest.getInstance("MD5"); StringBuffer result = new StringBuffer(); for (byte b : md5.digest(source)) { result.append(Integer.toHexString((b & 0xf0) >>> 4)); result.append(Integer.toHexString(b & 0x0f)); } return result.toString(); } catch (Exception e) { throw new RuntimeException(e.getMessage(), e); } } @SuppressWarnings("finally") public static String getMD5(String str) { StringBuffer strBuf = new StringBuffer(); try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(str.getBytes()); byte[] result16 = md.digest(); char[] digit = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' }; for (int i = 0; i < result16.length; i++) { char[] c = new char[2]; c[0] = digit[result16[i] >>> 4 & 0x0f]; c[1] = digit[result16[i] & 0x0f]; strBuf.append(c); } } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } finally { return strBuf.toString(); } } }