BASE64和其他相似的編碼算法通常用于轉(zhuǎn)換二進(jìn)制數(shù)據(jù)為文本數(shù)據(jù),其目的是為了簡(jiǎn)化存儲(chǔ)或傳輸。更具體地說(shuō),BASE64算法主要用于轉(zhuǎn)換二進(jìn)制數(shù)據(jù)為ASCII字符串格式。Java語(yǔ)言提供了一個(gè)非常好的BASE64算法的實(shí)現(xiàn),。本文將簡(jiǎn)要地講述怎樣使用BASE64以及它是怎樣工作的。
Base64的作用:主要不是加密,它主要的用途是把一些二進(jìn)制數(shù)轉(zhuǎn)成普通字符用于網(wǎng)絡(luò)傳輸。由于一些二進(jìn)制字符在傳輸協(xié)議中屬于控制字符,不能直接傳送需要轉(zhuǎn)換一下就可以了。
第一種方式:
通過(guò)反射使用java 中不對(duì)外公開(kāi)的類(lèi):
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
/*** * 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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
/** * @param bytes * @return */ public static byte [] decode( final byte [] bytes) { return Base64.decodeBase64(bytes); } /** * 二進(jìn)制數(shù)據(jù)編碼為BASE64字符串 * * @param bytes * @return * @throws Exception */ public static String encode( final byte [] bytes) { return new String(Base64.encodeBase64(bytes)); } |
第三種方式:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
|
/** * 編碼 * @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; } |
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持服務(wù)器之家。