實例代碼:注釋都很清楚,
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
|
import java.security.MessageDigest; import javax.xml.bind.annotation.adapters.HexBinaryAdapter; public class Main { static String src = "Hello,sahadev!" ; public static void main(String[] args) { MD5(); MD2(); SHA(); } /** * MD5加密 */ public static void MD5() { try { // 獲取MD5加密工具 MessageDigest md = MessageDigest.getInstance( "MD5" ); // 加密 byte [] digest = md.digest(src.getBytes()); // 獲取二進制十六進制互轉工具 HexBinaryAdapter hexBinaryAdapter = new HexBinaryAdapter(); // 將二進制數組轉換為十六進制字符串 String marshal = hexBinaryAdapter.marshal(digest); // 輸出結果 System.out.println(marshal); } catch (Exception e) { e.printStackTrace(); } } /** * MD2加密 */ public static void MD2() { try { // 獲取MD2加密工具 MessageDigest md = MessageDigest.getInstance( "MD2" ); // 加密 byte [] digest = md.digest(src.getBytes()); // 獲取二進制十六進制互轉工具 HexBinaryAdapter hexBinaryAdapter = new HexBinaryAdapter(); // 將二進制數組轉換為十六進制字符串 String marshal = hexBinaryAdapter.marshal(digest); // 輸出結果 System.out.println(marshal); } catch (Exception e) { e.printStackTrace(); } } public static void SHA() { try { // 獲取MD2加密工具 MessageDigest md = MessageDigest.getInstance( "SHA" ); // 加密 byte [] digest = md.digest(src.getBytes()); // 獲取二進制十六進制互轉工具 HexBinaryAdapter hexBinaryAdapter = new HexBinaryAdapter(); // 將二進制數組轉換為十六進制字符串 String marshal = hexBinaryAdapter.marshal(digest); // 輸出結果 System.out.println(marshal); } catch (Exception e) { e.printStackTrace(); } } } |
輸出結果:
1
2
3
|
MD5 : 8FC69C57ACC2258C7B4A9D39DC4C940B MD2 : 9EAF08289903A29C3C58D2AAA25BD83D SHA : 1B1330BFC6257FC9F4B4ED5CB605FA4109608CCA |
以上就是java 加密的實例,如疑問請留言或者到本站社區交流討論,感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!