Example output
The RSA algorithm is a widely used public key cryptography algorithm for encrypting and decrypting data. Here's an example of how you can write a Java program to encrypt and decrypt data using the RSA algorithm:
import java.security.*;
import javax.crypto.Cipher;
public class RSAEncryptionExample {
public static void main(String[] args) throws Exception {
String plainText = "Hello, RSA Encryption!";
KeyPair keyPair = generateKeyPair();
byte[] encryptedData = encrypt(plainText, keyPair.getPublic());
System.out.println("Encrypted Data: " + bytesToHex(encryptedData));
String decryptedText = decrypt(encryptedData, keyPair.getPrivate());
System.out.println("Decrypted Text: " + decryptedText);
}
public static KeyPair generateKeyPair() throws Exception {
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
keyGen.initialize(2048); // You can choose different key sizes
return keyGen.generateKeyPair();
}
public static byte[] encrypt(String data, PublicKey publicKey) throws Exception {
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
return cipher.doFinal(data.getBytes());
}
public static String decrypt(byte[] encryptedData, PrivateKey privateKey) throws Exception {
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, privateKey);
byte[] decryptedBytes = cipher.doFinal(encryptedData);
return new String(decryptedBytes);
}
public static String bytesToHex(byte[] bytes) {
StringBuilder result = new StringBuilder();
for (byte b : bytes) {
result.append(String.format("%02X", b));
}
return result.toString();
}
}