Base64 API in 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
| Variant | Factory methods | Alphabet and format |
|---|---|---|
| Basic | getEncoder(), getDecoder() | A-Z a-z 0-9 + /, no line breaks (RFC 4648) |
| URL and file-name safe | getUrlEncoder(), getUrlDecoder() | uses - and _ instead of + and / |
| MIME | getMimeEncoder(), 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.
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());
}
}
}
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
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);
}
}
Authorization: Basic YXBpLXVzZXI6czNjcmV0IQ== MIME lines: 2, first line length 76 Decoded back: api-user:s3cret!
4. How Base64 Encoding Works
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 betweenStringand bytes. - Encoded data is about one third larger than the input.
- Use
wrap(OutputStream)andwrap(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.Base64was 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
Frequently Asked Questions (FAQ)
Q1. Is Base64 encryption?
No. Base64 is a reversible encoding that anyone can decode. It only makes binary data safe to send as text.
Q2. What is the difference between getEncoder and getUrlEncoder?
getEncoder uses + and /; getUrlEncoder uses - and _, which are safe in URLs and file names.
Q3. Why does Base64 output end with = signs?
The output is built in groups of four characters. When the input length is not a multiple of three bytes, = pads the final group. withoutPadding() removes it.
Q4. What replaced sun.misc.BASE64Encoder?
java.util.Base64, the public and supported API added in Java 8.