Base64 Encoding and Decoding in Java

In this post, we’ll discuss Base64 Encoding and Decoding using plain Java, Guava and Apache Commons.


 

1. Java 8

Java 8 finally provided support for Base64 Encoding and Decoding capabilities, by providing Base64, Base64.Encoder and Base64.Decoder utility class. Base64 class consists of static methods for obtaining instances of encoders (Base64.Encoder) and decoders (Base64.Decoder) for the Base64 encoding scheme.

Below program uses Base64.Encoder.encodeToString() method for encoding the specified byte array into a Base64 encoded String and Base64.Decoder.decode() method for decoding back the Base64 encoded String into a newly-allocated byte array.

 

Download   Run Code

Output:

Encoded Data: VGVjaGllIERlbGlnaHQ=
Decoded Data: Techie Delight

 
Instead of writing the resulting bytes to a String, we can also use a byte array, by using Base64.Encoder.encode() method as shown below:

 

Download   Run Code

Output:

Encoded Data: VGVjaGllIERlbGlnaHQ=
Decoded Data: Techie Delight

 

2. Using javax.xml.bind.DatatypeConverter

The DatatypeConverter class from javax.xml.bind package has two methods – printBase64Binary() and parseBase64Binary(), which can be used to convert an array of bytes into a string string containing a lexical representation of xsd:base64Binary and then converting that string back into an array of bytes.

 

Download   Run Code

Output:

Encoded String: VGVjaGllIERlbGlnaHQ=
Decoded String: Techie Delight

 

3. Using Guava

One can also use Guava’s BaseEncoding class for reversibly translating between the byte sequence and printable ASCII strings using the Base64 encoding.

 

Download   Run Code

Output:

Encoded String: VGVjaGllIERlbGlnaHQ=
Decoded String: Techie Delight

 

4. Using Apache Commons Package

Apache Commons also provides implementation of Base64 algorithm. Below code creates a Base64 codec which is then used for decoding and encoding the specified data.

 

Download

Output:

Encoded Data: VGVjaGllIERlbGlnaHQ=
Decoded Data: Techie Delight

 

We can also use static methods provided by Apache Commons’s Base64 class – encodeBase64() and decodeBase64().

 

Download

Output:

Encoded Data: VGVjaGllIERlbGlnaHQ=
Decoded Data: Techie Delight

 

 
Thanks for reading.

Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 





Leave a Reply

Notify of
avatar
wpDiscuz