Three ways in which Java implements BASE64 encoding

Source: Internet
Author: User

Absrtact: The three ways of JAVABASE64 encoding are as follows three ways: Commons-codec.jar Java code 1. String base64string= "whuang123"; 2. byte[] result = Base64.

Three ways to encode Javabase64

There are three ways of doing this:

Way One: Commons-codec.jar

Java code

1. String base64string= "whuang123";

2. byte[] result = Base64.encodebase64 (Base64string.getbytes ());

Mode two: Use Sun.misc.BASE64Encoder

Java code

1./**

2. * Encoding

3. *

4. * @parambstr

5. * @returnString

6. */

7. Publicstaticstringencode (BYTE[]BSTR) {

8. Return new Sun.misc.BASE64Encoder (). Encode (BSTR);

9.}

10.

11./**

12. * Decoding

13. *

* @paramstr

* @returnstring

16. */

Publicstaticbyte[]decode (STRINGSTR) {

Byte[]bt=null;

try{.

Sun.misc.base64decoderdecoder=newsun.misc.base64decoder ();

Bt=decoder.decodebuffer (str);

}catch (Ioexceptione) {

E.printstacktrace ();

24.}

25.

RETURNBT;

27.}

Method Three: Use Com.sun.org.apache.xerces.internal.impl.dv.util.Base64

Java code

1./***

2. *encodebybase64

3. */

4. PublicstaticStringencodeBase64 (byte[]input) throwsexception{

5. Classclazz=class

6.. forname ("Com.sun.org.apache.xerces.internal.impl.dv.util.Base64");

7. Methodmainmethod=clazz.getmethod ("Encode", byte[].class);

8. Mainmethod.setaccessible (TRUE);

9. Objectretobj=mainmethod.invoke (Null,newobject[]{input});

Ten. Return (String) retobj;

11.}

12.

13./***

*decodebybase64.

15. */

Publicstaticbyte[]decodebase64 (stringinput) throwsexception{

. Class Clazz=class

forname ("Com.sun.org.apache.xerces.internal.impl.dv.util.Base64");

Methodmainmethod=clazz.getmethod ("Decode", String.class);

Mainmethod.setaccessible (TRUE);

Objectretobj=mainmethod.invoke (Null,input);

Return (byte[]) retobj;

23.}

The results of the operation are as follows:

Recommended use way one.

https://yq.aliyun.com/articles/52597

Three ways in which Java implements BASE64 encoding

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.