Base64 Encoding and Decoding in java8

     Data is everywhere. Anybody can track your data. To secure your data, it should be protected. Java8 offers you a built-in package “java.util.Base64” for security.

Base64 encoding and decoding is the process of making binary data into ASCII string data with 64 characters. Here, encoding is the process of converting normal data into Base64 encoding string.

Decoding is the process base64 encoding string into normal data.

Let us code an example.

First, encode a data into Base64 encoding format:

Steps to follow:

  • ·       Import the built in package java.util.Base64
  • ·       Create a class with main() function.
  • ·       Get the data to be encoded.
  • ·       Using the built in function encodeTostring() to encode the string. It gets the and use Base64.getEncoder() function to encode the data.
  • ·       Finally, Print the original data and encoded data.

//Java program to Base64 encoding a data

import java.util.Base64;

public class Base64Encode {

    public static void main(String[] args) {

        String originalData = "Happiness starts from you";

       // Encode the string

        String encodedData = Base64.getEncoder().encodeToString(originalData.getBytes());

        System.out.println("Original Data: " + originalData);

        System.out.println("Encoded Data: " + encodedData);

    }

}

Just compile and run the program to display the output.

C:\raji\blog>javac Base64Encode.java

C:\raji\blog>java Base64Encode

Original Data: Happiness starts from you

Encoded Data: SGFwcGluZXNzIHN0YXJ0cyBmcm9tIHlvdQ==

This is the output for encoding the data.

Next program is to decode the data.

Java Program to Base64 Decoding a data:

Steps to follow:

  • ·       Include the built in package java.util.Base64
  • ·       Create a class Base64Decode with main() function.
  • ·       Get the data to be decoded.
  • ·       Using the built in function getDecoder() to decode the string. It gets the and use decode() function to decode the data.
  • ·       Finally, Print the encoded and decoded data.

//Java Program to Base64 Decoding a data

import java.util.Base64;

public class Base64Decode {

    public static void main(String[] args) {

        String encodedData = "SGFwcGluZXNzIHN0YXJ0cyBmcm9tIHlvdQ==";

        byte[] decodedBytes = Base64.getDecoder().decode(encodedData);

        String decodedData = new String(decodedBytes);

        System.out.println("Encoded Data: " +encodedData);

        System.out.println("Decoded Data: " + decodedData);

    }

}

While running the program,the output will shown in the display is given below.

C:\raji\blog>javac Base64Decode.java

C:\raji\blog>java Base64Decode

Encoded Data: SGFwcGluZXNzIHN0YXJ0cyBmcm9tIHlvdQ==

Decoded Data: Happiness starts from you

This is the simple way of creating Base64 encoding and decoding in java programming.

No comments:

Post a Comment