Base64 Encoding and Decoding Examples in Java using Apache Commons

Base64 Encoding and Decoding Examples in Java using Apache Commons

In this tutorial we will discuss how to Encode and Decode using Base64 using Apache Commons Open Source library. In our other tutorials, we discuss how to perform “Base64 Encoding and Decoding Examples in Java using Google Guava”. If you are using Java 8, you may be aware that it now natively supports Base64 encoding and decoding. Please reference our Java 8 tutorial called “Base64 Encoding and Decoding Examples in Java 8”.

What’s Covered

  1. Getting Started
  2. Required Libraries
  3. What is Base64 Encoding
  4. Base64 Alphabet Characters Used for Encoding
  5. Base64 Encoding/Decoding using Apache Commons Library
  6. Base64 Encoding/Decoding Apache Commons Output

Getting Started

In order to run this tutorial yourself, you will need the following:

  • Java JDK 1.6 or greater
  • Favorite IDE Spring Tool Suite (STS), Eclipse IDE or NetBeans (I happen to be using STS because it comes with a Tomcat server built-in)
  • Tomcat 7 or greater or other popular container (Weblogic, Websphere, Glassfish, JBoss, VMWare vFabric, etc). For this tutorial I am using VMware vFabric tc Server Developer Edition which is essentially an enhanced Tomcat instance integrated with Spring STS
  • Apache Commons Codec – 1.10 The Apache Commons Codec package contains simple encoder and decoders for various formats such as Base64, Hexadecimal, Soundex, and various encryption utilities (Crypt, MD5Crypt, Sha2Crypt)

Required Libraries

commons-codec-1.10.jar

You will then configure your libraries in the Libraries tab on Java Build Path Dialog Screen (shown below).

base64_apache_lib_setup

Complete Project Overview

I have added the project overview to give you a full view of the structure and show you all files contained in this sample project.

base64_apache_proj_struct

What is Base64 Encoding

Base64 is one of several encoding schemes used to encode binary data in a text based representation (ASCII) using a radix-64 representation. Although there are several other variants among them Base16 and Base32, it is Base64 which is the most prevalent and popular. The need for Base64 arose during the advent of email. During which time folks began to speculate with the possiblity of using attachments with things like images, videos or other binary data. Since STMP (Simple Mail Transfer Protocol) only supported 7-bit ASCII characters within the messages, there was a need to be able to encode this binary data and convert it into a format that was universally supported without having to affect the current infrastructure of email servers and the SMTP protocol.

This led the industry into standards like MIME (Multipurpose Internet Mail Extensions). The MIME specification supports two binary-to-text encoding schemes (Base64 and quotable-printable).

Base64 Alphabet Characters Used for Encoding

Base64 makes use of the following characters:

CharactersDescription
[a-z]26 Characters
[A-Z]26 Characters
[0-9]10 Characters
[+]1 Character (filler)
[/]1 Character (filler)
[=]1 Character (padding)

Base64 Encoding/Decoding using Apache Commons Library

In this example, we will encode a String called sampleText using the Base64 encoding algorithm. We will be using the org.apache.commons.codec.binary.Base64 class from the Apache Commons Codec library. This class implements the Base64 Content Transfer Encoding from RFC 2045.

The Base64 class contains many static methods which will be used in our example for the encoding and the decoding. To encode our sampleText String we will use getBytes() method which returns a byte[] array for the encodeBase64 static method. It will return a byte[] array with the encoded data. We then simple create a new String passing in this byte[] array into the String’s constructor.

Decoding a previously Base64 encoded string we perform the identical steps as we did in the encoding phase.

  • Create a String containing the encoded text
  • Call the Base64.decodeBase64 static method
  • Use the String with the getBytes() method to return byte[] array
  • Output the String to our console
package com.avaldes.tutorial;

import java.nio.charset.StandardCharsets;

import org.apache.commons.codec.binary.Base64;

public class Base64EncodeDecodeApache {
 private static String sampleText = "Do, or do Not. There is no try.";

 public static void main(String[] args) {
  encodingDecodingApacheCommons();
  encodingDecodingApacheCommonsUTF();
 }

 public static void encodingDecodingApacheCommons() {
  // ---Encode Data---
  byte[] encoded = Base64.encodeBase64(sampleText.getBytes());
  String encodedText =  new String(encoded);

  // ---Decode Data---
  byte[] decoded = Base64.decodeBase64(encodedText.getBytes());
  String decodedText =  new String(decoded);

  System.out.println("Base64 Encoding/Decoding - Apache Commons");
  System.out.println("-----------------------------------------");
  System.out.println("SampleText......: " + sampleText);
  System.out.println("EncodedText.....: " + encodedText);
  System.out.println("DecodedText.....: " + decodedText);
  System.out.println();
 }

 public static void encodingDecodingApacheCommonsUTF() {
  // ---Encode Data---
  byte[] encoded = Base64.encodeBase64(sampleText
                            .getBytes(StandardCharsets.UTF_8));
  String encodedText =  new String(encoded, StandardCharsets.UTF_8);

  // ---Decode Data---
  byte[] decoded = Base64.decodeBase64(encodedText
                            .getBytes(StandardCharsets.UTF_8));
  String decodedText =  new String(decoded, StandardCharsets.UTF_8);

  System.out.println("Base64 Encoding/Decoding - Apache (UTF_8)");
  System.out.println("-----------------------------------------");
  System.out.println("SampleText......: " + sampleText);
  System.out.println("EncodedText.....: " + encodedText);
  System.out.println("DecodedText.....: " + decodedText);
  System.out.println();
 }
}

Base64 Encoding/Decoding using Apache Commons Output

Base64 Encoding/Decoding - Apache Commons
-----------------------------------------
SampleText......: Do, or do Not. There is no try.
EncodedText.....: RG8sIG9yIGRvIE5vdC4gVGhlcmUgaXMgbm8gdHJ5Lg==
DecodedText.....: Do, or do Not. There is no try.

Base64 Encoding/Decoding - Apache Commons (UTF_8)
-------------------------------------------------
SampleText......: Do, or do Not. There is no try.
EncodedText.....: RG8sIG9yIGRvIE5vdC4gVGhlcmUgaXMgbm8gdHJ5Lg==
DecodedText.....: Do, or do Not. There is no try.

References

Download the Complete Source Code

That’s It!

I hope you enjoyed this tutorial. It was certainly a lot of fun putting it together and testing it out. Please continue to share the love and like us so that we can continue bringing you quality tutorials. Happy Coding!!!

base64_apache_commons

Core Java Related Tutorials

Please Share Us on Social Media

Facebooktwitterredditpinterestlinkedinmail

Leave a Reply

Your email address will not be published. Required fields are marked *