Base64 withoutPadding Encoding of string or byte array (Java8)

Problem Statement:

  • Given input string or byte array, we would like to perform Base64 encoding withoutPadding.

Base 64 Encoder class:

  • Base64 class has Encoder inner class, which is used to encode input byte data.
  • Encoder class implements an encoder for encoding byte data using the Base64 encoding scheme as specified in RFC 4648 and RFC 2045.
  • Instances of Base64.Encoder class are SAFE for use by multiple concurrent threads.

Important points mentioned about padding in RFC 4648:

  • As per RFC 4648 section 3.2
    • In some circumstances, the use of padding (“=”) in base-encoded data is not required or used. In the general case, when assumptions about the size of transported data cannot be made, padding is required to yield correct decoded data.
  • As per RFC 4648 section 12:
    • When padding is used, there are some non-significant bits that warrant security concerns, as they may be abused to leak information or used to bypass string equality comparisons or to trigger implementation problems.

Base64 Encode withoutPadding of byte or string – Java8

package org.learn;

import java.util.Base64;

public class Base64EncodingWithoutPadDemo {

    public static void main(String[] args) {
        String input = "I Love Soccer";
        byte[] bytesInput = input.getBytes();

        System.out.println("Input String : "+input);

        //Encode String to  Base64
        Base64.Encoder base64Encoder = Base64.getEncoder();
        String encodedString = base64Encoder.encodeToString(bytesInput);
        System.out.println("Encoded String withPadding :" + encodedString);

        //Encode String withoutPadding to Base64
        base64Encoder = Base64.getEncoder().withoutPadding();
        encodedString = base64Encoder.encodeToString(bytesInput);
        System.out.println("Encoded String withoutPadding: " + encodedString);
    }
}

O/P: Base64 encoding withoutPadding of byte array (Java8)

Input String : I Love Soccer
Encoded String withPadding :SSBMb3ZlIFNvY2Nlcg==
Encoded String withoutPadding: SSBMb3ZlIFNvY2Nlcg

Observations: withoutPadding encoding of byte array:

  • Padding at the end of the data is performed using the ‘=’ character.
  • We can see result of “withoutPadding” encoded string is “SSBMb3ZlIFNvY2Nlcg” i.e. without trailing ‘=’ characters.
Scroll to Top