Library contents

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

  1. Start with "cat" encoded as UTF-8
  2. Do this Encode its three bytes as Base64
  3. Result "Y2F0"
Base64 represents these three bytes with four printable characters. Decoding restores cat.

Syntax

Java 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.java

Encode 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.

From the programbyte[] bytes = "A?".getBytes(StandardCharsets.UTF_8)
First output lineQT8
Main.java
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));
    }
}
Output
QT8
A?

The source is bytes. Explicitly using UTF-8 ensures the same text round-trips on systems with different defaults. Encoding is reversible.

Advertisements

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.

GivenBOX
Worked resultQk9Y

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.

GivenART
Worked resultQVJU

What to watch for

Base64 is reversible. It provides neither secrecy nor proof that a value came from a trusted sender.

Documentation for Base64 encoding and decoding