Base64 Encoding in Fortress
Our example demonstrates base64 encoding and decoding in Java using the java.util.Base64
class.
import java.util.Base64;
public class Base64Example {
public static void main(String[] args) {
// Here's the string we'll encode/decode.
String data = "abc123!?$*&()'-=@~";
// Java provides standard and URL-safe base64 encoding.
// Here's how to encode using the standard encoder.
String sEnc = Base64.getEncoder().encodeToString(data.getBytes());
System.out.println(sEnc);
// Decoding may throw an IllegalArgumentException, which you can catch
// if you're not sure the input is well-formed.
try {
byte[] sDec = Base64.getDecoder().decode(sEnc);
System.out.println(new String(sDec));
} catch (IllegalArgumentException e) {
System.out.println("Decoding failed: " + e.getMessage());
}
System.out.println();
// This encodes/decodes using a URL-safe base64 format.
String uEnc = Base64.getUrlEncoder().encodeToString(data.getBytes());
System.out.println(uEnc);
try {
byte[] uDec = Base64.getUrlDecoder().decode(uEnc);
System.out.println(new String(uDec));
} catch (IllegalArgumentException e) {
System.out.println("Decoding failed: " + e.getMessage());
}
}
}
The string encodes to slightly different values with the standard and URL-safe base64 encoders (trailing =
in standard encoding, and +
vs -
and /
vs _
), but they both decode to the original string as desired.
$ javac Base64Example.java
$ java Base64Example
YWJjMTIzIT8kKiYoKSctPUB+
abc123!?$*&()'-=@~
YWJjMTIzIT8kKiYoKSctPUB-
abc123!?$*&()'-=@~
In Java, we use the java.util.Base64
class for base64 encoding and decoding. This class provides separate encoders and decoders for standard and URL-safe base64 encoding.
The getEncoder()
and getDecoder()
methods return the standard Base64 encoder and decoder, while getUrlEncoder()
and getUrlDecoder()
return the URL-safe versions.
When encoding, we first convert our string to a byte array using getBytes()
. The encodeToString()
method then directly returns the encoded string.
For decoding, we use the decode()
method which returns a byte array. We then convert this byte array back to a string.
Note that in Java, decoding an invalid base64 string throws an IllegalArgumentException
, so it’s good practice to catch this exception when decoding user input or data from an untrusted source.