Base64 Encoder And Decoder

Encode and decode payloads with Base64's basic, URL-safe, and MIME encoders, including withoutPadding and the 76-character MIME line limit.

JavaSecurity Boundaries

Code

snippet
import java.nio.charset.StandardCharsets;
import java.util.Base64;

public class TokenCodec {

    public static void main(String[] args) {
        String payload = "user:42:2026-11-11";

        // 基本编码:A-Z a-z 0-9 + /
        String basic = Base64.getEncoder().encodeToString(payload.getBytes(StandardCharsets.UTF_8));
        System.out.println("basic: " + basic);
        System.out.println("decoded: " + new String(Base64.getDecoder().decode(basic), StandardCharsets.UTF_8));

        // URL 安全编码:- 和 _ 替代 + 和 /,适合放进链接或文件名
        String urlSafe = Base64.getUrlEncoder().withoutPadding()
                .encodeToString(payload.getBytes(StandardCharsets.UTF_8));
        System.out.println("url-safe: " + urlSafe);

        // MIME 编码:每 76 字符插入换行,长负载会变成多行
        String longPayload = payload.repeat(12);
        String mime = Base64.getMimeEncoder().encodeToString(longPayload.getBytes(StandardCharsets.UTF_8));
        System.out.println("mime lines: " + mime.lines().count());
    }
}

How the snippet works

Base64 Encoder And Decoder keeps everything in the class TokenCodec and the function main.

Applying it

The demo output is labeled (basic:, decoded:, url-safe:), so every line of output can be traced to the operation that made it.

Statements that matter

String mime = Base64.getMimeEncoder().encodeToString(longPayload.getBytes(StandardCharsets.UTF_8));
String basic = Base64.getEncoder().encodeToString(payload.getBytes(StandardCharsets.UTF_8));
String urlSafe = Base64.getUrlEncoder().withoutPadding()
.encodeToString(payload.getBytes(StandardCharsets.UTF_8));

Interactive Tools for This Topic

FAQ

What does Base64 Encoder And Decoder print when run?
No setup needed: run the file and look for labeled lines like `basic:`, `decoded:`, `url-safe:` in the output.