MIME Base64 Wraps Long Lines

Encode with Base64.getMimeEncoder so long payloads wrap at a fixed width, then decode the wrapped text back to the original bytes.

JavaData Integrity

Code

snippet
import java.nio.charset.StandardCharsets;
import java.util.Base64;

public class Main {
    public static void main(String[] args) {
        byte[] payload = "The quick brown fox jumps over the lazy dog".repeat(2)
                .getBytes(StandardCharsets.UTF_8);

        // the MIME encoder wraps every line at the requested width
        String wrapped = Base64.getMimeEncoder(20, "\n".getBytes(StandardCharsets.UTF_8))
                .encodeToString(payload);
        System.out.println("wrapped:");
        System.out.println(wrapped);
        System.out.println("lines: " + wrapped.split("\n").length);

        // the MIME decoder ignores the line breaks it produced
        String decoded = new String(
                Base64.getMimeDecoder().decode(wrapped), StandardCharsets.UTF_8);
        System.out.println("roundtrip: " + decoded.equals(new String(payload, StandardCharsets.UTF_8)));

        // the basic encoder keeps everything on one line
        String plain = Base64.getEncoder().encodeToString(payload);
        System.out.println("plain has newline: " + plain.contains("\n"));
    }
}

How the snippet works

Everything happens inside the class Main and the function main.

What to watch for

  • The imports (if any) point only at standard-library modules.

Applying it

Entry signature: public static void main(String[] args)

Each run prints the 3 labeled blocks wrapped:, lines:, roundtrip: in source order.

Statements that matter

String wrapped = Base64.getMimeEncoder(20, "\n".getBytes(StandardCharsets.UTF_8))
.encodeToString(payload);
byte[] payload = "The quick brown fox jumps over the lazy dog".repeat(2)
.getBytes(StandardCharsets.UTF_8);
String plain = Base64.getEncoder().encodeToString(payload);

Interactive Tools for This Topic

FAQ

What does MIME Base64 Wraps Long Lines print when run?
Execute the whole file; each printed line is prefixed with a label like `wrapped:`, `lines:`, `roundtrip:`.