This post will discuss Base64 Encoding and Decoding using plain Java, Guava, and Apache Commons.

Base64 is a group of similar binary-to-text encoding schemes representing binary data in an ASCII string format by translating it into a radix-64 representation. Each Base64 digit represents exactly 6-bits of data that means 3 bytes can be represented by 4 6-bit Base64 digits.

 
Base64 encoding schemes are commonly used when there is a need to encode binary data that needs to be stored and transferred over media that are designed to deal with textual data. This is to ensure that the data remain intact without modification during transport. Base64 is commonly used in a number of applications, including email via MIME and storing complex data in XML.

1. Using Java 8

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

The following 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 the 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 containing a lexical representation of xsd:base64Binary and then converting that string back into an array of bytes.

Download Code

Output:

Encoded String: VGVjaGllIERlbGlnaHQ=
Decoded String: Techie Delight

3. Using Guava Library

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

Download Code

Output:

Encoded String: VGVjaGllIERlbGlnaHQ=
Decoded String: Techie Delight

4. Using Apache Commons Library

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

Download Code

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 Code

Output:

Encoded Data: VGVjaGllIERlbGlnaHQ=
Decoded Data: Techie Delight

That’s all about base64 encoding and decoding in Java.

 
Also See:

Base64 Encoding and Decoding in JavaScript