EXERCISE – 8
Write a Java program to implement the RSA Algorithm using Java Cryptography.
✅ Step 1: Create Java Program
Create a new file named:
RSAExample.java
Now copy and paste the following code:
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import javax.crypto.Cipher;
import java.util.Base64;
public class RSAExample {
public static void main(String[] args) {
try {
String text = "Hello world";
// Generate RSA Key Pair
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
keyGen.initialize(2048); // Key size
KeyPair pair = keyGen.generateKeyPair();
PublicKey publicKey = pair.getPublic();
PrivateKey privateKey = pair.getPrivate();
// Create Cipher object
Cipher cipher = Cipher.getInstance("RSA");
// Encrypt using Public Key
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
byte[] encryptedBytes = cipher.doFinal(text.getBytes());
String encryptedText = Base64.getEncoder().encodeToString(encryptedBytes);
System.out.println("Original Text: " + text);
System.out.println("Encrypted Text: " + encryptedText);
// Decrypt using Private Key
cipher.init(Cipher.DECRYPT_MODE, privateKey);
byte[] decryptedBytes = cipher.doFinal(encryptedBytes);
String decryptedText = new String(decryptedBytes);
System.out.println("Decrypted Text: " + decryptedText);
} catch (Exception e) {
e.printStackTrace();
}
}
}
✅ Step 2: Compile the Program
javac RSAExample.java
If there are no errors, compilation is successful.
✅ Step 3: Run the Program
java RSAExample
You will see output like:
Original Text: Hello world Encrypted Text: ksjdfhksjdfhksjdfhksjdfhksjdfh== Decrypted Text: Hello world
Note: Encrypted text will be different every time because RSA generates new keys each run.
🎯 How RSA Works
- RSA generates a Public Key and Private Key.
- Public Key is used to Encrypt data.
- Private Key is used to Decrypt data.
- It is an Asymmetric Encryption Algorithm.
✅ Result
- RSA key pair generated successfully
- Text encrypted using Public Key
- Text decrypted using Private Key