1package util;
2
3import java.security.MessageDigest;
4
5public class StringUtil {
6
7 private final static String[] hexDigits = {
8 "0", "1", "2", "3", "4", "5", "6", "7",
9 "8", "9", "a", "b", "c", "d", "e", "f"};
10
11 /** *//**
12 * 转换字节数组为16进制字串
13 * @param b 字节数组
14 * @return 16进制字串
15 */
16
17 public static String byteArrayToHexString(byte[] b) {
18 StringBuffer resultSb = new StringBuffer();
19 for (int i = 0; i < b.length; i++) {
20 resultSb.append(byteToHexString(b[i]));
21 }
22 return resultSb.toString();
23 }
24
25 private static String byteToHexString(byte b) {
26 int n = b;
27 if (n < 0)
28 n = 256 + n;
29 int d1 = n / 16;
30 int d2 = n % 16;
31 return hexDigits[d1] + hexDigits[d2];
32 }
33
34 public static String MD5Encode(String origin) {
35 String resultString = null;
36
37 try {
38 resultString=new String(origin);
39 MessageDigest md = MessageDigest.getInstance("MD5");
40 resultString=byteArrayToHexString(md.digest(resultString.getBytes()));
41 }
42 catch (Exception ex) {
43
44 }
45 return resultString;
46 }
47
48 public static void main(String[] args){
49 System.err.println(MD5Encode(""));
50 System.err.println(MD5Encode("a"));
51 System.err.println(MD5Encode("abc"));
52 System.err.println(MD5Encode("message digest"));
53 System.err.println(MD5Encode("abcdefghijklmnopqrstuvwxyz"));
54
55 }
56
57 //MD5 ("") = d41d8cd98f00b204e9800998ecf8427e
58 //MD5 ("a") = 0cc175b9c0f1b6a831c399e269772661
59 //MD5 ("abc") = 900150983cd24fb0d6963f7d28e17f72
60 //MD5 ("message digest") = f96b697d7cb7938d525a2f31aaf161d0
61 //MD5 ("abcdefghijklmnopqrstuvwxyz") = c3fcd3d76192e4007dfb496cca67e13b
62
63
64
65}
66
Let life be beautiful like summer flowers and death like autumn leaves.