Feb 10, 2016

Java 8: Base64 encoding and decoding

Java 8 has come up with inbuilt encoder and decoder for Base64 encoding. Base 64 class is present in java.util package.

This class consists exclusively of static methods for obtaining encoders and decoders for the Base64 encoding scheme. The implementation of this class supports the following types of Base64 encodings:

• Basic
The encoder does not add any line feed (line separator) character and the output is mapped to characters in the Base64 Alphabet: A-Za-z0-9+/. The decoder rejects data that contains characters outside the Base64 alphabet.
• URL and Filename safe
This encoder uses the "URL and Filename safe" Alphabet which includes ‘-’  and ‘_’ (minus and underline) instead of +/. The encoder does not add any line feed (line separator) character. The decoder rejects data that contains characters outside the base64 alphabet.
• MIME
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.
Below is the class and method summary, taken from Oracle’s official site.

Nested Class Summary

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

Method Summary

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

Example:


package com.javaterritory;

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

public class EncodingDecoding {

 public static void main(String args[]) {
  try {
   String stringToBeEncoded = "Java 8 Base64 encoding";
   String charsetName = "utf-8";

   // Basic Encoder
   System.out.println("String to be encoded : " + stringToBeEncoded);
   String encodedString = Base64.getEncoder().encodeToString(stringToBeEncoded.getBytes(charsetName));
   System.out.println("Base64 Basic Encoded String :" + encodedString);

   // Decoder
   byte[] decodedBytes = Base64.getDecoder().decode(encodedString);
   System.out.println("Decoded String : " + new String(decodedBytes, charsetName) + "\n");

   // URL Encoder
   System.out.println("String to be encoded : " + stringToBeEncoded);
   encodedString = Base64.getUrlEncoder().encodeToString(stringToBeEncoded.getBytes(charsetName));
   System.out.println("Base64 Encoded String (URL) :" + encodedString);

   // URL Decoder
   decodedBytes = Base64.getUrlDecoder().decode(encodedString);
   System.out.println("Decoded String : " + new String(decodedBytes, charsetName) + "\n");

   // Mime Encoder
   StringBuilder stringBuilder = new StringBuilder();
   for (int i = 0; i < 10; ++i) {
    stringBuilder.append(UUID.randomUUID().toString());
   }
   System.out.println("String to be encoded : " + stringBuilder);

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

   // Mime decoder
   decodedBytes = Base64.getMimeDecoder().decode(mimeEncodedString);
   System.out.println("Decoded String : " + new String(decodedBytes, charsetName) + "\n");

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

Output:

String to be encoded : Java 8 Base64 encoding
Base64 Basic Encoded String :SmF2YSA4IEJhc2U2NCBlbmNvZGluZw==
Decoded String : Java 8 Base64 encoding

String to be encoded : Java 8 Base64 encoding
Base64 Encoded String (URL) :SmF2YSA4IEJhc2U2NCBlbmNvZGluZw==
Decoded String : Java 8 Base64 encoding

String to be encoded : 19d2b9d6-7a20-4110-9875-1d0894853326343a96d3-ca1b-42f2-a95a-372b0a80f05252e7fc11-b84b-4605-ad2a-df3077eaaa40a46bc5d2-d7ed-48ad-9e37-52d5495ad571e5598a08-4a86-4fb7-abbd-147b3df1363643589717-1dba-4033-9913-e6371cafaed9ea63d8f7-9a74-45fa-ae4e-9c0cc2f351b3c8493e17-0c64-44aa-950e-5a4d2daacdb16ba365ea-ab6b-4945-bbbd-916f054aa5dff03b9ebd-68e3-4c0f-a79c-d172990c904e
Base64 Encoded String (MIME) :MTlkMmI5ZDYtN2EyMC00MTEwLTk4NzUtMWQwODk0ODUzMzI2MzQzYTk2ZDMtY2ExYi00MmYyLWE5
NWEtMzcyYjBhODBmMDUyNTJlN2ZjMTEtYjg0Yi00NjA1LWFkMmEtZGYzMDc3ZWFhYTQwYTQ2YmM1
ZDItZDdlZC00OGFkLTllMzctNTJkNTQ5NWFkNTcxZTU1OThhMDgtNGE4Ni00ZmI3LWFiYmQtMTQ3
YjNkZjEzNjM2NDM1ODk3MTctMWRiYS00MDMzLTk5MTMtZTYzNzFjYWZhZWQ5ZWE2M2Q4ZjctOWE3
NC00NWZhLWFlNGUtOWMwY2MyZjM1MWIzYzg0OTNlMTctMGM2NC00NGFhLTk1MGUtNWE0ZDJkYWFj
ZGIxNmJhMzY1ZWEtYWI2Yi00OTQ1LWJiYmQtOTE2ZjA1NGFhNWRmZjAzYjllYmQtNjhlMy00YzBm
LWE3OWMtZDE3Mjk5MGM5MDRl
Decoded String : 19d2b9d6-7a20-4110-9875-1d0894853326343a96d3-ca1b-42f2-a95a-372b0a80f05252e7fc11-b84b-4605-ad2a-df3077eaaa40a46bc5d2-d7ed-48ad-9e37-52d5495ad571e5598a08-4a86-4fb7-abbd-147b3df1363643589717-1dba-4033-9913-e6371cafaed9ea63d8f7-9a74-45fa-ae4e-9c0cc2f351b3c8493e17-0c64-44aa-950e-5a4d2daacdb16ba365ea-ab6b-4945-bbbd-916f054aa5dff03b9ebd-68e3-4c0f-a79c-d172990c904e

Hope you liked the post. Join at +Java Territory to stay updated with latest articles.

2 comments:

  1. "Nice and good article.. it is very useful for me to learn and understand easily.. thanks for sharing your valuable information and time.. please keep updating.php jobs in hyderabad.
    "

    ReplyDelete