I just announced the new Spring Boot 2 material, coming in REST With Spring:

>> CHECK OUT THE COURSE

1. Overview

In this tutorial, we’re going to explore the various utilities that provide Base64 encoding and decoding functionality in Java.

We’re mainly going to illustrate the new Java 8 APIs as well as the utility APIs coming out of Apache Commons.

Further reading:

Guide to Java URL Encoding/Decoding

The article discusses URL encoding in Java, some pitfalls, and how to avoid them.

Read more

SHA-256 Hashing in Java

A quick and practical guide to SHA-256 hashing in Java

Read more

New Password Storage In Spring Security 5

A quick guide to understanding password encryption in Spring Security 5 and migrating to better encryption algorithms.

Read more

2. Java 8 for Base 64

Java 8 has finally added Base64 capabilities to the standard API, via the java.util.Base64 utility class.

Let’s start by looking a basic encoder process.

2.1. Java 8 Basic Base64

The basic encoder keeps things simple and encodes the input as is – without any line separation.

The output is mapped to a set of characters in A-Za-z0-9+/ character set and the decoder rejects any character outside of this set.

Let’s first encode a simple String:

String originalInput = "test input";
String encodedString = Base64.getEncoder().encodeToString(originalInput.getBytes());

Note how we retrieve the full Encoder API via the simple getEncoder() utility method.

Let’s now decode that String back to the original form:

byte[] decodedBytes = Base64.getDecoder().decode(encodedString);
String decodedString = new String(decodedBytes);

2.2. Java 8 Base64 Encoding without Padding

In Base64 encoding, the length of output encoded String must be a multiple of 3. If it’s not, the output will be padded with additional pad characters (`=`).

On decoding, these extra padding characters will be discarded. To dig deeper into padding in Base64, check out this detailed answer over on StackOverflow.

If you need to skip the padding of the output – perhaps, because the resulting String will never be decoded back – you can simply chose to encode without padding:

String encodedString = 
  Base64.getEncoder().withoutPadding().encodeToString(originalInput.getBytes());

2.3. Java 8 URL Encoding

URL encoding is very similar to the basic encoder we looked at above. It uses the URL and Filename safe Base64 alphabet and does not add any line separation:

String originalUrl = "https://www.google.co.nz/?gfe_rd=cr&ei=dzbFV&gws_rd=ssl#q=java";
String encodedUrl = Base64.getUrlEncoder().encodeToString(originalURL.getBytes());

Decoding happens in much the same way – the getUrlDecoder() utility method returns a java.util.Base64.Decoder that is then used to decode the URL:

byte[] decodedBytes = Base64.getUrlDecoder().decode(encodedUrl);
String decodedUrl = new String(decodedBytes);

2.4. Java 8 MIME Encoding

Let’s start with by generating some basic MIME input to encode:

private static StringBuilder getMimeBuffer() {
    StringBuilder buffer = new StringBuilder();
    for (int count = 0; count < 10; ++count) {
        buffer.append(UUID.randomUUID().toString());
    }
    return buffer;
}

The MIME encoder generates a Base64 encoded output using the basic alphabet but in a MIME friendly format: each line of the output is no longer than 76 characters and ends with a carriage return followed by a linefeed (\r\n):

StringBuilder buffer = getMimeBuffer();
byte[] encodedAsBytes = buffer.toString().getBytes();
String encodedMime = Base64.getMimeEncoder().encodeToString(encodedAsBytes);

The getMimeDecoder() utility method returns a java.util.Base64.Decoder that is then used in the decoding process:

byte[] decodedBytes = Base64.getMimeDecoder().decode(encodedMime);
String decodedMime = new String(decodedBytes);

3. Encoding/Decoding Using Apache Commons Code

First, we need to define the commons-codec dependency in the pom.xml:

<dependency>
    <groupId>commons-codec</groupId>
    <artifactId>commons-codec</artifactId>
    <version>1.10</version>
</dependency>

Note that you can check is newer versions of the library have been released over on Maven central.

The main API is the org.apache.commons.codec.binary.Base64 class – which can be parameterized with various constructors:

  • Base64(boolean urlSafe) – creates the Base64 API by controlling the URL-safe mode – on or off
  • Base64(int lineLength) – creates the Base64 API in an URL unsafe mode and controlling the length of the line (default is 76)
  • Base64(int lineLength, byte[] lineSeparator) – creates the Base64 API by accepting an extra line separator, which, by default is CRLF (“\r\n”)

On the Base64 API is created, both encoding and decoding are quite simple:

String originalInput = "test input";
Base64 base64 = new Base64();
String encodedString = new String(base64.encode(originalInput.getBytes()));

The decode() method of Base64 class returns the decoded string:

String decodedString = new String(base64.decode(encodedString.getBytes()));

Another simple option is using the static API of Base64 instead of creating an instance:

String originalInput = "test input";
String encodedString = new String(Base64.encodeBase64(originalInput.getBytes()));
String decodedString = new String(Base64.decodeBase64(encodedString.getBytes()));

4. Converting a String to a byte Array

Sometimes, we need to convert a String to a byte[]. The simplest way to do that is using String getBytes() method:

String originalInput = "test input";
byte[] result = originalInput.getBytes();

assertEquals(originalInput.length(), result.length);

It’s better to provide encoding as well and not depend on default encoding as it’s system dependent:

String originalInput = "test input";
byte[] result = originalInput.getBytes(StandardCharsets.UTF_16);

assertTrue(originalInput.length() < result.length);

If our String is Base64 encoded, we can use the Base64 decoder:

String originalInput = "dGVzdCBpbnB1dA==";
byte[] result = Base64.getDecoder().decode(originalInput);

assertEquals("test input", new String(result));

We can also use DatatypeConverter parseBase64Binary() method:

String originalInput = "dGVzdCBpbnB1dA==";
byte[] result = DatatypeConverter.parseBase64Binary(originalInput);

assertEquals("test input", new String(result));

Finally, we can convert a hexadecimal String to a byte[] using DatatypeConverter method:

String originalInput = "7465737420696E707574";
byte[] result = DatatypeConverter.parseHexBinary(originalInput);

assertEquals("test input", new String(result));

5. Conclusion

This article explains the basics of how to do Base64 encoding and decoding in Java, using the new APIs introduced in Java 8 as well as Apache Commons.

Finally, there are a few other APIs that are worth mentioning for providing similar functionality – for example java.xml.bind.DataTypeConverter with printHexBinary and parseBase64Binary.

Code snippets can be found over on GitHub.

I just announced the new Spring Boot 2 material, coming in REST With Spring:

>> CHECK OUT THE LESSONS

newest oldest most voted
Notify of
Erik Forkalsrud
Guest
Erik Forkalsrud

java.xml.bind.DataTypeConverter deserves mention, specifically the methods:
– public static String printHexBinary( byte[] val );

– public static byte[] parseBase64Binary( String lexicalXSDBase64Binary );

Eugen Paraschiv
Guest

I didn’t know about that one, thanks for the suggestion. I’m mentioning it in the article. Cheers,
Eugen.