CKTIS / Java
Base64 in Java: encoding and decoding bytes
Use `java.util.Base64` to represent bytes as text and recover the original bytes. Base64 is reversible and provides neither confidentiality nor integrity.
Version: Java SE 21
Syntax
import java.util.Base64;
Base64.Encoder encoder = Base64.getEncoder();
Base64.Decoder decoder = Base64.getDecoder();
String encoded = encoder.encodeToString(bytes); // bytes: byte[]
byte[] decoded = decoder.decode(encoded);In Java SE 21, Base64.getEncoder/getDecoder refers to two static, no-argument methods on java.util.Base64 for the Basic variant: Base64.getEncoder() returns a Base64.Encoder, and Base64.getDecoder() returns a Base64.Decoder. These objects can be reused and shared across threads. The Basic encoder inserts no line breaks. If a protocol requires URL-safe or MIME Base64, choose the matching pair of methods instead.
Base64.Encoder.encodeToString(byte[]) takes bytes and returns Base64 text as a String; encode(byte[]) returns encoded bytes instead. Base64.Decoder.decode(String) takes Base64 text and returns the original bytes in a new array. The decode(byte[]) overload takes encoded bytes instead of text. If the original data is text, convert it to bytes with an explicit charset such as StandardCharsets.UTF_8. After Base64 decoding, use the same charset to reconstruct the text.
The Basic encoder adds trailing = padding by default when needed. The decoder accepts omitted padding if the final group has two or three Base64 characters. The Basic decoder rejects characters outside the allowed alphabet, including whitespace, and rejects malformed padding; decode(String) throws IllegalArgumentException in these cases. A null argument causes NullPointerException.
Base64 is a reversible way to represent bytes as text, not encryption or an integrity check. Anyone can decode the data, and successful decoding does not show that the data is unchanged.
Examples
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Base64;
public class Base64RoundTrip {
public static void main(String[] args) {
byte[] original = "caf\u00E9".getBytes(StandardCharsets.UTF_8);
Base64.Encoder encoder = Base64.getEncoder();
Base64.Decoder decoder = Base64.getDecoder();
String encoded = encoder.encodeToString(original);
byte[] decoded = decoder.decode(encoded);
System.out.println(encoded);
System.out.println(Arrays.equals(original, decoded));
}
}Result
Y2Fmw6k= true
The text `café` is converted to UTF-8 bytes, encoded as `Y2Fmw6k=`, and decoded. `true` means the two byte arrays have identical contents.
Related lessons
- Java · Lesson 51 · Advanced · Version: 2