Interfaces for Custom Encryption in Java


Create a Java program to demonstrate the use of an interface for custom encryption

  • The Encryptor interface defines a single method encrypt(String data) for encrypting data.
  • In the main method of the Main class, an instance of the Encryptor interface is created using a lambda expression that performs Base64 encoding.
  • The original data string is encrypted using the encrypt method of the Encryptor interface.
  • The original and encrypted data are printed to the console.

Source Code

import java.util.Base64;
 
interface Encryptor
{
	String encrypt(String data);
}
 
public class Main
{
	public static void main(String[] args)
	{
		Encryptor encryptor = data -> Base64.getEncoder().encodeToString(data.getBytes());
 
		String originalData = "Hello World! 123";
		String encryptedData = encryptor.encrypt(originalData);
 
		System.out.println("Original Data : " + originalData);
		System.out.println("Encrypted Data : " + encryptedData);
	}
}

Output

Original Data : Hello World! 123
Encrypted Data : SGVsbG8gV29ybGQhIDEyMw==

Example Programs