在我們的程序設計中,我們經常要加密一些特殊的內容,今天總結了幾個簡單的加密方法,分享給大家!
如何用JAVA實現字符串簡單加密解密?為保證用戶信息安全,系統在保存用戶信息的時候,務必要將其密碼加密保存到數據庫。
需要使用密碼的時候,取出數據,解密處理即可。
避免保存明文密碼。
方案一:
1
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
|
package com.tnt.util; import java.security.MessageDigest; public class StringUtil { private final static String[] hexDigits = { "0" , "1" , "2" , "3" , "4" , "5" , "6" , "7" , "8" , "9" , "a" , "b" , "c" , "d" , "e" , "f" }; /** * 轉換字節數組為16進制字串 * * @param b * 字節數組 * @return 16進制字串 */ public static String byteArrayToHexString( byte [] b) { StringBuffer resultSb = new StringBuffer(); for ( int i = 0 ; i < b.length; i++) { resultSb.append(byteToHexString(b[i])); } return resultSb.toString(); } private static String byteToHexString( byte b) { int n = b; if (n < 0 ) n = 256 + n; int d1 = n / 16 ; int d2 = n % 16 ; return hexDigits[d1] + hexDigits[d2]; } public static String MD5Encode(String origin) { String resultString = null ; try { resultString = new String(origin); MessageDigest md = MessageDigest.getInstance( "MD5" ); resultString = byteArrayToHexString(md.digest(resultString .getBytes())); } catch (Exception ex) { } return resultString; } public static void main(String[] args) { System.err.println(MD5Encode( "123456" )); } } |
方案二
1
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
|
package com.shangyu.core.utils; public class MD5 { public static String getMD5( byte [] source) { String s = null ; char hexDigits[] = { // 用來將字節轉換成 16 進制表示的字符 ‘ 0 ‘, ‘ 1 ‘, ‘ 2 ‘, ‘ 3 ‘, ‘ 4 ‘, ‘ 5 ‘, ‘ 6 ‘, ‘ 7 ‘, ‘ 8 ‘, ‘ 9 ‘, ‘a‘, ‘b‘, ‘c‘, ‘d‘, ‘e‘, ‘f‘ }; try { java.security.MessageDigest md = java.security.MessageDigest .getInstance( "MD5" ); md.update(source); byte tmp[] = md.digest(); // MD5 的計算結果是一個 128 位的長整數, // 用字節表示就是 16 個字節 char str[] = new char [ 16 * 2 ]; // 每個字節用 16 進制表示的話,使用兩個字符, // 所以表示成 16 進制需要 32 個字符 int k = 0 ; // 表示轉換結果中對應的字符位置 for ( int i = 0 ; i < 16 ; i++) { // 從第一個字節開始,對 MD5 的每一個字節 // 轉換成 16 進制字符的轉換 byte byte0 = tmp[i]; // 取第 i 個字節 str[k++] = hexDigits[byte0 >>> 4 & 0xf ]; // 取字節中高 4 位的數字轉換, // >>> // 為邏輯右移,將符號位一起右移 str[k++] = hexDigits[byte0 & 0xf ]; // 取字節中低 4 位的數字轉換 } s = new String(str); // 換后的結果轉換為字符串 } catch (Exception e) { e.printStackTrace(); } return s; } public static String getMD5(String str) { return getMD5(str.getBytes()); } public static void main(String[] args){ System.out.println(MD5.getMD5( "123456" )); } } |
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!