1 package test.md5; 2 3 import java.security.MessageDigest; 4 5 public class MD5Util { 6 public final static String MD5(String s) { 7 char hexDigits[]={'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'}; 8 9 try { 10 byte[] btInput = s.getBytes(); 11 // 获得MD5摘要算法的 MessageDigest 对象 12 MessageDigest mdInst = MessageDigest.getInstance("MD5"); 13 // 使用指定的字节更新摘要 14 mdInst.update(btInput); 15 // 获得密文 16 byte[] md = mdInst.digest(); 17 // 把密文转换成十六进制的字符串形式 18 int j = md.length; 19 char str[] = new char[j * 2]; 20 int k = 0; 21 for (int i = 0; i < j; i++) { 22 byte byte0 = md[i]; 23 str[k++] = hexDigits[byte0 >>> 4 & 0xf]; 24 str[k++] = hexDigits[byte0 & 0xf]; 25 } 26 return new String(str); 27 } catch (Exception e) { 28 e.printStackTrace(); 29 return null; 30 } 31 } 32 33 public static void main(String[] args) { 34 System.out.println(MD5Util.MD5("20121221")); 35 System.out.println(MD5Util.MD5("加密")); 36 } 37 }