Apache Commons Codec应用

JDK的java.security提供MessageDigest的编码方式,包括MD2,MD5,SHA-1,SHA-256,SHA-384,及 SHA-512等。Apache Commons Codec是对其的补充,添加了Base64, Hex, Phonetic 等编码方式。

Apache Commons Codec (TM) software provides implementations of common encoders and decoders such as Base64, Hex, Phonetic and URLs.

Impetus

Codec was formed as an attempt to focus development effort on one definitive implementation of the Base64 encoder. At the time of Codec's proposal, there were approximately 34 different Java classes that dealt with Base64 encoding spread over the Foundation's CVS repository. Developers in the Jakarta Tomcat project had implemented an original version of the Base64 codec which had been copied by the Commons HttpClient and Apache XML project's XML-RPC subproject. After almost one year, the two forked versions of Base64 had significantly diverged from one another. XML-RPC had applied numerous fixes and patches which were not applied to the Commons HttpClient Base64. Different subprojects had differing implementations at various levels of compliance with theRFC 2045.

Out of that confusing duplication of effort sprang this simple attempt to encourage code reuse among various projects. While this package contains a abstract framework for the creation of encoders and decoders, Codec itself is primarily focused on providing functional utilities for working with common encodings.

示例代码

import org.apache.commons.codec.binary.Base64;  

import org.apache.commons.codec.digest.DigestUtils;  



public class Test {

	     

	    public static String base64Encode(String data){    

	        return Base64.encodeBase64String(data.getBytes());  

	    }  

	      

	    public static byte[] base64Decode(String data){  

	        return Base64.decodeBase64(data.getBytes());  

	    }  

	      

	    public static String md5(String data) {     

	        return DigestUtils.md5Hex(data);  

	    }  

	      

	    public static String sha1(String data) {   

	        return DigestUtils.shaHex(data);  

	    }  

	      

	    public static String sha256Hex(String data) {  

	        return DigestUtils.sha256Hex(data);  

	    }  

	      

	    public static void main(String[] args) {  

	          

	        String base64 = base64Encode("ricky");  

	        System.out.println("base64 encode="+base64);  

	          

	        byte[] buf = base64Decode(base64);  

	        System.out.println("base64 decode="+new String(buf));  

	          

	        String md5 = md5("ricky");  

	        System.out.println("md5="+md5+"**len="+md5.length());  

	          

	        String sha1 = sha1("test");  

	        System.out.println("sha1="+sha1+"**len="+sha1.length());  

	    }   

}

  

链接 http://commons.apache.org/proper/commons-codec/

你可能感兴趣的:(apache commons)