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?

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);
   }
}