00:00

Base64 API in Java 8

Last updated: · Standard (Java 8)

java.util.Base64, added in Java 8 (JEP 135), is the standard way to convert binary data to text and back. It provides three encoder types, basic, URL-safe and MIME, each with a matching decoder.

This tutorial explains when to use each variant, how padding works, and a common real-world use: the HTTP Basic authentication header.

1. Why Was the Base64 API Added?

Base64 is needed whenever binary data must travel through a text-only channel, such as JSON, email or URLs. Before Java 8 there was no public API: developers used the internal sun.misc.BASE64Encoder, which was unsupported, or added a third-party library. Java 8 made a fast, standard implementation part of java.util.

2. Encoders and Decoders

VariantFactory methodsAlphabet and format
BasicgetEncoder(), getDecoder()A-Z a-z 0-9 + /, no line breaks (RFC 4648)
URL and file-name safegetUrlEncoder(), getUrlDecoder()uses - and _ instead of + and /
MIMEgetMimeEncoder(), getMimeDecoder()lines of at most 76 characters, separated by \r\n

Every encoder adds = padding by default; call withoutPadding() to remove it, for example in URLs or JWT-style tokens.

3. Practical Examples

Example 1: Basic vs URL-safe encoding

The sample text was chosen so that its Base64 form contains + and /, which shows the difference between the two alphabets.

Base64Variants.java
import java.nio.charset.StandardCharsets;
import java.util.Base64;

public class Base64Variants {
    public static void main(String[] args) {
        byte[] data = "Rs 500 off?? ~~~".getBytes(StandardCharsets.UTF_8);

        // Basic encoder: standard alphabet (A-Z a-z 0-9 + /) with = padding
        String basic = Base64.getEncoder().encodeToString(data);
        System.out.println("Basic   : " + basic);

        // URL and file-name safe: uses - and _ instead of + and /
        String urlSafe = Base64.getUrlEncoder().encodeToString(data);
        System.out.println("URL     : " + urlSafe);
        System.out.println("No pad  : " + Base64.getUrlEncoder().withoutPadding().encodeToString(data));

        // Decoding returns the original bytes
        String back = new String(Base64.getDecoder().decode(basic), StandardCharsets.UTF_8);
        System.out.println("Decoded : " + back);

        // The basic decoder rejects URL-safe characters such as - and _
        try {
            Base64.getDecoder().decode(urlSafe);
        } catch (IllegalArgumentException e) {
            System.out.println("Invalid input rejected: " + e.getMessage());
        }
    }
}
Output
Basic   : UnMgNTAwIG9mZj8/IH5+fg==
URL     : UnMgNTAwIG9mZj8_IH5-fg==
No pad  : UnMgNTAwIG9mZj8_IH5-fg
Decoded : Rs 500 off?? ~~~
Invalid input rejected: Illegal base64 character 5f

The basic decoder rejects the URL-safe output because _ (hex 5f) is not in its alphabet. Always decode with the decoder that matches the encoder.

Example 2: Basic authentication and MIME

MimeAndBasicAuth.java
import java.nio.charset.StandardCharsets;
import java.util.Base64;

public class MimeAndBasicAuth {
    public static void main(String[] args) {
        // HTTP Basic authentication header value: Base64 of "user:password"
        String credentials = "api-user:s3cret!";
        String header = "Basic " + Base64.getEncoder()
                .encodeToString(credentials.getBytes(StandardCharsets.UTF_8));
        System.out.println("Authorization: " + header);

        // MIME encoder: lines of at most 76 characters separated by \r\n
        byte[] attachment = new byte[90];
        for (int i = 0; i < attachment.length; i++) {
            attachment[i] = (byte) i;
        }
        String mime = Base64.getMimeEncoder().encodeToString(attachment);
        String[] lines = mime.split("\r\n");
        System.out.println("MIME lines: " + lines.length + ", first line length " + lines[0].length());

        // Base64 is encoding, not encryption: anyone can decode it
        String decoded = new String(Base64.getDecoder().decode(header.substring(6)), StandardCharsets.UTF_8);
        System.out.println("Decoded back: " + decoded);
    }
}
Output
Authorization: Basic YXBpLXVzZXI6czNjcmV0IQ==
MIME lines: 2, first line length 76
Decoded back: api-user:s3cret!

4. How Base64 Encoding Works

Three bytes become four characters Base64 takes three input bytes, which are 24 bits, splits them into four 6-bit groups, and maps each group to one of 64 characters. 3 bytes 24 bits of data split 4 groups of 6 bits lookup 64-character alphabet 4 characters about 33% larger
Figure 1: Every 3 bytes become 4 characters; padding with = fills the last group when the input length is not a multiple of 3.

5. Important Points and Best Practices

  • Base64 is an encoding, not encryption: anyone can decode it. Never use it to protect passwords.
  • Always choose an explicit charset, such as StandardCharsets.UTF_8, when converting between String and bytes.
  • Encoded data is about one third larger than the input.
  • Use wrap(OutputStream) and wrap(InputStream) to encode large files without loading them into memory.
  • Encoder and decoder instances are thread-safe and can be shared.

6. Summary

  • java.util.Base64 was added in Java 8 by JEP 135.
  • Use the basic, URL-safe or MIME variant depending on where the text will go.
  • Decode with the matching decoder; mixing alphabets causes IllegalArgumentException.
  • Base64 makes binary data text-safe but provides no security.

Related Tutorials

7. References