How to encode decode String in Java base64 Encoding

apache

Base64 Encoding Algorithm

Base64 encodes String using an algorithm which uses 64 printable characters to replace each character in original string in an algorithmic sequence so that it can be decoded later. Base64 encoding prevents misuse of data by encoding it into ASCII format.

Base64 is real simple and easy to use for simple encoding needs. There are more advanced encryption algorithm available like RSA-SHA etc. which should be used in production.

Here we have used Apache commons codec open source library for Encoding and Decoding of String in Java using base64. It provides static method Base64.encodeBase64(byte[]) and Base64.decodeBase64(byte []) for converting binary data into base64 encoded binary Stream and than decoding back from encoded data in base64 encoding mechanism.

Many times we need to encode sensitive data be it binary String format transferring over socket or transferring or storing data in xml files.

Encoding & Decoding String into Base64 Java

Here is an example of encoding and decoding of String in base64 encoding algorithm. we will first encode String by converting it into byte array and than passing down to Base64.encodeBase64(byte[]) which encodes byte array as per base64 encoding algorithm and returns and encoded byte array, which can be converted into String. And then we will decode the String by calling Base64.decodeBase64(byte[]) method.

import org.apache.commons.codec.binary.Base64;

public class Base64Encoding{

    public static void main(String args[]) throws IOException {
        String input = "Example to show base64 encoding in java";

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

	String encodedInput = encode(input);
        System.out.println("Base64 Encoded String : " + new String(inputEncode));

      
	String decodedInput = decode(encodedInput);
        System.out.println("Base64 Encoded String : " + new String(inputEncode));
    }

    private static String encode(String input){
        //encoding  byte array into base64
        byte[] inputEncode = Base64.encodeBase64(input.getBytes());     
      
	return new String(inputEncode);
    }

    private static String decode(String encodedInput){
        byte[] inputEncode = Base64.encodeBase64(encodedInput.getBytes());     

        //decoding byte array into base64
        byte[] decoded = Base64.decodeBase64(inputEncode);      
      
	return new String(decoded);
    }
}