編寫代碼之前先來介紹一下我們要用到的兩個包;
commons-codec-1.10.jar
Commons項目中用來處理常用的編碼方法的工具類包,例如DES、SHA1、MD5、Base64,URL,Soundx等等。
commons-exec-1.3.jar
Apache Commons Exec 是 Apache 上的一個 Java 項目,提供一些常用的方法用來執行外部進程
你可以到本站直接下載 Apache Commons 官方包
下面看一下代碼結構:
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
|
import org.apache.commons.codec.binary.Base64; import org.apache.commons.codec.digest.DigestUtils; /** * @author Delver_Si * */ public class EncodeAndDecode { /** * Md5加密 * @param str * @return */ public static String Md5encode(String str) { return DigestUtils.md5Hex(str); } /** * Base64加密 * @param str * @return */ public static String Base64encode(String str) { byte [] b = Base64.encodeBase64(str.getBytes(), true ); return new String(b); } /** * Base64解密 * @param str * @return */ public static String Base64decode(String str) { byte [] b = Base64.decodeBase64(str.getBytes()); return new String(b); } /** * 生成SHA1 */ public static String SHA1encode(String str) { return DigestUtils.sha1Hex(str); } } |
把主要功能都放在一個類文件中
新建Test類引用上個文件
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
import security.EncodeAndDecode; import security.Exec; public class Test { public static void main(String[] args) { System.out.println(EncodeAndDecode.Md5encode( "zzvips.com" )); //MD5加密 System.out.println(EncodeAndDecode.Base64encode( "zzvips.com" )); //Base64加密 System.out.println(EncodeAndDecode.Base64decode( "amI1MS5uZXQ=" )); //Base64解密 String str = Exec.exec( "ping zzvips.com" ); //執行系統的Ping命令 System.out.println(str); } } |
好了 ,運行一下看看最終結果
這些只是Apache commons 包的基本功能,其它功能大家可以到這里下載 apache commons 使用說明 中文WORD版 詳細研究