Signup/Sign In

Base64 Encoding and Decoding in Java

The Base64 class is part of java.util class and provides static methods for Base64 encoding and decoding scheme. Java 8 introduced the Base64 class. This class supports three types of Base64 encoding - Basic, URL, and Filename Safe, and MIME.

In this tutorial, we will learn Base64 encoding and decoding using the java.util.Base64 class and the Apache Commons library.

Base64 Basic Encoding and Decoding

The Basic encoder uses the Base64 Alphabet for encoding and decoding. It will not add any line separators to the encoded string. We will use the getEncoder() method that returns a simple Base64.Encoder.

As discussed, this encoder uses the Basic type base64 encoding scheme. Next, we will use the encodeToString() method. It takes a byte array as input and returns an encoded string.

import java.util.Base64;
public class Demo
{
	public static void main(String args[])
	{
		String strToEncode = "Hello World";
		byte[] bytesToEncode = strToEncode.getBytes();
		String encodedStr = Base64.getEncoder().encodeToString(bytesToEncode);		
		System.out.print(encodedStr);
	}
}


SGVsbG8gV29ybGQ=

To decode an encoded string, we will use Base64.Decoder returned by the getDecoder() method. Then, we will use the decode() method of the decoder. It will take an encoded string as input and returns the decoded string.

import java.util.Base64;
public class Demo
{
	public static void main(String args[])
	{
		String strToEncode = "Hello World";
         //encoding
		byte[] bytesToEncode = strToEncode.getBytes();
		String encodedStr = Base64.getEncoder().encodeToString(bytesToEncode);
		System.out.println("Encoded String: " + encodedStr);
		//decoding
		byte[] decodedByteArr = Base64.getDecoder().decode(encodedStr);
		String decodedStr = new String(decodedByteArr);
		System.out.println("Decoded String: " + decodedStr);
	}
}


Encoded String: SGVsbG8gV29ybGQ=
Decoded String: Hello World

Base64 Encoding Without Padding

The encoding performed in the previous section adds additional padding character(=) if the encoded string's length is not a multiple of three. The code below demonstrates this. We can see the two equals sign(=) at the end of the encoded string.

import java.util.Base64;
public class Demo
{
	public static void main(String args[])
	{
		String strToEncode = "Java";
		byte[] bytesToEncode = strToEncode.getBytes();
		String encodedStr = Base64.getEncoder().encodeToString(bytesToEncode);//Encoding with padding
		System.out.println("Encoded String: " + encodedStr);
	}
}


Encoded String: SmF2YQ==

If we don't want this padding, we can use the withoutPadding() method on the encoder.

import java.util.Base64;
public class Demo
{
	public static void main(String args[])
	{
		String strToEncode = "Java";
		byte[] bytesToEncode = strToEncode.getBytes();
		String encodedStr = Base64.getEncoder().withoutPadding().encodeToString(bytesToEncode);//encoding without padding
		System.out.println("Encoded String: " + encodedStr);
	}
}


Encoded String: SmF2YQ

Base64 URL Encoding and Decoding

Base64 class handles URL encoding and decoding by using the URL and Filename safe Base64 Alphabet. We can use the getUrlEncoder() method to obtain a Base64 URL encoder. Then, we can use the encodeToString() method as we did in the previous section.

Similarly, we have a getUrlDecoder() method that returns a URL decoder. Again, we can use the decode() method with this decoder.

import java.util.Base64;
public class Demo
{
	public static void main(String args[])
	{
		String urlToEncode = "https://go.java/?intcmp=gojava-banner-java-com";
         //Encoding
		String encodedUrl = Base64.getUrlEncoder().encodeToString(urlToEncode.getBytes());
		System.out.println("Encoded URL: " + encodedUrl);
		//Decoding
		byte[] decodedUrlBytes = Base64.getUrlDecoder().decode(encodedUrl);
		String decodedUrl = new String(decodedUrlBytes);
		System.out.print("Decoded URL: " + decodedUrl);
	}
}


Encoded URL: aHR0cHM6Ly9nby5qYXZhLz9pbnRjbXA9Z29qYXZhLWJhbm5lci1qYXZhLWNvbQ==
Decoded URL: https://go.java/?intcmp=gojava-banner-java-com

Base64 MIME Encoding and Decoding

MIME stands for Multipurpose Internet Mail Extension, and the Base64 class uses the Base64 Alphabet for its encoding and decoding operations. In the encoded output, each line contains a maximum of 76 characters.

Each line ends with a carriage return(\r) followed by a linefeed(\n) as the line separator. Note that no line separator is present at the end of the encoded string.

We can use the getMimeEncoder() and the encodeToString() methods for the encoding.

import java.util.Base64;
import java.util.UUID;
public class Demo
{
	public static void main(String args[])
	{
        //Creating a MIME input for encoding
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < 10; ++i) {
            sb.append(UUID.randomUUID().toString());
         }
		//Encoding
         byte[] bytes = sb.toString().getBytes();
         String mimeEncodedStr = Base64.getMimeEncoder().encodeToString(bytes);
         System.out.println("Encoded String: " + mimeEncodedStr);
	}
}


Encoded String: NTdjMzlmZGMtOWFmYS00YTM5LWExNTktNzNlZWMzZjJlNWVkZTYwNzhhNGEtODMzMS00NWUxLWFj
MmUtYWI4ZGJlZDJlMzljNGIzMGExOTktODc0Ny00ZjQwLWJiNmQtMDgxMGQ4Yjg1MGNjNTAxZDhj
NjctOWMwOS00M2M2LWE2M2ItNmUwNThkYTQ0NzQ3ODJkM2QzNjgtMWQzZi00YWM0LTljYzUtNTll
NTFhZjRlNThiZTExNjQxZjItOTIyYy00MGZkLTkwOWEtMmVhNjczYTMyMjczOWNjNmQ2ZjgtZDYx
YS00YjI1LWI5Y2QtMTVlNWM3ZmE1MTM4ODMwMTM3ZTYtMzdiYS00NjJlLThlMDYtZjdlMDE4OGNk
NDEwOWJlZDM3NjUtZDc0ZS00NzUxLWExOWQtZmVmMjg3N2E5MmRmNzc3ZGE2NWYtYTUyOS00MjBm
LThlZmMtY2JhZjAzY2ZjMjI5

To decode, we will use the getMimeDecoder() to obtain a decoder, and then we will use the decode() method.

import java.util.Base64;
import java.util.UUID;
public class Demo
{
	public static void main(String args[])
	{
        //Creating a MIME input for encoding
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < 10; ++i) {
            sb.append(UUID.randomUUID().toString());
         }		
		//Encoding
         byte[] bytes = sb.toString().getBytes();
         String mimeEncodedStr = Base64.getMimeEncoder().encodeToString(bytes);         
         //Decoding
         byte[] mimeDecodedBytes = Base64.getMimeDecoder().decode(mimeEncodedStr);
         String mimeDecodedStr = new String(mimeDecodedBytes);
	}
}

Using Apache Commons Library

The Apache Commons library also provides a Base64 class inside its org.apache.commons.codec.binary package. This class contains five different constructors for different encoding schemes. After creating a Base64 instance, we can use the encode() and decode() methods on the string bytes to perform encoding and decoding.

import org.apache.commons.codec.binary.Base64;
public class Demo
{
	public static void main(String args[])
	{
		Base64 base64 = new Base64();
        //encoding
		String strToEncode = "Hello World";
		byte[] encodedBytes = base64.encode(strToEncode.getBytes());
		String encodedStr = new String(encodedBytes);
		System.out.println("Encoded String: " + encodedStr);
		//decoding
		byte[] decodedByteArr = base64.decode(encodedStr.getBytes());
		String decodedStr = new String(decodedByteArr);
		System.out.println("Decoded String: " + decodedStr);
	}
}


Encoded String: SGVsbG8gV29ybGQ=
Decoded String: Hello World

We can also directly access the API by using the static methods encodeBase64() and decodeBase64().

import org.apache.commons.codec.binary.Base64;
public class Demo
{
	public static void main(String args[])
	{
		String strToEncode = "Hello World";
        //encoding
		String encodedStr = new String(Base64.encodeBase64(strToEncode.getBytes()));
		System.out.println("Encoded String: " + encodedStr);
		//decoding
		String decodedStr = new String(Base64.decodeBase64(encodedStr.getBytes()));
		System.out.print("Decoded String: " + decodedStr);
	}
}


Encoded String: SGVsbG8gV29ybGQ=
Decoded String: Hello World

Summary

The Base64 of the java.util package was added in Java 8 to provide Base64 encoding and decoding functionalities. It supports three different Base64 encoding and decoding schemes - Basic, URL, and Filename safe, and MIME. This class provides static methods like getEncoder() and getDecoder() to acquire base64 encoders and decoders.

Then, we can use the encodeToString() and decode() methods to perform the encoding and decoding operations. We can also use the Base64 class of the Apache Commons library to perform Base64 encoding and decoding.



About the author:
I am a 3rd-year Computer Science Engineering student at Vellore Institute of Technology. I like to play around with new technologies and love to code.