How to perform BASE64 encoding and decoding in Java

Source: Internet
Author: User

BASE64 encoding is a common character encoding, which is used in many places. JDK provides very convenient BASE64Encoder and BASE64Decoder, which can be used to conveniently complete BASE64-based encoding and decoding. The following are two small functions compiled by myself for BASE64 encoding and decoding:


View sourceprint?
01
Import sun. misc. BASE64Encoder;
02
Import sun. misc. BASE64Decoder;
03
 
04
// Encode s with BASE64
05
PublicstaticString getBASE64 (String s ){
06
If (s = null) returnnull;
07
Return (new sun. misc. BASE64Encoder (). encode (s. getBytes ());
08
}
09
 
10
// Decodes the BASE64 encoded string s.
11
PublicstaticString getFromBASE64 (String s ){
12
If (s = null) returnnull;
13
BASE64Decoder decoder = new BASE64Decoder ();
14
Try {
15
Byte [] B = decoder. decodeBuffer (s );
16
ReturnnewString (B );
17
} Catch (Exception e ){
18
Returnnull;
19
}
20
}
Author: liweigov

Related Article

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.