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);
时刻与技术进步,每天一点滴,日久一大步!!!
本博客只为记录,用于学习,如有冒犯,请私信于我。