Base64 Encode and Decode in Java

In this tutorial, We will show simple program about, How to perform simple Base64 Encode and Decode in Java. The same example program has been attached here.

Base64 Encode and Decode

package com.dineshkrish;
import java.util.Base64;
/**
* 
* @author Dinesh Krishnan
*
*/
public class CryptoUtil {
public static String doEncode(String data) {
Base64.Encoder encoder = Base64.getEncoder();
return encoder.encodeToString(data.getBytes());
}
public static String doDecode(String data) {
Base64.Decoder decoder = Base64.getDecoder();
return new String(decoder.decode(data));
}
}

Example Program

package com.dineshkrish;
/**
* 
* @author Dinesh Krishnan
*
*/
public class Example {
public static void main(String[] args) {
String encoded = CryptoUtil.doEncode("Dinesh Krishnan");
System.out.println("Encode String : " + encoded);
String decoded = CryptoUtil.doDecode(encoded);
System.out.println("Decoded String : " + decoded);
}
}

Output

Encode String : RGluZXNoIEtyaXNobmFu
Decoded String : Dinesh Krishnan

Reference

1. Base64 API Documentation
2. Base64.Encoder API Documentation
3. Base64.Decoder API Documentation

No responses yet

Leave a Reply

Your email address will not be published. Required fields are marked *