Java Base64 encoding and decoding
Base64 turns bytes into printable text. Java provides a URL-safe alphabet for values that travel inside links.
A simple example
Base64 encoding and decoding
- Start with "cat" encoded as UTF-8
- Do this Encode its three bytes as Base64
- Result "Y2F0"
Syntax
Base64.getUrlEncoder().withoutPadding().encodeToString(bytes)
Run these examples in Java
Save one example at a time as Main.java. Use JDK 21.
java Main.javaEncode a compact URL-safe identifier
A system can carry a short payload only in a text field. Encode the original bytes into the alphabet the receiving field accepts, and distinguish that transport encoding from the underlying data.
import java.util.Base64;
import java.nio.charset.StandardCharsets;
class Main {
public static void main(String[] args) throws Exception {
byte[] bytes = "A?".getBytes(StandardCharsets.UTF_8);
String token = Base64.getUrlEncoder().withoutPadding().encodeToString(bytes);
System.out.println(token);
System.out.println(new String(Base64.getUrlDecoder().decode(token), StandardCharsets.UTF_8));
}
}
QT8 A?
The source is bytes. Explicitly using UTF-8 ensures the same text round-trips on systems with different defaults. Encoding is reversible.
Encode a parcel marker
A parcel terminal needs a text version of its three marker bytes. Encode the supplied ASCII bytes and read the four-character Base64 group. These inputs occupy a complete three-byte block.
Store an exhibit tag
A catalog stores three literal tag bytes in a Base64 field. Encode the supplied ASCII bytes and read the four-character Base64 group. These inputs occupy a complete three-byte block.
What to watch for
Base64 is reversible. It provides neither secrecy nor proof that a value came from a trusted sender.