This post will discuss Base64 encoding and decoding in Java.

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

 
The implementation of the Base64 class supports the following types of encoding:

1. Basic Encoding

The basic encoder does not add any line feed (line separator) character. The decoder rejects data that contains characters outside the base64 alphabet set, which is A-Za-z0-9+/.

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.

We can also use the Base64.Encoder.encode() method for writing the resulting bytes to a byte array instead of a string.

Download  Run Code

Output:

Encoded Data: VGVjaGllIERlbGlnaHQ=
Decoded Data: Techie Delight

 
The basic encoding adds padding character at the end of the encoded byte data by default if the length of the encoded string is not a multiple of 3. These padding characters are then discarded on decoding. To get an encoder without padding, we can call the withoutPadding() method:

2. URL and Filename safe encoding

To encode an URL, we can’t use a basic encoding. We should use the “URL and Filename safe Base64 Alphabet” for encoding and decoding. The encoder does not add any line feed (line separator) character, and the decoder rejects data that contains characters outside the base64 alphabet.

The following example encodes a URL using the URL encoder:

Download  Run Code

Output:

Using URL Alphabet: aHR0cDovL3d3dy50ZWNoaWVkZWxpZ2h0LmNvbS8_dj0x
https://techiedelight.com/?v=1

3. MIME Encoding

The MIME Encoding uses the “The Base64 Alphabet” for encoding and decoding operation, but the encoded output is represented in lines of no more than 76 characters each and uses a carriage return, followed by a linefeed '\r\n' as the line separator.

The following example encodes a large block of text (having more than 76 characters) using the MIME encoder:

Download  Run Code

Output (may vary):

e2317f97-47d0-4799-b383-2a89070d5c1ef57d1659-3153-47d6-88a1-be3d5cca8cf526afb83c-c0db-4ef6-bd41-edc7ca4a691db744a484-f6fd-4f80-a7e4-4d8d3d7d3153309b3b8c-d4b3-4027-821b-85450c735616

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

 
Reference: Base64 (Java Platform SE 8)