How to Do Base64 Encoding in Java

Published on 2024-03-28

How to Do Base64 Encoding in Java

How to Do Base64 Encoding in Java

If you are developing enterprise applications, REST APIs, or dealing with cryptographic operations in Java, Base64 encoding is an unavoidable requirement. Fortunately, ever since the release of Java 8, managing Base64 has become seamless and standardized without the need for external dependencies like Apache Commons Codec.

In this guide, we will break down exactly how to do base64 encoding in java, decode those strings, and handle more advanced scenarios like URL-safe encoding and converting files to Base64.

Key Takeaways

The Standard Java Base64 API

Prior to Java 8, developers often had to rely on third-party libraries or internal, unsupported classes (like sun.misc.BASE64Encoder) to handle encoding. Today, the standard approach is to use java.util.Base64.

This class provides factory methods to obtain instances of Encoders and Decoders.

1. How to Base64 Encode a String in Java

To encode a string, you need to follow three simple steps: get the bytes of the string, use the Basic encoder, and convert the resulting encoded bytes back into a readable String.

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

public class Base64Example {
    public static void main(String[] args) {
        String originalText = "Hello, Java Developer!";

        // 1. Convert string to byte array using UTF-8
        byte[] textBytes = originalText.getBytes(StandardCharsets.UTF_8);

        // 2. Perform the Base64 encoding
        String encodedText = Base64.getEncoder().encodeToString(textBytes);

        System.out.println("Original: " + originalText);
        System.out.println("Encoded:  " + encodedText);
    }
}

Output:

Original: Hello, Java Developer!
Encoded:  SGVsbG8sIEphdmEgRGV2ZWxvcGVyIQ==

Note: Always specify the charset (StandardCharsets.UTF_8) when converting strings to bytes to ensure cross-platform consistency.

2. How to Decode a Base64 String in Java

Decoding is just as straightforward. You take the Base64 encoded string, decode it into a byte array, and then construct a new String from those bytes.

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

public class Base64DecodeExample {
    public static void main(String[] args) {
        String encodedText = "SGVsbG8sIEphdmEgRGV2ZWxvcGVyIQ==";

        // 1. Decode the Base64 string to a byte array
        byte[] decodedBytes = Base64.getDecoder().decode(encodedText);

        // 2. Convert the byte array back to a String using UTF-8
        String decodedText = new String(decodedBytes, StandardCharsets.UTF_8);

        System.out.println("Decoded: " + decodedText);
    }
}

3. URL and Filename Safe Base64 Encoding

Standard Base64 uses the + and / characters, which have special meanings in URLs and file paths. If you need to pass a Base64 string via a GET parameter in a web application, you must use the URL-safe encoder.

The URL-safe variant replaces + with - and / with _.

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

public class UrlSafeBase64 {
    public static void main(String[] args) {
        String urlText = "subjects?_d=1/some+data";

        // Use getUrlEncoder() instead of getEncoder()
        String encodedUrl = Base64.getUrlEncoder().encodeToString(urlText.getBytes(StandardCharsets.UTF_8));

        System.out.println("URL Safe Encoded: " + encodedUrl);

        // Decoding uses getUrlDecoder()
        byte[] decodedBytes = Base64.getUrlDecoder().decode(encodedText);
    }
}

4. Encoding Files (e.g., Images) to Base64

A common requirement is converting an image or a PDF into a Base64 string to send it inside a JSON payload over a REST API. You can achieve this easily by combining the java.nio.file.Files class with the Base64 encoder.

import java.util.Base64;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.io.IOException;

public class FileToBase64 {
    public static void main(String[] args) {
        Path filePath = Paths.get("path/to/your/image.png");

        try {
            // Read all bytes from the file
            byte[] fileBytes = Files.readAllBytes(filePath);

            // Encode the file bytes
            String base64File = Base64.getEncoder().encodeToString(fileBytes);

            System.out.println("File encoded successfully. Length: " + base64File.length());
        } catch (IOException e) {
            System.err.println("Error reading the file: " + e.getMessage());
        }
    }
}

Conclusion

Knowing how to do base64 encoding in java is a crucial skill for modern backend development. Thanks to the java.util.Base64 utility introduced in Java 8, you have a native, fast, and thread-safe way to handle basic encoding, URL-safe data transfer, and file serialization. By sticking to UTF-8 and selecting the right encoder variant for your specific use case, you can handle data formatting safely and efficiently.

FAQs

Q: Is java.util.Base64 thread-safe? A: Yes. Instances of Base64.Encoder and Base64.Decoder are thread-safe and can be reused concurrently across multiple threads.

Q: Should I still use Apache Commons Codec for Base64? A: If you are using Java 8 or newer, it is highly recommended to drop the external dependency and use the native java.util.Base64 class, as it is heavily optimized by the JVM.

Q: What is MIME encoding in Java Base64? A: MIME encoding (Base64.getMimeEncoder()) generates Base64 output where lines are wrapped at a maximum of 76 characters, separated by a carriage return and line feed (\r\n). This is typically used in email systems and specific cryptographic certificates (like PEM files).

Prosun

About the Author: Prosun

Prosun is a passionate web developer and technical writer specializing in data encoding, cybersecurity, and modern web architectures. As the creator of GoBase64, he is dedicated to building fast, privacy-focused tools for the developer community. He also manages tinyfont.me and htmlcode.blog.

From the GoBase64 Blog