Java Base64 encoding encryption and decryption (remember to note garbled problems)

Source: Internet
Author: User
Tags base64

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)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.