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

VariantOutput alphabetPaddingLine wrapWhen to use
BasicA-Z a-z 0-9 + /Yes (=)NoDefault for most APIs, configs, data payloads
URL-safeA-Z a-z 0-9 - _OptionalNoURLs, JWT, filenames. + and / break URL parsing.
MIMEA-Z a-z 0-9 + /Yes (=)76 chars + CRLFEmail (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 pass StandardCharsets.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/END markers

Everything on this page runs in your browser — no network call, no data uploaded. Paste freely.