簡單實現MD5加密字符串
1
package util;
2
3
import java.security.MessageDigest;
4
5
public 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

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

Let life be beautiful like summer flowers and death like autumn leaves.
posted on 2008-06-30 23:34 Alexwan 閱讀(2114) 評論(0) 編輯 收藏 所屬分類: J2EE 、小筆記