How to encode and decode Base64
Short answer
Base64 turns bytes into text made of Latin letters, digits and the +, / and = characters. Turn the string into bytes first:
void main() {
String text = "Hello, Java!";
String encoded = Base64.getEncoder().encodeToString(text.getBytes(StandardCharsets.UTF_8));
IO.println(encoded);
}Output:
SGVsbG8sIEphdmEhDecoding
The decoder returns a byte array — make a string out of it again:
void main() {
byte[] bytes = Base64.getDecoder().decode("SGVsbG8sIEphdmEh");
IO.println(new String(bytes, StandardCharsets.UTF_8));
}Output:
Hello, Java!For URLs and tokens
Regular Base64 contains + and /, which have a special meaning in URLs. The URL-safe variant replaces them with - and _:
void main() {
byte[] data = {(byte) 0xfb, (byte) 0xff, (byte) 0xbf};
IO.println(Base64.getEncoder().encodeToString(data));
IO.println(Base64.getUrlEncoder().withoutPadding().encodeToString(data));
}Output:
+/+/
-_-_Common mistake
Treating Base64 as encryption. It is just another way to write data: anyone can decode the string back without a key. And a string with invalid characters throws an exception:
void main() {
Base64.getDecoder().decode("not base64!");
}Output:
Exception in thread "main" java.lang.IllegalArgumentException: Illegal base64 character 20