How to perform base64 encoding and decoding in Java

In Java 8, the Base64 class is added to the java.util package, which encodes the input with A-Za-z0-9+/ character set and decodes the encoded string. Any character other than A-Za-z0-9+/ will be skipped.

Encoding and decoding a string

To encode a string:

  • Get encoder using Base64.getEncoder().
  • Generate an encoded string by passing the string as bytes to the encodeToString method of the encoder object.

To decode a string:

  • Get decoder using Base64.getDecoder().

  • Call the decode method by passing the encodedString.

  • The decode method will return the decoded value as bytes.

import java.util.Base64;
public class Main {
public static void main( String args[] ) {
String str = "Educative.io";
String encodedString = Base64.getEncoder().encodeToString(str.getBytes());
System.out.println("Encoded String of " + str + " is " + encodedString);
byte[] decodedBytes = Base64.getDecoder().decode(encodedString);
String decodedString = new String(decodedBytes);
System.out.println("Decoded String of " + encodedString + " is " + decodedString);
}
}

In the code above, we have encoded and decoded the Educative.io string using Base64.

When we are encoding using Base64, the length of the output-encoded string must be a multiple of three. If the encoded string length is not a multiple of three, then the = character will be added internally to make the string length a multiple of 3. To skip this extra added = character, we can use the withoutPadding method.

import java.util.Base64;
public class Main {
public static void main( String args[] ) {
String str = "Educative.";
String encodedString = Base64.getEncoder().withoutPadding().encodeToString(str.getBytes());
System.out.println("Encoded String(Without padding) of " + str + " is " + encodedString);
encodedString = Base64.getEncoder().encodeToString(str.getBytes());
System.out.println("Encoded String of " + str + " is " + encodedString);
}
}

In the example above, we have encoded the string with and without padding. When encoding the string without padding, the = character is not added to the encoded string.

The Base64 class also contains methods to encode and decode URLs. To use the URL encoder and decoder, use getUrlEncoder and the getUrlDecooder method in the Base64 class, and call encodeToString and the decode method respectively.

import java.util.Base64;
public class Main {
public static void main( String args[] ) {
String url = "https://www.educative.io/profile/view/5405507787423744";
String encodedString = Base64.getUrlEncoder().encodeToString(url.getBytes());
System.out.println("Encoded URL is " + encodedString);
byte[] decodedBytes = Base64.getUrlDecoder().decode(encodedString);
String decodedString = new String(decodedBytes);
System.out.println("Decoded URL is " + decodedString);
}
}

Free Resources