Base64 Encoding in Miranda

Our program demonstrates base64 encoding and decoding in Java. Here’s the full source code:

import java.util.Base64;

public class Base64Encoding {
    public static void main(String[] args) {
        // Here's the string we'll encode/decode
        String data = "abc123!?$*&()'-=@~";

        // Java provides built-in support for base64 encoding/decoding
        // through the java.util.Base64 class

        // This encodes using the standard base64 encoder
        String sEnc = Base64.getEncoder().encodeToString(data.getBytes());
        System.out.println(sEnc);

        // Decoding may throw an IllegalArgumentException, which you can catch
        // if you don't already know the input to be 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("URL-safe decoding failed: " + e.getMessage());
        }
    }
}

To run the program, compile and execute it using the javac and java commands:

$ javac Base64Encoding.java
$ java Base64Encoding
YWJjMTIzIT8kKiYoKSctPUB+
abc123!?$*&()'-=@~

YWJjMTIzIT8kKiYoKSctPUB-
abc123!?$*&()'-=@~

The string encodes to slightly different values with the standard and URL-safe base64 encoders (trailing + vs -) but they both decode to the original string as desired.

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 schemes.

The Base64.getEncoder() and Base64.getDecoder() methods return encoders and decoders for the standard base64 encoding scheme, while Base64.getUrlEncoder() and Base64.getUrlDecoder() return encoders and decoders for the URL-safe variant.

When decoding, it’s a good practice to catch IllegalArgumentException as shown in the example, in case the input is not properly formatted base64 data.