1 import java.security.MessageDigest; 2 public static String MD5(byte[] btInput) 3 { 4 char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 5 'A', 'B', 'C', 'D', 'E', 'F' 6 }; 7 try 8 { 9 10 //获得MD5摘要算法的 MessageDigest 对象 11 MessageDigest mdInst = MessageDigest.getInstance("MD5"); 12 //使用指定的字节更新摘要 13 mdInst.update(btInput); 14 //获得密文 15 byte[] md = mdInst.digest(); 16 //把密文转换成十六进制的字符串形式 17 int j = md.length; 18 char str[] = new char[j * 2]; 19 int k = 0; 20 for (int i = 0; i < j; i++) 21 { 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 } 28 catch (Exception e) 29 { 30 e.printStackTrace(); 31 return null; 32 } 33 } 34 35 public static void main(String[] args) 36 { 37 String strTest = "sfdsfs中华"; 38 byte[] c = strTest.getBytes(); 39 byte[] b = strTest.getBytes("utf-8"); 40 System.out.println(MD5Util.MD5(c)); 41 System.out.println(MD5Util.MD5(b)); 42 //B696DB892244130D3B9F9C4FE17B4A61 43 //20CB170D82ADC9967E1F8F096F7ED00B 44 }
有时候真是无语,哎!都要自己测试,多尝试,多思考,少叽歪。