;

How to Encode and Decode String With Base64 in Java


Tutorialsrack 23/04/2022 Java

In this article, you will learn how to encode and decode strings with base64 in Java. There are various utilities that provide Base64 encoding and decoding functionality in Java.  

Here are the examples to encode the plain text to Base64 and decode the plain text from Base64 using Java.

Java 8 for Base 64

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

Example 1: Encode a string to Base64 in Java

In this example, you’ll learn how to encode a simple string to Base64 in Java. We used the getEncoder() method that returns a simple Base64.Encoder() and the encodeToString() method which takes a byte array as input and returns an encoded string. Let's take an example: 

Example 1: Encode a string to Base64 in Java
//Encode String to Base64 in Java

import java.util.Base64;

public class JavaPrograms {

	public static void main(String[] args) {
		// Normal String Encoding
		String plainText = "Hello, TutorialsRack!";
		ToBase64Encoded(plainText);
	}
	
    public static void ToBase64Encoded(String plainText){
		
		Base64.Encoder simpleEncoder = Base64.getEncoder();
		String encodedText = simpleEncoder.encodeToString(plainText.getBytes());
		System.out.println("Base64 Encoded String: "+ encodedText);
	}
}
Output

Base64 Encoded String: SGVsbG8sIFR1dG9yaWFsc1JhY2sh

Example 2: Decode a String From Base64 in Java

In this example, you’ll learn how to decode a simple string from Base64 in Java. We used the getDecoder() method that returns a simple Base64.Decoder() and the decode() method which takes an encoded string as input and returns a decoded string. Let's take an example:

Example 2: Decode a String From Base64 in Java
//Decode String From Base64 in Java

import java.util.Base64;

public class JavaPrograms {

	public static void main(String[] args) {
		// Encoded String
		String EncodedText = "SGVsbG8sIFR1dG9yaWFsc1JhY2sh";
		FromBase64Decoded(EncodedText);
	}

	public static void FromBase64Decoded(String EncodedText) {
		byte[] decodedByteArr = Base64.getDecoder().decode(EncodedText);
		String decodedStr = new String(decodedByteArr);
		System.out.println("Decoded String: " + decodedStr);
	}
}
Output

Decoded String: Hello, TutorialsRack!

Example 3: Encoding the String to Base64 Without Padding in Java

In this example, we encode the string to Base64 without padding in Java. Padding characters helps to complete the length requirements and carries no meaning. If the encoded string's length is not a multiple of three of the string then the encoder method adds some additional padding characters(such as =) to the encoded string. Let's take an example to understand this:

Example 3: Encoding the String to Base64 Without Padding in Java
//Encode String to Base64 with or Without Padding in Java

import java.util.Base64;

public class JavaPrograms {

	public static void main(String[] args) {
		// Normal String Encoding with Padding
		String plainText = "Java World";
		ToBase64Encoded(plainText);
		
		// Normal String Encoding without Padding
		ToBase64EncodedWithoutPadding(plainText);
	}

	// Encode String with Padding Character
	public static void ToBase64Encoded(String plainText) {

		Base64.Encoder simpleEncoder = Base64.getEncoder();
		String encodedText = simpleEncoder.encodeToString(plainText.getBytes());
		System.out.println("Base64 Encoded String With Padding: " + encodedText);
	}

	// Encode String without Padding Character
	public static void ToBase64EncodedWithoutPadding(String plainText) {

		Base64.Encoder simpleEncoder = Base64.getEncoder();
		String encodedText = simpleEncoder.withoutPadding().encodeToString(plainText.getBytes());
		System.out.println("Base64 Encoded String Without Padding: " + encodedText);
	}
}
Output

Base64 Encoded String With Padding: SmF2YSBXb3JsZA==

Base64 Encoded String Without Padding: SmF2YSBXb3JsZA

Base64 URL Encoding and Decoding

URL encoding is very similar to basic encoding. Base64 class also handles URL encoding and decoding by using the URL and Filename safe Base64 Alphabet

You can use the getUrlEncoder() method to get a Base64 URL encoder. Then, you can use the encodeToString() method as we did in the previous examples for encoding simple strings to Base64.

Similarly, you also have a getUrlDecoder() method that returns a URL Decoder. Again, you can use the decode() method with this decoder. Let's take an example: 

Example 4: URL Encoding To Base64 In Java

Example 4: URL Encoding To Base64 In Java
//Encode and Decode URL in Java

import java.util.Base64;

public class JavaPrograms {

	public static void main(String[] args) {
		// Encode URL
		String urlToEncode = "https://go.java/?intcmp=gojava-banner-java-com";
		String encodedURL = ToBase64EncodedURL(urlToEncode);
		System.out.println("Base64 Encoded URL: " + encodedURL);

		// Decode URL
		String decodedURL = FromBase64DecodedURL(encodedURL);
		System.out.println("Base64 Decoded URL: " + decodedURL);
	}

	// Encode URL
	public static String ToBase64EncodedURL(String plainURL) {

		String encodedURL = Base64.getUrlEncoder().encodeToString(plainURL.getBytes());
		return encodedURL;
	}

	// Decode URL
	public static String FromBase64DecodedURL(String EncodedURL) {

		byte[] decodedUrlBytes = Base64.getUrlDecoder().decode(EncodedURL);
		String deocdedURL = new String(decodedUrlBytes);
		return deocdedURL;
	}
}
Output

Base64 Encoded URL: aHR0cHM6Ly9nby5qYXZhLz9pbnRjbXA9Z29qYXZhLWJhbm5lci1qYXZhLWNvbQ==

Base64 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 of the output is no longer than 76 characters. And also it ends with a carriage return(\r) followed by a linefeed(\n) as the line separator. 

You can use the getMimeEncoder() and the encodeToString() methods for the encoding and for the decoding process, you can use getMimeDecoder() method that returns a java.util.Base64.Decoder  with decode() method to decode the encoded string.

Example 5: Base64 MIME Encoding and Decoding

Example 5: Base64 MIME Encoding and Decoding
import java.util.Base64;
import java.util.UUID;

public class JavaPrograms {

	public static void main(String[] args) {
		// creating a MIME input for encoding
		StringBuilder strBuilder = getMimeBuffer();
		String encodedURL = ToBase64EncodedMIME(strBuilder);
		System.out.println("Base64 Encoded: " + encodedURL);

		// Decode URL
		String decodedURL = FromBase64DecodedMIME(encodedURL);
		System.out.println("Base64 Decoded: " + decodedURL);
	}

	// Method for creating a MIME input for encoding
	private static StringBuilder getMimeBuffer() {
		StringBuilder buffer = new StringBuilder();
		for (int count = 0; count < 10; ++count) {
			buffer.append(UUID.randomUUID().toString());
		}
		return buffer;
	}

	// Encoding
	public static String ToBase64EncodedMIME(StringBuilder buffer) {

		byte[] encodedAsBytes = buffer.toString().getBytes();
		String encodedMime = Base64.getMimeEncoder().encodeToString(encodedAsBytes);
		return encodedMime;
	}

	// Decoding
	public static String FromBase64DecodedMIME(String encodedText) {

		byte[] mimeDecodedBytes = Base64.getMimeDecoder().decode(encodedText);
		String mimeDecodedStr = new String(mimeDecodedBytes);
		return mimeDecodedStr;
	}
}

Encoding/Decoding Using Apache Commons Code

The org.apache.commons.codec.binary.Base64 is not part of the default java language, it is part of a library. To use it you have to put this library on the classpath. 

If you use a build and dependency management tool like maven you can add it as a dependency in the pom.xml file.

First, you need to define the commons-codec dependency in the pom.xml:

<dependencies>
    <dependency>
        <groupId>commons-codec</groupId>
        <artifactId>commons-codec</artifactId>
        <version>1.9</version>
    </dependency>
</dependencies>

Once the Base64 API is created, both the encoding and decoding processes are quite simple.

Example 6: Encoding/Decoding Using Apache Commons Code

Example 6: Encoding/Decoding Using Apache Commons Code
import org.apache.commons.codec.binary.Base64;

public class EncodingDecodingBase64 {

	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);
	}
}

I hope this article will help you to understand how to encode and decode strings with base64 in Java.

Share your valuable feedback, please post your comment at the bottom of this article. Thank you!


Related Posts



Comments

Recent Posts
Tags