Base64 Encode & Decode of password string or byte array (Java8)

Problem Statement ?

  • Given a string like password, byte array, we would like to perform Base64 encoding and decoding of input string or byte array.

Example of Base64 Encoding and decoding of String:

  • Input stringĀ  = “I Love Soccer”.
  • Base64 encoded string should: “SSBMb3ZlIFNvY2Nlcg==”
  • Base64 decoded string for “SSBMb3ZlIFNvY2Nlcg==” would be “I Love Soccer”

JDK classes for Base 64 encoding & decoding:

  • Base64 class has two inner classes Encoder and Decoder which are used to encode and decode input byte data respectively.
  • Encoder class:

    • 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.
  • Decoder class:

    • Decoder class implements a decoder for decoding byte data using the Base64 encoding scheme as specified in RFC 4648 and RFC 2045.
    • Instances of Base64.Decoder class are SAFE for use by multiple concurrent threads.

Code: Encode & decode byte/ string using Base64 (Java8)

package org.learn;

import java.util.Base64;

public class Base64EncodingDemo {

    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 :" + encodedString);

        //Decode Base64 encoded string to String
        Base64.Decoder base64Decoder = Base64.getDecoder();
        byte[] byteDecoded = base64Decoder.decode(encodedString);
        System.out.println("Decoded String :" + new String(byteDecoded));
    }
}

Output: Base64 encoding & decoding of byte array (Java8)

Input String : I Love Soccer
Encoded String :SSBMb3ZlIFNvY2Nlcg==
Decoded String :I Love Soccer
Scroll to Top