Java Base64 Encode and Decode Example

Java 8 introduced ‘java.util.Base64‘ utility class that provides built-in support for performing base64 encoding and decoding operations as specified in RFC 4648 and RFC 2045. Let us explore Base64 encode and decode processes with various usecases with examples.

String originalInput = "hello world";
String encodedString = Base64.getEncoder().encodeToString(originalInput.getBytes());  // aGVsbG8gd29ybGQ=

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

1. What is Base64?

Base64 is a binary-to-text encoding scheme that converts binary data into an ASCII string format. The encoded consists of printable characters. This helps in safely transmitting the data over text-based protocols, such as HTTP, or storing in text-based formats, such as XML or JSON.

For example, when we have some binary data that we want to send across a network, we generally don’t do it by just converting data into a stream of bits in a raw format. Why? Because some protocols (such as HTTP, SMTP, and JSON) are designed for streaming text only. These associated protocols may interpret our binary data as control characters which they are not. Generally, base64 encoding is done for binary data in email messages and "basic" HTTP authentication.

1.1. Base64 Charset

Base-64 encoding converts our binary data into a string containing characters out of 64 printable characters. These 64 printable characters are:

  • 26 uppercase letters [A…Z]
  • 26 lowercase letters [a…z]
  • 10 digits [0…9]
  • 2 symbols [Read more]

The base-64 encoded string containing the above characters is safe to be transferred over the network supporting text data without fear of losing data in a confusion of control characters. At the receiving end, the Base64-encoded string can be decoded back into its original binary form. This process preserves the data integrity and ensures compatibility with text-based protocols.

1.2. Base64 without Padding

The Base64 encoded strings are always of the length that is multiple of 4. To achieve this, the encoder may add one or two equal (=) signs at the end of the encoded string if needed, as seen in the quick reference example.

However, in some cases, we might not want these padding characters in the encoded string. To encode without padding, we can use the withoutPadding() method provided by the Base64 encoder.

Let us rerun the previous example without padding. This time, the encoded string does not have the padded character “=”.

String originalInput = "hello world";
String encodedString = Base64.getEncoder()
    .withoutPadding()
    .encodeToString(originalInput.getBytes());  //aGVsbG8gd29ybGQ

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

2. Base64 Support before Java 8

For many years, Java has provided support for base-64 via a non-public class (therefore non-usable) java.util.prefs.Base64 and an undocumented class sun.misc.BASE64Encoder. This class has also very limited information in the public domain.

3. Base64 Support since Java 8

Java 8 has added java.util.Base64 for Base-64 encoding and decoding purposes. It has two nested classes to work with the encoding and decoding process.

  • Base64.Encoder
  • Base64.Decoder

The Base64.Encoder class provides the following methods to support the encoding process:

MethodPurpose
byte[] encode(byte[] src)Encodes all bytes from the specified byte array into a newly-allocated byte array
ByteBuffer encode(ByteBuffer buffer)Encodes all remaining bytes from the specified byte buffer into a newly-allocated ByteBuffer
String encodeToString(byte[] src)Encodes the specified byte array into a String
OutputStream wrap(OutputStream os)Wraps an output stream for encoding byte data

The Base64.Decoder class provides the following methods to support the decoding process:

MethodPurpose
byte[] decode(byte[] src)Decodes all bytes from the specified byte array into a newly-allocated byte array
ByteBuffer decode(ByteBuffer buffer)Decodes all bytes from the specified byte buffer into a newly-allocated ByteBuffer
byte[] decode(String)Decodes the specified String into a new byte array.
InputStream wrap(InputStream in)Wraps an input stream for decoding byte data

3.1. Base64 Encode Example

This is as simple as getting an instance of the Base64.Encoder and input the string as bytes to encode it.

Base64.Encoder encoder = Base64.getEncoder();
String normalString = "username:password";

String encodedString = encoder.encodeToString(
        normalString.getBytes(StandardCharsets.UTF_8) );
dXNlcm5hbWU6cGFzc3dvcmQ=

3.2. Base64 Decode Example

This is also very simple. Just get the instance of Base64.Decoder and use it to decode the base64 encoded string.

String encodedString = "dXNlcm5hbWU6cGFzc3dvcmQ=";
Base64.Decoder decoder = Base64.getDecoder();

byte[] decodedByteArray = decoder.decode(encodedString);

//Verify the decoded string
System.out.println(new String(decodedByteArray));
username:password

4. Base64 Encoded Streams

If you don’t want to directly work with data and rather prefer to work with streams, you can wrap the output stream such that all data written to this output stream will be automatically base 64 encoded.

Path originalPath = Paths.get("c:/temp", "mail.txt");
Path targetPath = Paths.get("c:/temp", "encodedMail.txt");

Base64.Encoder mimeEncoder = Base64.getMimeEncoder();

try(OutputStream output = Files.newOutputStream(targetPath))
{
    //Copy the encoded file content to target file
    Files.copy(originalPath, mimeEncoder.wrap(output));

    //Or simply use the encoded output stream
    OutputStream encodedStrem = mimeEncoder.wrap(output);
}

5. Base64 Encoded URLs

The Base64.getUrlEncoder() Uses the “URL and Filename safe Base64 Alphabet” as specified in Table 2 of RFC 4648 for encoding and decoding. The encoder does not add any line feed (line separator) character.

String originalUrl = "https://howtodoinjava.com/?search=java&data";
String encodedUrl = Base64.getUrlEncoder()
	.encodeToString(originalURL.getBytes());

The use of the decoder is almost the same. The decoder rejects data that contains characters outside the base64 alphabet.

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

6. Conclusion

This Java tutorial discussed the base64 encode and decode examples using the Java 8 java.util.Base64 class and its inner classes.

That’s all for this topic. This is already simple enough.

Happy Learning !!

Comments

Subscribe
Notify of
guest
4 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Our Blogs

REST API Tutorial

Dark Mode

Dark Mode