Explain Codes LogoExplain Codes Logo

Base64 Java encode and decode a string

java
base64-encoding
java-8
best-practices
Anton ShumikhinbyAnton Shumikhin·Oct 30, 2024
TLDR

Here's how to encode a string to Base64 using Base64.getEncoder().encodeToString(str.getBytes()):

// Who needs plaintext? Not us! String encoded = Base64.getEncoder().encodeToString("input".getBytes());

Next, decode with new String(Base64.getDecoder().decode(encoded)):

// Back to plaintext - it's like we never left! String decoded = new String(Base64.getDecoder().decode(encoded));

Quick and easy with java.util.Base64 - no sweat!

Choosing the right tools

Ensure you're using the right implementation:

  • Java 8+: Stick with java.util.Base64. Trust me, it's powerful!
  • Pre-Java 8: Go with javax.xml.bind.DatatypeConverter or org.apache.commons.codec.binary.Base64. Old but gold!

Working on an Android app? Switch to android.util.Base64. If it's a Spring application, try Spring Security's Base64 class for a seamless integration.

Understanding Base64

Base64 encoding morphs binary data into text format for safe and sound transmission over text-only media. This is due to its process of dividing input into 6-bit chunks and transforming each into a character from a set of 64 - hence, "Base64".

Special considerations

  • Padding: Discard padding? Use .withoutPadding().
  • Charset: When converting byte arrays, use Charset.forName("UTF-8") to avoid those pesky character encoding issues.

Error handling

Catch unexpected exceptions like a pro. Wrap your operations in try-catch blocks:

try { // Encode or decode operations here } catch (IllegalArgumentException e) { // Invalid input for Base64 operations? Not on my watch! }

Best practices for maintainability

  • Maintain readability: Code that's easy to read is easy to maintain. Write pretty!
  • Consistency verification: Don't trust, verify. Compare your original, encoded, and decoded values.
  • Byte conversion: Ensure to convert strings to bytes before encoding. Get it right!

Additional functions and features

  • Stream encoding/decoding: Check out java.util.Base64.Encoder and Decoder stream functionality for handling large volumes of data.
  • URL safe encoding: Use Base64.getUrlEncoder() for URL specific encoding.
  • Advanced handling: With org.apache.commons.codec.binary.Base64, it's more than just vanilla Base64!