Base64 Encoding and Decoding in Java

Naveen AnamaneniUpdated · 4 min read

Base64 is a way of turning any bytes (text, images, files) into plain text made of only 64 safe characters: A to Z, a to z, 0 to 9, + and / (plus = for padding). It is used when binary data must travel through systems that only handle text, such as email, JSON, URLs or HTTP headers. Java provides the java.util.Base64 class, added in Java 8, to encode and decode Base64. In this lesson, you will learn its three kinds of encoders and how to use them.

How Base64 Works

Base64 takes the input 3 bytes (24 bits) at a time and splits them into four 6-bit groups. Each 6-bit number, from 0 to 63, is replaced by one character from the Base64 alphabet. So every 3 bytes become 4 characters, which makes the output about 33% larger. If the input length isn't a multiple of 3, = signs pad the end.

Encoders and Decoders

MethodDescription
Base64.getEncoder() / getDecoder()It is used for the basic alphabet, with + and /.
Base64.getUrlEncoder() / getUrlDecoder()It uses - and _ instead of + and /, safe in URLs and file names.
Base64.getMimeEncoder() / getMimeDecoder()It splits output into lines of 76 characters, for email.
encoder.withoutPadding()It leaves out the trailing = signs.
encodeToString(byte[])It encodes bytes into a Base64 string.
decode(String)It decodes a Base64 string into bytes.

Example: Encoding and Decoding Text

Let's see an example that encodes a name and decodes it back.

Base64Demo.java▶ Try it
import java.nio.charset.StandardCharsets;
import java.util.Base64;
 
public class Base64Demo {
    public static void main(String[] args) {
        String original = "Navika Anamaneni";
        byte[] bytes = original.getBytes(StandardCharsets.UTF_8);
 
        String encoded = Base64.getEncoder().encodeToString(bytes);
        System.out.println("Encoded: " + encoded);
 
        byte[] decodedBytes = Base64.getDecoder().decode(encoded);
        String decoded = new String(decodedBytes, StandardCharsets.UTF_8);
        System.out.println("Decoded: " + decoded);
 
        System.out.println(original.length() + " characters became "
            + encoded.length());
    }
}
Output
Encoded: TmF2aWthIEFuYW1hbmVuaQ==
Decoded: Navika Anamaneni
16 characters became 24

Explanation: The string is first turned into bytes with UTF-8. encodeToString produces Base64 text; 16 bytes aren't a multiple of 3, so two = signs pad the end. decode reverses the process, and new String(..., UTF_8) turns the bytes back into text.

Example: URL-Safe Encoding

UrlSafe.java▶ Try it
import java.util.Base64;
 
public class UrlSafe {
    public static void main(String[] args) {
        byte[] data = {(byte) 0xFB, (byte) 0xFF, (byte) 0xBF};
 
        System.out.println("Basic:   "
            + Base64.getEncoder().encodeToString(data));
        System.out.println("URL:     "
            + Base64.getUrlEncoder().encodeToString(data));
        System.out.println("No pad:  " + Base64.getUrlEncoder().withoutPadding()
            .encodeToString("Hi".getBytes()));
    }
}
Output
Basic:   +/+/
URL:     -_-_
No pad:  SGk

Explanation: These bytes produce + and / in basic Base64, which have special meanings in URLs. The URL encoder uses - and _ instead. withoutPadding() drops the = signs, which are often unwanted in URLs and tokens.

Common Mistakes

Decoding with the wrong decoder. A URL-safe string with - or _ fails in the basic decoder with IllegalArgumentException.

Forgetting the character set. Always use StandardCharsets.UTF_8 with getBytes and new String.

Treating Base64 as security. It only changes the format.

Practice

  1. Easy: Encode your favorite quote with the basic encoder and decode it back.
  2. Harder: Read a small image file with Files.readAllBytes, encode it with Base64, and build a data:image/png;base64,... string that a browser could display.

Quick check: Base64

4 questions
1Which class handles Base64 in Java?
2How many Base64 characters do 3 bytes become?
3Which encoder is safe for URLs?
4Is Base64 a form of encryption?

Key Takeaways

Was this tutorial helpful?

Lesson 327 of 482