Java實現(xiàn)BASE64編碼和解碼的方法
BASE64和其他相似的編碼算法通常用于轉(zhuǎn)換二進制數(shù)據(jù)為文本數(shù)據(jù),其目的是為了簡化存儲或傳輸。更具體地說,BASE64算法主要用于轉(zhuǎn)換二進制數(shù)據(jù)為ASCII字符串格式。Java語言提供了一個非常好的BASE64算法的實現(xiàn),。本文將簡要地講述怎樣使用BASE64以及它是怎樣工作的。
Base64的作用:主要不是加密,它主要的用途是把一些二進制數(shù)轉(zhuǎn)成普通字符用于網(wǎng)絡傳輸。由于一些二進制字符在傳輸協(xié)議中屬于控制字符,不能直接傳送需要轉(zhuǎn)換一下就可以了。
第一種方式:
通過反射使用java 中不對外公開的類:
/***
* encode by Base64
*/
public static String encodeBase64(byte[]input) throws Exception{
Class clazz=Class.forName("com.sun.org.apache.xerces.internal.impl.dv.util.Base64");
Method mainMethod= clazz.getMethod("encode", byte[].class);
mainMethod.setAccessible(true);
Object retObj=mainMethod.invoke(null, new Object[]{input});
return (String)retObj;
}
/***
* decode by Base64
*/
public static byte[] decodeBase64(String input) throws Exception{
Class clazz=Class.forName("com.sun.org.apache.xerces.internal.impl.dv.util.Base64");
Method mainMethod= clazz.getMethod("decode", String.class);
mainMethod.setAccessible(true);
Object retObj=mainMethod.invoke(null, input);
return (byte[])retObj;
}
第二種方式:
使用commons-codec.jar
/**
* @param bytes
* @return
*/
public static byte[] decode(final byte[] bytes) {
return Base64.decodeBase64(bytes);
}
/**
* 二進制數(shù)據(jù)編碼為BASE64字符串
*
* @param bytes
* @return
* @throws Exception
*/
public static String encode(final byte[] bytes) {
return new String(Base64.encodeBase64(bytes));
}
第三種方式:
/**
* 編碼
* @param bstr
* @return String
*/
public static String encode(byte[] bstr){
return new sun.misc.BASE64Encoder().encode(bstr);
}
/**
* 解碼
* @param str
* @return string
*/
public static byte[] decode(String str){
byte[] bt = null;
try {
sun.misc.BASE64Decoder decoder = new sun.misc.BASE64Decoder();
bt = decoder.decodeBuffer( str );
} catch (IOException e) {
e.printStackTrace();
}
return bt;
}
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
利用Mybatis向PostgreSQL中插入并查詢JSON字段
這篇文章主要介紹了利用Mybatis向PostgreSQL中插入并查詢JSON字段,文章圍繞主題展開詳細的內(nèi)容介紹,具有一定的參考價值,需要的小伙伴可以參考一下2022-07-07
springmvc九大組件之HandlerAdapter詳解
這篇文章主要介紹了springmvc九大組件之HandlerAdapter詳解,RequestMappingHandlerAdapter支持的handler的類型是HandlerMethod,而HandlerMethod是通過解析@RequestMapping注解獲得的,需要的朋友可以參考下2023-11-11
SpringBoot深入探究@Conditional條件裝配的使用
這篇文章主要為大家介紹了SpringBoot底層注解@Conditional的使用分析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-06-06

