Developer Documentation
Java
Updated September 19, 2026

Base64 Encoding and Decoding in Java

Encode and decode Base64 safely, including UTF-8 text and binary data in Java.

Base64 converts binary data to printable ASCII text. It is useful for transport and embedding, but it is an encoding format, not encryption.

Quick Start#

The following example uses the standard Java API or a widely used package for this task.

Quick start#

Java
1import java.nio.charset.StandardCharsets;2import java.util.Base64;34String text = "Hello ToolPorta";5String encoded = Base64.getEncoder()6    .encodeToString(text.getBytes(StandardCharsets.UTF_8));7String decoded = new String(8    Base64.getDecoder().decode(encoded),9    StandardCharsets.UTF_810);1112System.out.println(encoded);13System.out.println(decoded);

Common Operations#

This second pattern covers a common production operation or a safer way to handle real input.

URL-safe Base64#

Java
1byte[] bytes = "token bytes".getBytes(StandardCharsets.UTF_8);2String token = Base64.getUrlEncoder().withoutPadding().encodeToString(bytes);3byte[] restored = Base64.getUrlDecoder().decode(token);

Important Notes#

Use the URL-safe encoder for URL or cookie tokens; it replaces + and / with URL-safe characters.

Best Practices#

  1. Treat external input as untrusted and handle parse/validation errors explicitly.
  2. Keep encoding, units, formats, and library-specific mapping rules explicit at system boundaries.
  3. Add test vectors that cover empty input, Unicode text, malformed input, and representative production data.

References#

Implement Base64 in other languages: