Pages

Wednesday, August 19, 2020

Java 8 Base64 Encoding and Decoding (With Examples)

1. Overview

In this article, you'll learn the different ways to do the base 64 encoding and decoding techniques in java 8 and other alternative libraries such as apache common API utility.

Main focus on How to do Base64 encoding and decoding in Java, using the new APIs introduced in Java 8 as well as Apache Commons.

Understand the techniques on how to encode and decode base64 in java.

Java 8 Base64 Encoding and Decoding (With Examples)


2. Java 8 - Base64 API

After a long time, java 8 is added with the builtin base64 encoding and decoding functionalities as part of JDK 8.

This simplifies the encode and decode process without using the other third-party libraries.

In java 8, We can use mainly 3 types of encoding and decoding capabilities as standard. All of the classes are related to this are in java.util.base64 package.

2.1 Base or Simple Type

2.2 URL Encoding/Decoding

2.3 MIME Encoding/Decoding

Let us explore all of these ones.

3. Java 8 Base64 Methods

Base64 is a base class for encoding and decoding. It has two static inner classes and those are Base64.Encoder, Base64.Decoder.

Use the below methods to get the right encoders and decoders for each type.

3.1 static Base64.Decoder getDecoder()

Returns a Base64.Decoder that decodes using the Basic type base64 encoding scheme.

3.2 static Base64.Encoder getEncoder()

Returns a Base64.Encoder that encodes using the Basic type base64 encoding scheme.

3.3 static Base64.Decoder getMimeDecoder()

Returns a Base64.Decoder that decodes using the MIME type base64 decoding scheme.

3.4 static Base64.Encoder getMimeEncoder()

Returns a Base64.Encoder that encodes using the MIME type base64 encoding scheme.

3.5 static Base64.Encoder 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.

3.6 static Base64.Decoder getUrlDecoder()

Returns a Base64.Decoder that decodes using the URL and Filename safe type base64 encoding scheme.

3.7 static Base64.Encoder getUrlEncoder()

Returns a Base64.Encoder that encodes using the URL and Filename safe type base64 encoding scheme.

4. Java 8 Base 64 Simple Encoding and Decoding

This is a simple encoding technique in the Base64.

The encoded string will contain only "A-Za-z0-9+/" these characters set and considers the new line character as line breaker in decoding. Let us see the example you will understand clearly.

package com.javaprogramto.java8.base64;

import java.util.Base64;

public class SImpleBase64Example {

    public static void main(String[] args) {

        String originalString = "Welcome to javaprogramto.com \n good day";

        // create base simple encoder object
        Base64.Encoder simpleEncoder = Base64.getEncoder();

        // Encoding string using simple encode
        String encodedString = simpleEncoder.encodeToString(originalString.getBytes());
        System.out.println("Encoded string : "+encodedString);
        
        // Create base simple decoder  object
        Base64.Decoder simpleDecoder = Base64.getDecoder();
        
        // Deconding the encoded string using decoder
        String decodedString = new String(simpleDecoder.decode(encodedString.getBytes()));
        System.out.println("Decoded String : "+decodedString);
    }
}

Output:

Encoded string : V2VsY29tZSB0byBqYXZhcHJvZ3JhbXRvLmNvbSAKIGdvb2QgZGF5
Decoded String : Welcome to javaprogramto.com 
 good day

As you see in the output, the actual input string is having a line separator. For encoding used. encodeToString() method and it is having the characters from simple encoding characters set.

But, when decoded using decode() method that returns byte[] rather than a string. You need to explicitly cast to the String object.

Finally, the decoded string is showing the content in the next line when the line separator encounters.

5. Java  8 Base64 Encoding and Decoding With Padding

By default, encoding pads with the '=' double equal operator if the encoded string length is not met the desired length.

Typically, an encoded string should be multiples of 3 otherwise it will be added with = character.

On the other side, while decoding all extra padded characters will be discarded.

If you do want to be decoded then encode without padding using withoutPadding().

withoutPadding() method helps to skip the padding of the output.

Many developers think that no padding encoded string cannot be decoded back to the original string.

But, it is wrong and Base64.Decode api provides flexibility to decode back.

Look at the below example to understand with and without padding and also how it can be encoded to the original form.

package com.javaprogramto.java8.base64;

import java.util.Base64;

public class SImpleBase64WithoutPaddingExample {

    public static void main(String[] args) {

        String originalString = "Welcome to javaprogramto.com";

        System.out.println("Original String : "+originalString);
        // create base simple encoder object
        Base64.Encoder simpleEncoder = Base64.getEncoder();

        // Encoding string using simple encode
        String encodedString = simpleEncoder.encodeToString(originalString.getBytes());
        System.out.println("Encoded string with padding : "+encodedString);

        // encode  without  padding
        Base64.Encoder withoutPaddingEncoder = Base64.getEncoder().withoutPadding();
        String encodeWithoutPadding  =  withoutPaddingEncoder.encodeToString(originalString.getBytes());
        System.out.println("Encoded string without padding : "+encodeWithoutPadding);

        // Create base simple decoder  object
        Base64.Decoder simpleDecoder = Base64.getDecoder();

        // Deconding the encoded string using decoder
        String decodedString = new String(simpleDecoder.decode(encodeWithoutPadding.getBytes()));
        System.out.println("Decoded String : "+decodedString);
    }
}

Output:

Original String : Welcome to javaprogramto.com
Encoded string with padding : V2VsY29tZSB0byBqYXZhcHJvZ3JhbXRvLmNvbQ==
Encoded string without padding : V2VsY29tZSB0byBqYXZhcHJvZ3JhbXRvLmNvbQ
Decoded String : Welcome to javaprogramto.com

6. Java  8 Base64 URL Encoding and Decoding

Base64 URL encoder is very similar to the simple encoder. All character set is the same as a simple one but the difference is '_' instead of '\'.

Here is the full URL allowed characters 'A-Za-z0-9+_'.

And also does not add any line separation in the decoder.

use getUrlEncoder() for encoding and getUrlDecoder() for decoding the URL's from Base64.

Base64 URL Example:

package com.javaprogramto.java8.base64;

import java.util.Base64;

public class SImpleBase64URLExample {

    public static void main(String[] args) {

        String originalStringURL = "https://www.google.co.in/imghp?hl=en&tab=wi&authuser=0&ogbl";

        System.out.println("Original String : "+originalStringURL);

        // create url encoder object
        Base64.Encoder simpleEncoder = Base64.getUrlEncoder();

        // Encoding string using url encode
        String encodedString = simpleEncoder.encodeToString(originalStringURL.getBytes());
        System.out.println("Encoded URL string with padding : "+encodedString);

        // encode  without  padding
        Base64.Encoder withoutPaddingEncoder = Base64.getEncoder().withoutPadding();
        String encodeWithoutPadding  =  withoutPaddingEncoder.encodeToString(originalStringURL.getBytes());
        System.out.println("Encoded URL string without padding : "+encodeWithoutPadding);

        // Create base simple decoder  object
        Base64.Decoder simpleDecoder = Base64.getDecoder();

        // Deconding the encoded string using decoder
        String decodedString = new String(simpleDecoder.decode(encodeWithoutPadding.getBytes()));
        System.out.println("Decoded URL String : "+decodedString);
    }
}

Output:

Original String : https://www.google.co.in/imghp?hl=en&tab=wi&authuser=0&ogbl
Encoded URL string with padding : aHR0cHM6Ly93d3cuZ29vZ2xlLmNvLmluL2ltZ2hwP2hsPWVuJnRhYj13aSZhdXRodXNlcj0wJm9nYmw=
Encoded URL string without padding : aHR0cHM6Ly93d3cuZ29vZ2xlLmNvLmluL2ltZ2hwP2hsPWVuJnRhYj13aSZhdXRodXNlcj0wJm9nYmw
Decoded URL String : https://www.google.co.in/imghp?hl=en&tab=wi&authuser=0&ogbl

7. Java  8 Base64 MIME Encoding and Decoding

MIME encoding is another type of Base64 encode and decode. MIME technique is mainly used for more data such as ASCII, email contents attachments, audio, video, and images that need to be encoded and decoded.

Use Base64.getMimeEncoder() for MIME data encoding and Base64.getMimeDecoder() for MIME data decoding.

The encoded content byMIME type will be divided into multiple lines and each line length not exceeding 76 characters. Each line ends with a carriage return such as \n or \r.

package com.javaprogramto.java8.base64;
import java.util.Base64;
import java.util.UUID;

public class SImpleBase64MIMEExample {

    public static void main(String[] args) {

        // adding random  10 UUID values.
        String mimeContent = generateMimeBuffer().toString();

        System.out.println("Original mime buffer length: " + mimeContent.length());

        // Base64 MIME Encode
        Base64.Encoder mimeEncode = Base64.getMimeEncoder();
        String mimeEncodedStr = mimeEncode.encodeToString(mimeContent.getBytes());
        System.out.println("MIME encoded string : " + mimeEncodedStr);

        // Base64 MIME Decode
        Base64.Decoder mimeDecode = Base64.getMimeDecoder();
        String mimeDecodedStr = new String(mimeDecode.decode(mimeEncodedStr.getBytes()));
        System.out.println("MIME decoded string length: " + mimeDecodedStr.length());
    }

    /**
     * Genreates random 10 UUID numbers and adds to the StringBuffer.
     *
     * @return
     */
    private static StringBuffer generateMimeBuffer() {

        StringBuffer buffer = new StringBuffer();
        for (int i = 0; i < 10; i++) {

            buffer.append(UUID.randomUUID());
        }

        return buffer;

    }
}

Output:

package com.javaprogramto.java8.base64;
Original mime buffer length: 360
MIME encoded string : N2Y1Njk5MjEtMjg1OC00YTBhLWFlMDgtYTJhMTIzMDkxOTY5OWNjNWM3OWYtZGQ5My00OTE4LWIz
N2MtYmNlM2I1MzA2MDk0ODdhZTUwNDgtODBlMi00YTUxLThjMGEtZDY4M2Y1YWZmMjc1OWI2YWU4
ZDMtZTE0Ni00ZTQzLWE4MWItMTllYTZiYzE0MDEwYzQ1YjE3MzQtZTM1Ni00NmU5LThhOWMtNDlk
ODA2NGQ4YTU1YzgwYzIxZTUtZDI1Zi00YzMyLTliMzEtY2ViNmU3OGIyNWU3ZDcxOWI4OGYtNzY2
OC00ZGExLThiZGYtMDlmOGM4MTk2MzkxMjI3MTllZjQtMTVkZC00YTY1LTgxZmQtYWUyYzAxYjI1
MjAyYjM2ZDY4ZmItODkxMS00ZGY1LWJiZmEtM2YwMDhiYmZkMzQ5NGIwZmUyOTUtNzMyOC00Nzgz
LThmOTEtYTI5ZWMwM2E4NWFk
MIME decoded string length: 360

8. Encoding and Decoding Using Apache Commons API

The first thing is you need to add a dependency to the pom.xml file as below or add commons-codec.jar file to the project.

package com.javaprogramto.java8.base64;
<dependency>
    <groupId>commons-codec</groupId>
    <artifactId>commons-codec</artifactId>
    <version>1.10</version>
</dependency>

It is suggested to use always the latest version of commons-codec as security is high priority.

Use the org.apache.commons.codec.binary.Base64 class methods work with encoding and decoding and it has various constructors with different arguments. Most of them look very useful.

Base64(): Creates a Base64 codec used for decoding (all modes) and encoding in URL-unsafe mode.

Base64(boolean urlSafe): Creates a Base64 codec used for decoding (all modes) and encoding in the given URL-safe mode.

Base64(int lineLength): Creates a Base64 codec used for decoding (all modes) and encoding in URL-unsafe mode.

Base64(int lineLength, byte[] lineSeparator): Creates a Base64 codec used for decoding (all modes) and encoding in URL-unsafe mode.

Base64(int lineLength, byte[] lineSeparator, boolean urlSafe): Creates a Base64 codec used for decoding (all modes) and encoding in URL-unsafe mode.

Apache Commons Codec Bas64 Example:

package com.javaprogramto.java8.base64;
package com.javaprogramto.java8.base64.apache;

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

public class ApacheCommonsCodecBase64 {
    public static void main(String[] args) {

        String originalInput = "test input for apache commons codec";

        Base64 base64 = new Base64();

        // Commons codec encoding
        String encodedString = new String(base64.encode(originalInput.getBytes()));
        System.out.println("Encoded string : "+encodedString);

        // Commons codec decoding
        String decodedString = new String(base64.decode(encodedString.getBytes()));
        System.out.println("Decoded string : "+decodedString);

    }
}

Output:

package com.javaprogramto.java8.base64;
Encoded string : dGVzdCBpbnB1dCBmb3IgYXBhY2hlIGNvbW1vbnMgY29kZWM=
Decoded string : test input for apache commons codec

And also apache commons codec api provides static methods for decoding and encoding.

Base64.encodeBase64() & Base64.decodeBase64() Example:

package com.javaprogramto.java8.base64;
package com.javaprogramto.java8.base64.apache;

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

public class ApacheCommonsCodecBase64Static {
    public static void main(String[] args) {

        String originalInput = "Test commons codec with static methods";

        // Commons codec encoding with Base64.encodeBase64()
        String encodedString = new String(Base64.encodeBase64(originalInput.getBytes()));
        System.out.println("Encoded string : "+encodedString);

        // Commons codec decoding with Base64.decodeBase64()
        String decodedString = new String(Base64.decodeBase64(encodedString.getBytes()));
        System.out.println("Decoded string : "+decodedString);

    }
}

Output:

package com.javaprogramto.java8.base64;
Encoded string : VGVzdCBjb21tb25zIGNvZGVjIHdpdGggc3RhdGljIG1ldGhvZHM=
Decoded string : Test commons codec with static methods

Use isChunked argument and pass it as true then it will divide the encoded string into multiple lines and each line with 76 characters.

9. Conclusion

In this article, you've seen in-depth about Java 8 Base64 and apache commons codec api on how to encoding and decoding.

As usual. all examples are over GitHub.

java.util.Base64 examples

Apache codec examples

Base64 API

No comments:

Post a Comment

Please do not add any spam links in the comments section.