Explain Codes LogoExplain Codes Logo

Encoding as Base64 in Java

java
base64-encoding
java-8
encoding
Nikita BarsukovbyNikita Barsukov·Dec 8, 2024
TLDR

Quickly convert text into Base64 in Java using the Base64 class:

//Don't encode your love letters this way, they may still be decoded! String encoded = Base64.getEncoder().encodeToString("text".getBytes());

And here's how you can decode:

//Crack the code and unleash the secrets! String decoded = new String(Base64.getDecoder().decode(encoded));

Just replace "text" with your data and you're good to encode and decode!

Explicit character encoding

Specify your character encoding to avoid strange output. Let's secure with UTF-8:

String text = "text"; //UTF-8 is the real MVP! String encoded = Base64.getEncoder().encodeToString(text.getBytes(StandardCharsets.UTF_8));

This ensures consistency while dealing with different environments.

Encoding bytes, not just words!

You can also encode byte arrays directly:

byte[] bytesToEncode = ...; // Bytes looking for transformation! String encoded = Base64.getEncoder().encodeToString(bytesToEncode);

The encode() method is also available if you want the encoded data as a byte array instead of a string.

Avoiding the "sunburn"

The sun.* packages seem tempting but are unstable. Stick to java.util.Base64. For those running nostalgia on Java 7 or lower, use javax.xml.bind.DatatypeConverter.

Exploring other libraries

java.util.Base64 got you covered. But Google Guava's BaseEncoding is another player in town:

//Now Google knows you were here! String encoded = BaseEncoding.base64().encode("text".getBytes(UTF_8));

Remember to add the Guava dependency in your pom.xml if you decide to go down this road.

Decoding: The Art and the Exceptions

Use the correct decode() variant for your input type and handle exceptions like a pro:

try { //The key to deciphering... byte[] decodedBytes = Base64.getDecoder().decode(encodedString); } catch (IllegalArgumentException e) { //Oops, that's an invalid Base64 input. Back to school! }

Java version compatibility

Pick the right tool for your Java version:

  • Java 8 or later: Use java.util.Base64.
  • Pre-Java 8: Alternatives like Guava or javax.xml.bind.DatatypeConverter are your friends.

Troubleshooting your Base64 woes

Facing unexpected behavior? Try these:

  • Check all IDE configurations.
  • Ensure input data is in the correct format.
  • Test output against expected results.