In this source code example, we show you how to encode and decode(Base64) any arbitrary text in Java using the Base64 API that was introduced in Java 8.
Base64 is a binary-to-text encoding scheme that represents binary data in a printable ASCII string format.Java Base64 Encode and Decode Example
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
class Base64DecodeExample {
private static String base64Decode(String value) {
try {
byte[] decodedValue = Base64.getDecoder().decode(value);
return new String(decodedValue, StandardCharsets.UTF_8.toString());
} catch(UnsupportedEncodingException ex) {
throw new RuntimeException(ex);
}
}
private static String base64Encode(String value) {
try {
return Base64.getEncoder()
.encodeToString(value.getBytes(StandardCharsets.UTF_8.toString()));
} catch(UnsupportedEncodingException ex) {
throw new RuntimeException(ex);
}
}
public static void main(String[] args) {
String data = "https://www.sourcecodeexamples.net";
String encodedData = base64Encode(data);
System.out.println("encodedData -> " + encodedData);
String decodedData = base64Decode(encodedData);
System.out.println("decodedData -> " + decodedData);
}
}
Output:
encodedData -> aHR0cHM6Ly93d3cuc291cmNlY29kZWV4YW1wbGVzLm5ldA==
decodedData -> https://www.sourcecodeexamples.net
References
Free Spring Boot Tutorial - 5 Hours Full Course
Watch this course on YouTube at Spring Boot Tutorial | Fee 5 Hours Full Course