$show=/label

Java 8 Base64 Encoding and Decoding (With Examples)

SHARE:

Learn different ways to do base64 encoding and decoding functionality in java and using java 8 api. And also examples using the apache commons codec.

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

COMMENTS

BLOGGER

About Us

Author: Venkatesh - I love to learn and share the technical stuff.
Name

accumulo,1,ActiveMQ,2,Adsense,1,API,37,ArrayList,18,Arrays,24,Bean Creation,3,Bean Scopes,1,BiConsumer,1,Blogger Tips,1,Books,1,C Programming,1,Collection,8,Collections,37,Collector,1,Command Line,1,Comparator,1,Compile Errors,1,Configurations,7,Constants,1,Control Statements,8,Conversions,6,Core Java,149,Corona India,1,Create,2,CSS,1,Date,3,Date Time API,38,Dictionary,1,Difference,2,Download,1,Eclipse,3,Efficiently,1,Error,1,Errors,1,Exceptions,8,Fast,1,Files,17,Float,1,Font,1,Form,1,Freshers,1,Function,3,Functional Interface,2,Garbage Collector,1,Generics,4,Git,9,Grant,1,Grep,1,HashMap,2,HomeBrew,2,HTML,2,HttpClient,2,Immutable,1,Installation,1,Interview Questions,6,Iterate,2,Jackson API,3,Java,32,Java 10,1,Java 11,6,Java 12,5,Java 13,2,Java 14,2,Java 8,128,Java 8 Difference,2,Java 8 Stream Conversions,4,java 8 Stream Examples,12,Java 9,1,Java Conversions,14,Java Design Patterns,1,Java Files,1,Java Program,3,Java Programs,114,Java Spark,1,java.lang,4,java.util. function,1,JavaScript,1,jQuery,1,Kotlin,11,Kotlin Conversions,6,Kotlin Programs,10,Lambda,2,lang,29,Leap Year,1,live updates,1,LocalDate,1,Logging,1,Mac OS,3,Math,1,Matrix,6,Maven,1,Method References,1,Mockito,1,MongoDB,3,New Features,1,Operations,1,Optional,6,Oracle,5,Oracle 18C,1,Partition,1,Patterns,1,Programs,1,Property,1,Python,2,Quarkus,1,Read,1,Real Time,1,Recursion,2,Remove,2,Rest API,1,Schedules,1,Serialization,1,Servlet,2,Sort,1,Sorting Techniques,8,Spring,2,Spring Boot,23,Spring Email,1,Spring MVC,1,Streams,31,String,61,String Programs,28,String Revese,1,StringBuilder,1,Swing,1,System,1,Tags,1,Threads,11,Tomcat,1,Tomcat 8,1,Troubleshoot,26,Unix,3,Updates,3,util,5,While Loop,1,
ltr
item
JavaProgramTo.com: Java 8 Base64 Encoding and Decoding (With Examples)
Java 8 Base64 Encoding and Decoding (With Examples)
Learn different ways to do base64 encoding and decoding functionality in java and using java 8 api. And also examples using the apache commons codec.
https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhXobVUe8z-5f2lUMhT9nuNZJGJ_8CF0kKlPH-p1vfLPfrwpbQn7bJxcXYAwgHYheVpB1nakrWCKkTGwhHs6xwxdCrrHD2RjXzMyYhPL9Sv-NOj-9Nx1pwZ-d1HZu9cdO6gEgQFQK5m5zs/w640-h393/Java+8+Base64+Encoding+and+Decoding+.png
https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhXobVUe8z-5f2lUMhT9nuNZJGJ_8CF0kKlPH-p1vfLPfrwpbQn7bJxcXYAwgHYheVpB1nakrWCKkTGwhHs6xwxdCrrHD2RjXzMyYhPL9Sv-NOj-9Nx1pwZ-d1HZu9cdO6gEgQFQK5m5zs/s72-w640-c-h393/Java+8+Base64+Encoding+and+Decoding+.png
JavaProgramTo.com
https://www.javaprogramto.com/2020/08/java-base64-encode-and-decode.html
https://www.javaprogramto.com/
https://www.javaprogramto.com/
https://www.javaprogramto.com/2020/08/java-base64-encode-and-decode.html
true
3124782013468838591
UTF-8
Loaded All Posts Not found any posts VIEW ALL Readmore Reply Cancel reply Delete By Home PAGES POSTS View All RECOMMENDED FOR YOU LABEL ARCHIVE SEARCH ALL POSTS Not found any post match with your request Back Home Sunday Monday Tuesday Wednesday Thursday Friday Saturday Sun Mon Tue Wed Thu Fri Sat January February March April May June July August September October November December Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec just now 1 minute ago $$1$$ minutes ago 1 hour ago $$1$$ hours ago Yesterday $$1$$ days ago $$1$$ weeks ago more than 5 weeks ago Followers Follow THIS PREMIUM CONTENT IS LOCKED STEP 1: Share to a social network STEP 2: Click the link on your social network Copy All Code Select All Code All codes were copied to your clipboard Can not copy the codes / texts, please press [CTRL]+[C] (or CMD+C with Mac) to copy Table of Content