CKTIS / Java
Base64 — encoding and decoding bytes
The java.util.Base64 class represents bytes as Base64 text and recovers them by decoding. Learn the Basic variant, explicit UTF-8 conversion, and handling of malformed input.
Version: Java SE 21; repository runtime, production runtime not attested
Syntax
String encoded = Base64.getEncoder().encodeToString(bytes);
byte[] decoded = Base64.getDecoder().decode(encoded);Base64 in java.util provides encoders and decoders. Base64 is a reversible textual representation of bytes, not encryption: it does not protect confidentiality. This entry targets Java SE 21; the production runtime has not been attested.
Base64.getEncoder() returns a Basic encoder. Base64.Encoder.encodeToString(byte[]) converts bytes into a String. Base64.getDecoder() returns a Basic decoder, and Base64.Decoder.decode(String) recovers a newly allocated byte[]. For text, explicitly use StandardCharsets.UTF_8 before encoding and after decoding; Base64 itself does not specify the original text's character encoding.
Basic adds no line breaks, and its decoder rejects characters outside its alphabet, including whitespace. Use getUrlEncoder() and getUrlDecoder() for the URL-safe variant. MIME has separate factories, getMimeEncoder() and getMimeDecoder(); its decoder ignores characters outside the alphabet. Match the variant to the data format.
Malformed input to decode(String) causes IllegalArgumentException, while null causes NullPointerException. Trailing = padding may be omitted when the final group contains two or three Base64 characters; if padding is present, its count must be correct. The example checks text recovery and shows the expected output.
Examples
import java.nio.charset.StandardCharsets;
import java.util.Base64;
public class Main {
public static void main(String[] args) {
String original = "Hello";
byte[] bytes = original.getBytes(StandardCharsets.UTF_8);
String encoded = Base64.getEncoder().encodeToString(bytes);
byte[] decoded = Base64.getDecoder().decode(encoded);
String restored = new String(decoded, StandardCharsets.UTF_8);
if (!original.equals(restored)) {
throw new AssertionError("Round-trip failed");
}
System.out.println(encoded);
System.out.println(restored);
}
}Result
SGVsbG8= Hello
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.