java api強大啊,基本上常用的都為我們想到了,沒有想到的,也有開源項目。所以開源就是好啊,希望我哪天也能為開源作出自己的貢獻。
1 ///////////////////////////////////////////////////////////////////////////////
2 //
3 // 程序描述:MD5加密
4 //
5 // 作者:hcm
6 //
7 // 時間:2006-11-30
8 //
9 ////////////////////////////////////////////////////////////////////////////////
10 import java.security.*;
11 import java.security.spec.*;
12 class MD5
13 {
14 public final static String Md5 (String s)
15 {
16 //聲明并初始化一個字符數組,內含16元素
17 // char hexDigits[] = new char[16];
18 char hexDigits[] = {
19 '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '1', 'b', 'c', 'd', 'e', 'f'};
20 try
21 {
22 //待加密數據拆為字節數組
23 byte[] strTemp = s.getBytes ("utf-8");
24 //獲取MessageDigest 實例,應用程序提供信息摘要算法的功能
25 MessageDigest mdTemp = MessageDigest.getInstance ("MD5");
26 //處理
27 mdTemp.update (strTemp);
28 //處理完畢,將處理結果存入md 字節數組
29 byte[] md = mdTemp.digest ();
30 int j = md.length;
31 //構造一個字符數組,長度為處理結果的2倍
32 char str[] = new char[j * 2];
33 int k = 0;
34 //遍歷md,j = 16
35 for (int i = 0; i < j; i++)
36 {
37 byte temp = md[i];
38 str[k++] = hexDigits[temp >>>4 & 0xf];
39 str[k++] = hexDigits[temp & 0xf];
40 }
41 //結束 k 正好是2j =32
42 return new String (str);
43 }
44 catch (Exception e)
45 {
46 return null;
47 }
48 }
49 public static void main (String[] args)
50 {
51 System.out.println (MD5.Md5 ("XX"));
52 }
53 }
54
2 //
3 // 程序描述:MD5加密
4 //
5 // 作者:hcm
6 //
7 // 時間:2006-11-30
8 //
9 ////////////////////////////////////////////////////////////////////////////////
10 import java.security.*;
11 import java.security.spec.*;
12 class MD5
13 {
14 public final static String Md5 (String s)
15 {
16 //聲明并初始化一個字符數組,內含16元素
17 // char hexDigits[] = new char[16];
18 char hexDigits[] = {
19 '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '1', 'b', 'c', 'd', 'e', 'f'};
20 try
21 {
22 //待加密數據拆為字節數組
23 byte[] strTemp = s.getBytes ("utf-8");
24 //獲取MessageDigest 實例,應用程序提供信息摘要算法的功能
25 MessageDigest mdTemp = MessageDigest.getInstance ("MD5");
26 //處理
27 mdTemp.update (strTemp);
28 //處理完畢,將處理結果存入md 字節數組
29 byte[] md = mdTemp.digest ();
30 int j = md.length;
31 //構造一個字符數組,長度為處理結果的2倍
32 char str[] = new char[j * 2];
33 int k = 0;
34 //遍歷md,j = 16
35 for (int i = 0; i < j; i++)
36 {
37 byte temp = md[i];
38 str[k++] = hexDigits[temp >>>4 & 0xf];
39 str[k++] = hexDigits[temp & 0xf];
40 }
41 //結束 k 正好是2j =32
42 return new String (str);
43 }
44 catch (Exception e)
45 {
46 return null;
47 }
48 }
49 public static void main (String[] args)
50 {
51 System.out.println (MD5.Md5 ("XX"));
52 }
53 }
54