Java Base64 Encode Example

In this article, you’ll learn how to Base64 decode any Base64 encoded text back to binary data. Java 8’s Base64 API contains implementations for all the Base64 encoding and decoding variants described in the official RFC 4648.

Following variants of Base64 encoding and decoding is supported -

  • Basic: This is the standard Base64 encoding defined in the RFC 4648. The algorithm converts the input to a set of characters containing A-Z, a-z, 0-9, + and /. It uses = as the padding character. The decoder rejects data that contains characters outside this set.

URL and Filename Safe: It is same as the Basic Base64 encoding except that + is replaced by - and / is replaced by _ to make the output URL and filename safe. The decoder rejects data that contains characters outside A-Za-z0-9-_.

MIME: The MIME variant uses the Basic Base64 alphabet (A-Za-z0-9+/). MIME enforces a limit on line length of Base64 encoded data. The encoded output is organized into lines of no more than 76 characters. Each line (except the last line) is separated from the next line via a carriage return (\r) followed by a linefeed (\n). The decoder ignores all line separators and other characters not found in the basic base64 alphabet.

Java Base64 Decode Example

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

class Base64DecodeExample {

    // Base64 Basic Decoding
    private static String base64Decode(String value) {
        try {
            byte[] decodedValue = Base64.getDecoder().decode(value);
            return new String(decodedValue, StandardCharsets.UTF_8.toString());        
        } catch(UnsupportedEncodingException ex) {
            throw new RuntimeException(ex);
        }
    }

    private static String base64Encode(String value) {
        try {
            return Base64.getEncoder()
                        .encodeToString(value.getBytes(StandardCharsets.UTF_8.toString()));        
        } catch(UnsupportedEncodingException ex) {
            throw new RuntimeException(ex);
        }
    }

    public static void main(String[] args) {
        String data = "hello:world!?$*&()'-=@~";

        String encodedData = base64Encode(data);
        System.out.println(base64Decode(encodedData));
    }
}
# Output
$ javac Base64DecodeExample.java
$ java Base64DecodeExample
hello:world!?$*&()'-=@~

Java Base64 URL Decode Example

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

class Base64UrlDecodeExample {

    // Base64 URL Decoding
    private static String base64UrlDecode(String value) {
        try {
            byte[] decodedValue = Base64.getUrlDecoder().decode(value);
            return new String(decodedValue, StandardCharsets.UTF_8.toString());        
        } catch(UnsupportedEncodingException ex) {
            throw new RuntimeException(ex);
        }
    }

    private static String base64UrlEncode(String value) {
        try {
            return Base64.getUrlEncoder()
                        .encodeToString(value.getBytes(StandardCharsets.UTF_8.toString()));
        } catch(UnsupportedEncodingException ex) {
            throw new RuntimeException(ex);
        }
    }
    public static void main(String[] args) {
        String data = "hello:world!?$*&()'-=@~";

        String urlEncodedData = base64UrlEncode(data);
        System.out.println(base64UrlDecode(urlEncodedData));
    }
}
# Output
$ javac Base64UrlDecodeExample.java 
$ java Base64UrlDecodeExample
hello:world!?$*&()'-=@~

Java Base64 MIME Decode Example

import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.UUID;

class Base64MimeDecodeExample {

    // Base64 MIME Decoding
    private static String base64MimeDecode(String value) {
        try {
            byte[] decodedValue = Base64.getUrlDecoder().decode(value);
            return new String(decodedValue, StandardCharsets.UTF_8.toString());        
        } catch(UnsupportedEncodingException ex) {
            throw new RuntimeException(ex);
        }
    }

    private static String base64MimeEncode(String value) {
        try {
            return Base64.getUrlEncoder()
                        .encodeToString(value.getBytes(StandardCharsets.UTF_8.toString()));
        } catch(UnsupportedEncodingException ex) {
            throw new RuntimeException(ex);
        }
    }
    public static void main(String[] args) {
        StringBuilder mimeBuffer = new StringBuilder();
        for (int count = 0; count < 10; ++count) {
            mimeBuffer.append(UUID.randomUUID().toString());
        }

        String mimeEncodedData = base64MimeEncode(mimeBuffer.toString());
        System.out.println(base64MimeDecode(mimeEncodedData));
    }
}
# Output
$ javac Base64MimeDecodeExample.java 
$ java Base64MimeDecodeExample
8122388a-bbce-44b9-a960-b1c3fc06d48f271ade35-429a-4fb3-97c9-14995932bef8bbbe0836-8ba7-48b1-8cf0-b8f785c9eaa19e8919c3-d05e-49bf-bff0-6b52423a181ed2eec246-abd5-48a8-bc22-b540b0ea6050709610c7-dc82-4d1d-9d55-87a990d2bd78e6b70c9d-8ed4-4410-b5e8-1812023f450b57548555-89ca-4918-82ef-8e6921ca30eaa7888345-ac88-4e0a-9fa8-881fa0e0aaf2ef2ad14c-303c-46fb-8648-23ecce0d71e2

Also Read: Java Base64 Encode Example

References