What is the correct way to encode and decode a string using Base64 in Java, and how can I fix the issue with incorrect output?

I’m trying to encode a string to Base64 in Java and then decode it after transferring through a socket. However, the decoded result doesn’t match the original input. Here’s the code I’m using:

import javax.xml.bind.DatatypeConverter;

public class f {
   public static void main(String a[]) {
      String str = new String(DatatypeConverter.parseBase64Binary("user:123"));
      String res = DatatypeConverter.printBase64Binary(str.getBytes());
      System.out.println(res);
   }
}

What’s going wrong here, and how can I properly handle Base64 encoding and decoding in Java to ensure the result stays consistent?

Here’s how to properly encode a string to Base64 and decode it back:

import javax.xml.bind.DatatypeConverter;

public class f {
   public static void main(String[] args) {
      String input = "user:123";

      // Encode to Base64
      String encoded = DatatypeConverter.printBase64Binary(input.getBytes());
      System.out.println("Encoded: " + encoded);

      // Decode back to original
      String decoded = new String(DatatypeConverter.parseBase64Binary(encoded));
      System.out.println("Decoded: " + decoded);
   }
}

Since Java 8, there’s a cleaner and more modern way:

import java.util.Base64;

public class f {
   public static void main(String[] args) {
      String input = "user:123";

      // Encode
      String encoded = Base64.getEncoder().encodeToString(input.getBytes());
      System.out.println("Encoded: " + encoded);

      // Decode
      byte[] decodedBytes = Base64.getDecoder().decode(encoded);
      String decoded = new String(decodedBytes);
      System.out.println("Decoded: " + decoded);
   }
}

If you’re using this in a socket communication context, make sure:

You’re sending the encoded string as a full message, not splitting it. You use a consistent charset, like UTF-8, both when encoding/decoding and when sending/receiving.

You decode exactly what was encoded. Partial reads from sockets can mess things up.

String input = "user:123";
byte[] encodedBytes = Base64.getEncoder().encode(input.getBytes(StandardCharsets.UTF_8));
String encoded = new String(encodedBytes, StandardCharsets.UTF_8);

// Send `encoded` through socket...
// On receive: decode it back to original string
String decoded = new String(Base64.getDecoder().decode(encoded), StandardCharsets.UTF_8);

Pro Tip: Always test your encoded output manually using an online Base64 decoder to validate correctness.