Java 8 Base64 example

Java 8 provides a new feature Base64 to deal with decryption and encryption. Java 8 Base64 class provides three different encoders and decoders to encrypt information at each level.

Simple Encoding and Decoding:

It uses the Base64 alphabet specified by Java in RFC 4648 and RFC 2045 for encoding and decoding operations. The encoder does not add any line feed in output, and the decoder rejects any character other than A-Za-z0-9+/.

 

URL Encoding and Decoding:

It uses the Base64 alphabet specified by Java in RFC 4648 for encoding and decoding operations. The decoder rejects data that contains characters outside A-Za-z0-9+_. Output is URL and filename safe.

 

MIME Encoding and Decoding:

It uses the Base64 alphabet as specified in RFC 2045 for encoding and decoding operations. The output is mapped to MIME friendly format and represented in lines of no more than 76 characters each, and uses a carriage return ‘\r’ followed by a linefeed ‘\n’ as the line separator. No line separator is present to the end of the encoded output.

 

Base64 Nested Classes:

Class Description
Base64.Decoder This class implements a decoder for decoding byte data using the Base64 encoding scheme as specified in RFC 4648 and RFC 2045.
Base64.Encoder This class implements an encoder for encoding byte data using the Base64 encoding scheme as specified in RFC 4648 and RFC 2045.

Base64 Methods

Methods Description
public static Base64.Decoder getDecoder() It returns a Base64.Decoder that decodes using the Basic type base64 encoding scheme.
public static Base64.Encoder getEncoder() It returns a Base64.Encoder that encodes using the Basic type base64 encoding scheme.
public static Base64.Decoder getUrlDecoder() It returns a Base64.Decoder that decodes using the URL and Filename safe type base64 encoding scheme.
public static Base64.Decoder getMimeDecoder() It returns a Base64.Decoder that decodes using the MIME type base64 decoding scheme.
public static Base64.Encoder getMimeEncoder() It Returns a Base64.Encoder that encodes using the MIME type base64 encoding scheme.
public static Base64.Encoder getMimeEncoder(int lineLength, byte[] lineSeparator) It returns a Base64.Encoder that encodes using the MIME type base64 encoding scheme with specified line length and line separators.
public static Base64.Encoder getUrlEncoder() It returns a Base64.Encoder that encodes using the URL and Filename safe type base64 encoding scheme.

Base64 Decoder Methods

Methods Description
public byte[] decode(byte[] src) It decodes all bytes from the input byte array using the Base64 encoding scheme, writing the results into a newly-allocated output byte array. The returned byte array is of the length of the resulting bytes.
public byte[] decode(String src) It decodes a Base64 encoded String into a newly-allocated byte array using the Base64 encoding scheme.
public int decode(byte[] src, byte[] dst) It decodes all bytes from the input byte array using the Base64 encoding scheme, writing the results into the given output byte array, starting at offset 0.
public ByteBuffer decode(ByteBuffer buffer) It decodes all bytes from the input byte buffer using the Base64 encoding scheme, writing the results into a newly-allocated ByteBuffer.
public InputStream wrap(InputStream is) It returns an input stream for decoding Base64 encoded byte stream.

Base64.Encoder Methods

Methods Description
public byte[] encode(byte[] src) It encodes all bytes from the specified byte array into a newly-allocated byte array using the Base64 encoding scheme. The returned byte array is of the length of the resulting bytes.
public int encode(byte[] src, byte[] dst) It encodes all bytes from the specified byte array using the Base64 encoding scheme, writing the resulting bytes to the given output byte array, starting at offset 0.
public String encodeToString(byte[] src) It encodes the specified byte array into a String using the Base64 encoding scheme.
public ByteBuffer encode(ByteBuffer buffer) It encodes all remaining bytes from the specified byte buffer into a newly-allocated ByteBuffer using the Base64 encoding scheme. Upon return, the source buffer’s position will be updated to its limit; its limit will not have been changed. The returned output buffer’s position will be zero and its limit will be the number of resulting encoded bytes.
public OutputStream wrap(OutputStream os) It wraps an output stream for encoding byte data using the Base64 encoding scheme.
public Base64.Encoder withoutPadding() It returns an encoder instance that encodes equivalently to this one, but without adding any padding character at the end of the encoded byte data.

Java Base64 example

package com.w3schools;

import java.util.Base64;
import java.util.UUID;

public class TestExample {
	public static void main(String args[]){
		try {
			
	         // Encode using basic encoder
	         String base64encodedString = Base64.getEncoder().encodeToString(
	            "w3schools?java8".getBytes("utf-8"));
	         System.out.println("Base64 Encoded String (Basic) :" + base64encodedString);
			
	         // Decode
	         byte[] base64decodedBytes = Base64.getDecoder().decode(base64encodedString);
			
	         System.out.println("Original String: " + new String(base64decodedBytes, "utf-8"));
	         base64encodedString = Base64.getUrlEncoder().encodeToString(
	            "w3schools?java8".getBytes("utf-8"));
	         System.out.println("Base64 Encoded String (URL) :" + base64encodedString);
			
	         StringBuilder stringBuilder = new StringBuilder();
			
	         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);

	      } catch(Exception e) {
	         e.printStackTrace();
	      }
	}  
}

Output

Base64 Encoded String (Basic) :Q29kZXNKYXZhP2phdmE4
Original String: w3schools?java8
Base64 Encoded String (URL) :Q29kZXNKYXZhP2phdmE4
Base64 Encoded String (MIME) :M2ZjM2MwZGYtMjFkOS00NWM1LTllNTYtNTViNDhiYzYzNWU0YmZhOWIzMzgtYjcxZC00Y2RjLWE1
ODAtMWIxYzMzMmQ3ZjUwNGFlMjQ2ZDAtNzkzYy00NjNkLTk5OWQtOGNhZTI5NzcxMzYzMzEwNzBk
ZGItMzkwNi00ZjRhLWI1ZGEtMGEyNGI3OGZhNmYwMTgzMzI0Y2UtMGQ2Zi00ZDBhLTg2YzAtZDU5
ZTM3NjZhMjQ2MjE3MTUwNDEtZGM5MC00N2VjLWJmYjgtMmUwZWQyNjMxOGMwOTdmZGUxMDMtZWRl
Ny00YmM2LWJlOWYtZWYyOWFkYzQ1YjgwNzAyMmQzNTMtMzQ2Ny00N2ZlLTk4MDgtYTNjODE1ZGRk
ZDI5NzE4ZWRlYTMtYTZmZi00MzExLWEyMDYtNzYxNDAwNGQwMWIwM2Y2NzdhZTYtMDc5ZC00OTNi
LTlhYjAtYmZhMjAwYTM2YjQz