maven commons-codec-1.9.jar是jdk中一款用于編碼運算的開源工具包,調用簡單方便,支持MD5、Base64、哈希等加密方式,還可以解碼,需要的程序猿們趕緊來IT貓撲下載吧!
commons-codec.jar介紹
commons-codec是Apache開源組織提供的用于摘要運算、編碼的包。
commons-codec.jar內容
Commons codec,是項目中用來處理常用的編碼方法的工具類包,例如DES、SHA1、MD5、Base64,URL,Soundx等等。
不僅是編碼,也可用于解碼。
在該包中主要分為四類加密:BinaryEncoders、DigestEncoders、LanguageEncoders、NetworkEncoders。
commons-codec.jar運算示例
1、Base64編解碼
private static String encodeTest(String str){
Base64 base64 = new Base64();
try {
str = base64.encodeToString(str.getBytes(“UTF-8”));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
System.out.println(“Base64 編碼后:”+str);
return str;
}
private static void decodeTest(String str){
Base64 base64 = new Base64();
//str = Arrays.toString(Base64.decodeBase64(str));
str = new String(Base64.decodeBase64(str));
System.out.println(“Base64 解碼后:”+str);
}
2、Hex編解碼
private static String encodeHexTest(String str){
try {
str = Hex.encodeHexString(str.getBytes(“UTF-8”));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
System.out.println(“Hex 編碼后:”+str);
return str;
}
private static String decodeHexTest(String str){
Hex hex = new Hex();
try {
str = new String((byte[])hex.decode(str));
} catch (DecoderException e) {
e.printStackTrace();
}
System.out.println(“Hex 編碼后:”+str);
return str;
}
3、MD5加密
private static String MD5Test(String str){
try {
System.out.println(“MD5 編碼后:”+newString(DigestUtils.md5Hex(str.getBytes(“UTF-8”))));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return str;
}
4、SHA編碼
private static String ShaTest(String str){
try {
System.out.println(“SHA 編碼后:”+newString(DigestUtils.shaHex(str.getBytes(“UTF-8”))));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return str;
}
5、Metaphone和Soundex
這個例子來源于網上,
Metaphone 建立出相同的key給發音相似的單字, 比 Soundex 還要準確, 但是 Metaphone 沒有固定長度, Soundex 則是固定第一個英文字加上3個數字. 這通常是用在類似音比對, 也可以用在 MP3 的軟件開發.
import org.apache.commons.codec.language.*;
import org.apache.commons.codec.*;
public class LanguageTest {
public static void main(String args[]) {
Metaphone metaphone = new Metaphone();
RefinedSoundex refinedSoundex = new RefinedSoundex();
Soundex soundex = new Soundex();
for (int i=0; i<2; i++ ) {
String str=(i==0)?”resume”:”resin”;
String mString = null;
String rString = null;
String sString = null;
try {
mString = metaphone.encode(str);
rString = refinedSoundex.encode(str);
sString = soundex.encode(str);
} catch (Exception ex) {
;
}
System.out.println(“original:”+str);
System.out.println(“Metaphone:”+mString);
System.out.println(“RefinedSoundex:”+rString);
System.out.println(“Soundex:”+sString +”\\n”);
}
}
}





