logo

Java Base64 Encoding and Decoding with Apache Commons Codec

In this tutorial you will learn how to encoding and decoding a String in Java using Apache Commons Codec library. The library provide org.apache.commons.codec.binary.Base64 class with different methods to encode and decode data.

Adding Dependency

Define below dependency in build.gradle if you are using gradle.

compile group: 'commons-codec', name: 'commons-codec', version: '1.12'

Define this dependency in pom.xml if you are using maven.

<dependency>
    <groupId>commons-codec</groupId>
    <artifactId>commons-codec</artifactId>
    <version>1.12</version>
</dependency>

Or you can download the release from Apache Commons Codec home page at: here

4 solutions to encode data

Using encode(byte[]) method:

Base64 base64 = new Base64();
String valueToEncode = "https://simplesolution.dev/";
byte[] encodedBytes = base64.encode(valueToEncode.getBytes());
String encodedString = new String(encodedBytes);

Using encodeToString(byte[]) method:

Base64 base64 = new Base64();
String valueToEncode = "https://simplesolution.dev/";
String encodedString = base64.encodeToString(valueToEncode.getBytes());

Using static method encodeBase64(byte[]):

String valueToEncode = "https://simplesolution.dev/";
byte[] encodedBytes = Base64.encodeBase64(valueToEncode.getBytes());
String encodedString = new String(encodedBytes);

Using static method encodeBase64String(byte[]):

String valueToEncode = "https://simplesolution.dev/";
String encodedString = Base64.encodeBase64String(valueToEncode.getBytes());

4 solutions to decode data

Using decode(byte[]) method:

Base64 base64 = new Base64();
String valueToDecode = "aHR0cHM6Ly9zaW1wbGVzb2x1dGlvbi5kZXYv";
byte[] bytesToDecode = valueToDecode.getBytes();
byte[] decodedBytes = base64.decode(bytesToDecode);
String decodedString = new String(decodedBytes);

Using decode(String) method:

Base64 base64 = new Base64();
String valueToDecode = "aHR0cHM6Ly9zaW1wbGVzb2x1dGlvbi5kZXYv";
byte[] decodedBytes = base64.decode(valueToDecode);
String decodedString = new String(decodedBytes);

Using static method decodeBase64(byte[]):

String valueToDecode = "aHR0cHM6Ly9zaW1wbGVzb2x1dGlvbi5kZXYv";
byte[] bytesToDecode = valueToDecode.getBytes();
byte[] decodedBytes = Base64.decodeBase64(bytesToDecode);
String decodedString = new String(decodedBytes);

Using static method decodeBase64(String):

String valueToDecode = "aHR0cHM6Ly9zaW1wbGVzb2x1dGlvbi5kZXYv";
byte[] decodedBytes = Base64.decodeBase64(valueToDecode);
String decodedString = new String(decodedBytes);

The source code in this article can be found at: https://github.com/simplesolutiondev/Base64ApacheCommonsCodec

Happy Coding!