Java Base64 Encoder & Decoder
Matching Java code
// Loading…
What is Base64?
Base64 is an encoding that represents binary data as ASCII text, using 64 printable characters. It's used everywhere a system expects text but you need to carry bytes: email attachments (MIME), data: URIs in HTML, JWT tokens, OAuth exchanges, HTTP Basic Auth headers.
Three characters are different across the three standard variants:
The three Base64 variants in java.util.Base64
| Variant | Output alphabet | Padding | Line wrap | When to use |
|---|---|---|---|---|
| Basic | A-Z a-z 0-9 + / | Yes (=) | No | Default for most APIs, configs, data payloads |
| URL-safe | A-Z a-z 0-9 - _ | Optional | No | URLs, JWT, filenames. + and / break URL parsing. |
| MIME | A-Z a-z 0-9 + / | Yes (=) | 76 chars + CRLF | Email (RFC 2045), PEM certificates |
Encoding in Java
import java.util.Base64;
import java.nio.charset.StandardCharsets;
byte[] raw = "Hello, world!".getBytes(StandardCharsets.UTF_8);
String basic = Base64.getEncoder().encodeToString(raw);
String urlStr = Base64.getUrlEncoder().withoutPadding().encodeToString(raw);
String mime = Base64.getMimeEncoder().encodeToString(raw);
Note withoutPadding() — JWT and most URL-safe uses strip trailing = signs. getMimeEncoder(lineLength, lineSeparator) lets you customize the wrap.
Decoding in Java
byte[] decoded = Base64.getDecoder().decode(basic);
String text = new String(decoded, StandardCharsets.UTF_8);
// URL-safe decode
byte[] fromUrl = Base64.getUrlDecoder().decode(urlStr);
// MIME decode — tolerates newlines and surrounding whitespace
byte[] fromMime = Base64.getMimeDecoder().decode(mime);
Common mistakes
- Mixing variants: decoding a URL-safe string with
getDecoder()fails — the-and_characters aren't in the Basic alphabet. - Platform encoding:
"text".getBytes()without a charset depends on the platform locale. Always passStandardCharsets.UTF_8. - Forgetting padding: Basic decoding requires
=padding; URL decoding tolerates its absence. - Leading/trailing whitespace: only the MIME decoder ignores whitespace. Trim before passing to the Basic decoder.
Base64 in the real world
- HTTP Basic Auth:
Authorization: Basic base64(user:pass) - JWT: three URL-safe Base64 sections separated by dots
- Data URIs:
data:image/png;base64,... - PEM certificates: MIME variant, wrapped in
BEGIN/ENDmarkers
Everything on this page runs in your browser — no network call, no data uploaded. Paste freely.
Related tools and guides
- Java String Escape — escape Base64 output for a Java literal
- Java Online Compiler — test Base64 code instantly
- JSON to Java POJO — generate classes from JSON payloads
- XML to Java POJO — same for XML
- Convert String to int in Java — guide to numeric parsing