commons-codec
is a package provided by the Apache Open source organization for digest operations and encoding. In this package is divided into four types of encryption: Binaryencoders, Digestencoders, Languageencoders, Networkencoders.
Today I would like to introduce you how to use commons-codec
the package to complete the common coding, digest operations.
Base64
Example code:
@TestpublicvoidtestBase64(){ System.out.println("==============Base64================"); byte"jianggujin".getBytes(); new Base64(); String encode = base64.encodeAsString(data); System.out.println(encode); System.out.println(new String(base64.decode(encode)));}
Operation Result:
==============Base64================amlhbmdndWppbg==jianggujin
MD5 Digest Operations
Example code:
@TestpublicvoidtestMD5(){ System.out.println("==============MD5================"); String result = DigestUtils.md5Hex("jianggujin"); System.out.println(result);}
Operation Result:
acab4efdfd3b8efcdec37fe160d7be0e
Summary operations such as SHA and MD5 are similar.
Urlcodec
Example code:
@TestpublicvoidtestURLCodecthrows Exception{ System.out.println("==============URLCodec================"); new URLCodec(); "蒋固金"; "UTF-8"); System.out.println(encode); "UTF-8"));}
Operation Result:
==============URLCodec================%E8%92%8B%E5%9B%BA%E9%87%91蒋固金
Complete Sample code:
PackageCom.gujin.codec;ImportOrg.apache.commons.codec.binary.Base64;ImportOrg.apache.commons.codec.digest.DigestUtils;ImportOrg.apache.commons.codec.net.URLCodec;ImportOrg.junit.Test; Public class codectest{ @Test Public void testBase64() {System.out.println ("==============base64================");byte[] data ="Jianggujin". GetBytes (); Base64 base64 =NewBase64 (); String encode = base64.encodeasstring (data); System.out.println (encode); System.out.println (NewString (Base64.decode (encode))); }@Test Public void testMD5() {System.out.println ("==============md5================"); String result = Digestutils.md5hex ("Jianggujin"); SYSTEM.OUT.PRINTLN (result); }@Test Public void Testurlcodec()throwsException {System.out.println ("==============urlcodec================"); Urlcodec codec =NewUrlcodec (); String data ="Shung"; String encode = codec.encode (data,"UTF-8"); System.out.println (encode); System.out.println (Codec.decode (Encode,"UTF-8")); }}
Commons-codec Usage Introduction