BASE64 encoding is a commonly used character encoding and is used in many places. The JDK provides easy-to-use Base64encoder and Base64decoder, which makes it easy to complete BASE64-based encoding and decoding.
Remember: The following two encodings must be consistent.
Gets the byte stream when res = new Sun.misc.BASE64Encoder (). Encode (S.getbytes ("GBK"));
BYTE stream when converting a string: Return new string (b,"GBK");
The complete code is as follows:
PackageCom.util;Importjava.io.UnsupportedEncodingException;ImportSun.misc.BASE64Decoder;/*** Base64 encoding, decoding util * *@authorLifq * @date 2015-3-4 a.m. 09:23:33*/ Public classBase64util {/*** BASE64 encoding for S * *@returnString *@authorLifq * @date 2015-3-4 a.m. 09:24:02*/ Public Staticstring Encode (string s) {if(s = =NULL) return NULL; String Res= ""; Try{res=NewSun.misc.BASE64Encoder (). Encode (S.getbytes ("GBK")); } Catch(unsupportedencodingexception e) {//TODO auto-generated Catch blockE.printstacktrace (); } returnRes; } /*** Decode the BASE64 encoded string s * *@returnString *@authorLifq * @date 2015-3-4 a.m. 09:24:26*/ Public Staticstring decode (string s) {if(s = =NULL) return NULL; Base64decoder Decoder=NewBase64decoder (); Try { byte[] B =Decoder.decodebuffer (s); return NewString (b, "GBK"); } Catch(Exception e) {return NULL; } } /** * * @returnvoid *@authorLifq * @date 2015-3-4 a.m. 09:23:17*/ Public Static voidMain (string[] args) {System.out.println (Base64util.encode (haha)); System.out.println (Base64util.decode ("uf65/g==")); }}
Java Base64 encoding encryption and decryption (remember to note garbled problems)