commons-codec介紹


commons-codec是Apache開源組織提供的用於摘要運算、編碼解碼的包。常見的編碼解碼工具Base64、MD5、Hex、SHA1、DES等。

/**
 * *********** Base64編碼和解碼  ***********
 * 核心類
 *      org.apache.commons.codec.binary.Base64
 * 核心方法
 *      encodeToString 編碼
 *      decode 解碼
 */
Base64 base64 = new Base64();
String str = "AAaaa我";
String result = base64.encodeToString(str.getBytes("UTF-8"));//編碼
System.out.println(result);
byte[] decode = base64.decode(result.getBytes());//解碼
System.out.println(new String(decode));
/**
 * *********** Hex編碼和解碼  ***********
 * 核心類
 *      org.apache.commons.codec.binary.Hex
 * 核心方法
 *      encodeHexString, encodeHex 編碼
 *      decodeHex 解碼
 */
String str_1 = "test";
/**編碼*/
String hexString = Hex.encodeHexString(str_1.getBytes("UTF-8"));//直接一步到位
System.out.println(hexString);
char[] encodeHex = Hex.encodeHex(str_1.getBytes(), true);//先轉換成char數組,第二個參數意思是是否全部轉換成小寫
System.out.println(new String(encodeHex));
/**解碼*/
byte[] decodeHex = Hex.decodeHex(encodeHex);//char數組型的
System.out.println(new String(decodeHex));
byte[] decodeHex2 = Hex.decodeHex(hexString.toCharArray());//字符串類型的,該方法要求傳入的是char[]
System.out.println(new String(decodeHex2));

/**
 * *********** MD5加密  ***********
 * 核心類
 *      org.apache.commons.codec.digest.DigestUtils
 * 核心方法
 *      md5Hex 編碼
 */
String str_2 = "test";
String md5 = DigestUtils.md5Hex(str_2.getBytes("UTF-8"));
System.out.println(md5);

/**
 * *********** SHA加密  ***********
 * 核心類
 *      org.apache.commons.codec.digest.DigestUtils
 * 核心方法
 *      sha1Hex 編碼
 */
String str_3 = "test中國";
String sha1Hex = DigestUtils.sha1Hex(str_3.getBytes("UTF-8"));
System.out.println(sha1Hex);

/**
 * *********** URLCodec  ***********
 * 核心類
 *      org.apache.commons.codec.net.URLCodec
 * 核心方法
 *      encode 編碼
 *      decode 解碼
 */
String url = "http://baidu.com?name=你好";
URLCodec codec = new URLCodec();
String encode = codec.encode(url);
System.out.println(encode);
String decodes = codec.decode(encode);
System.out.println(decodes);

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM