Java 8: Base64 Encoding and Decoding


In Java 8 added new class Base64 for encryption and decryption. It supports three types encoding and decoding:

  • Simple
  • URL
  • MIME

Note: Passing a null argument to a method of this class will cause a NullPointerException to be thrown.

Simple

Uses “The Base64 Alphabets” lying in A-Za-z0-9+/ for encoding and decoding. The encoder does not add any line feed/line separate character in output and decoder rejects all characters out of the Base 64 alphabet.

Example: Simple Encoding and Decoding

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

public class Base64s {

	public static void main(String[] args) {
    final String text = "Facing Issues On IT in Java 8!";

        final String encoded = Base64.getEncoder().encodeToString( text.getBytes( StandardCharsets.UTF_8 ) );
        System.out.println("After Encoding:"+ encoded );

        final String decoded = new String(Base64.getDecoder().decode( encoded ),StandardCharsets.UTF_8 );
        System.out.println("After Decoding:"+ decoded );
	}
}

Output


After Encoding:RmFjaW5nIElzc3VlcyBPbiBJVCBpbiBKYXZhIDgh
After Decoding:Facing Issues On IT in Java 8!

URL

Uses “URL and Filename safe Base64 Alphabet” lying in A-Za-z0-9+_ for encoding and decoding. The encoder does not add any line feed/line separater character in output and decoder rejects all characters out of the Base 64 alphabet.

Example: URL Encoding and Decoding

import java.util.Base64;

public class Base64URLExample {

	public static void main(String[] args) {
		String originalUrl = "https://www.google.co.in/?gfe_rd=cr&ei=dzbFV&gws_rd=ssl#q=java";
		String encodedUrl = Base64.getUrlEncoder().encodeToString(originalUrl.getBytes());
		System.out.println("After Encoding:"+ encodedUrl );

		byte[] decodedBytes = Base64.getUrlDecoder().decode(encodedUrl);
		String decodedUrl = new String(decodedBytes);
		System.out.println("After Decoding:"+ decodedUrl );
	}

}

Output


After Encoding:aHR0cHM6Ly93d3cuZ29vZ2xlLmNvLmluLz9nZmVfcmQ9Y3ImZWk9ZHpiRlYmZ3dzX3JkPXNzbCNxPWphdmE=
After Decoding:https://www.google.co.in/?gfe_rd=cr&ei=dzbFV&gws_rd=ssl#q=java

MIME

Uses “The Base64 Alphabet” lying in lying in A-Za-z0-9+/ for encoding and decoding. The encoded output must be represented in lines of no more than 76 characters each and uses a carriage return ‘\r’ followed immediately by a linefeed ‘\n’ as the line separator. No line separator is added to the end of the encoded output. All line separators or other characters not found in the base64 alphabet table are ignored in decoding operation.

Example: MIME Encoding and Decoding

import java.io.UnsupportedEncodingException;
import java.util.Base64;
import java.util.UUID;

public class Base64Mime {

	public static void main(String[] args) {

		try {
			StringBuilder stringBuilder = new StringBuilder();
			// Lets generate some mime input to encode
			for (int i = 0; i < 10; ++i) {
				stringBuilder.append(UUID.randomUUID().toString());
			}

			byte[] mimeBytes = stringBuilder.toString().getBytes("utf-8");
			String mimeEncodedString = Base64.getMimeEncoder().encodeToString(mimeBytes);
			System.out.println("Base64 Encoded String (MIME) :" + mimeEncodedString);

			byte[] decodedBytes = Base64.getMimeDecoder().decode(mimeEncodedString);
			String decodedMime = new String(decodedBytes);
			System.out.println("Base64 Decoded String (MIME) :" + decodedMime);

		} catch (UnsupportedEncodingException e) {
			System.out.println("Error :" + e.getMessage());
		}
	}

}

Output


Base64 Encoded String (MIME) :YWY1MWRkMDAtNjg0MC00MDE4LTk5YWYtMDE4NTFhYmZkYzA3M2Q0MjU1YjMtNDFiOS00ZmZmLTky
NjktYzc5YjU2Mzg4OGMyM2IzZTAyN2QtNzhkMC00YzRiLTg3MzgtZWFiMmI3OTdlNmVlMzdmYzQ3
ZDItYmI2Zi00NmVjLThlYTQtOWUwYWJlODA0M2IwN2I1NzIxNjUtNzJjZC00ODhmLWJkMWUtOWVl
NGI3YTc5M2NmZjczMjU1MDItMzIyNC00Mjc1LWI2MjQtNTcxZTU3ZmZkZjVhNTdiMmM4NTgtMzFi
Yi00ZjNlLWI5MWYtZWJkNjc5ODlkOTA2NDQ4MDZiZDQtOWM4Zi00NjJlLWI1ZWUtODZiNWM0MTJm
MmVjM2JmMjFjMDAtNjUwYi00ZjE0LWI5ZTUtOTY2YjE2NjUzMWQxMGJhYTIzMTAtOTFmMy00OGYz
LTg1ZTgtZmU3OTEyMjNhODc3
Base64 Decoded String (MIME) :af51dd00-6840-4018-99af-01851abfdc073d4255b3-41b9-4fff-9269-c79b563888c23b3e027d-78d0-4c4b-8738-eab2b797e6ee37fc47d2-bb6f-46ec-8ea4-9e0abe8043b07b572165-72cd-488f-bd1e-9ee4b7a793cff7325502-3224-4275-b624-571e57ffdf5a57b2c858-31bb-4f3e-b91f-ebd67989d90644806bd4-9c8f-462e-b5ee-86b5c412f2ec3bf21c00-650b-4f14-b9e5-966b166531d10baa2310-91f3-48f3-85e8-fe791223a877

References

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s