DEV Community

Ankur Rohilla
Ankur Rohilla

Posted on

Base 64 Encoder-Decoder in Java

Encoding is a way to encode anything as it is, without any line separation. Where output generated is the character set A-Za-z0–9+/, and the decoder rejects any characters outside of that set.

Encoding

Scanner sc = new Scanner(System.in);
        String input = sc.nextLine();
        String encodeInput = Base64.getEncoder().encodeToString(input.getBytes(StandardCharsets.UTF_8));
        System.out.println("Encoded output is :"+encodeInput);
Enter fullscreen mode Exit fullscreen mode

For Example if we give input "hey ankur"
Then the output will be : aGV5IGFua3Vy

Decoding

        byte[] output = Base64.getDecoder().decode(encodeInput);
        String decodeOutput = new String(output);
        System.out.println("The decoded output is :"+decodeOutput);
Enter fullscreen mode Exit fullscreen mode

If we gives the same output that is encoded by the base-64 encoder as we write above then the output we will get :
is "hey ankur"

How Base 64 Encoding Works?

Base64 encoding is used when any binary data needs to be transmitted over a media that is designed to handle only textual data. Many communication protocols like SMTP, NNTP were traditionally designed to work with plain text data represented by the 7-bit US-ASCII character set. To transfer non-ASCII or binary data over such communication channels, the binary data is encoded to the ASCII charset using Base64 encoding scheme.

The encoding process converts binary data to a printable ASCII string format. The decoding process converts the encoded string back to binary data. for detailed information click here

Complete java program for Encoding and Decoding using Base 64

package Basic_project;

import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.Scanner;

public class encoder_decoder {
    public static void main(String[]args){
        Scanner sc = new Scanner(System.in);
        String input = sc.nextLine();
        String encodeInput = Base64.getEncoder().encodeToString(input.getBytes(StandardCharsets.UTF_8));
        System.out.println("Encoded output is :"+encodeInput);

        byte[] output = Base64.getDecoder().decode(encodeInput);
        String decodeOutput = new String(output);
        System.out.println("The decoded output is :"+decodeOutput);
    }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)