CNS Lab Exercise -6


6. Write a JAVA program to implement the Rijndael algorithm logic.





import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import java.util.Base64;
import java.util.Scanner;

public class RijndaelAES {

    public static void main(String[] args) throws Exception {

        Scanner sc = new Scanner(System.in);

        // User input plaintext
        System.out.print("Enter Plain Text: ");
        String plaintext = sc.nextLine();

        // Step 1: Generate AES Key (128-bit)
        KeyGenerator keyGen = KeyGenerator.getInstance("AES");
        keyGen.init(128);
        SecretKey secretKey = keyGen.generateKey();

        // Step 2: Encryption
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.ENCRYPT_MODE, secretKey);
        byte[] encryptedBytes = cipher.doFinal(plaintext.getBytes());

        // Convert encrypted bytes to Base64 for display
        String encryptedText = Base64.getEncoder().encodeToString(encryptedBytes);

        // Step 3: Decryption
        cipher.init(Cipher.DECRYPT_MODE, secretKey);
        byte[] decryptedBytes = cipher.doFinal(encryptedBytes);
        String decryptedText = new String(decryptedBytes);

        // Output
        System.out.println("\n----- OUTPUT -----");
        System.out.println("Plain Text  : " + plaintext);
        System.out.println("Encrypted   : " + encryptedText);
        System.out.println("Decrypted   : " + decryptedText);
    }
}




Output:

Enter Plain Text: hi 

----- OUTPUT -----
Plain Text  : hi 
Encrypted   : dmZUHhpls3tEe6mr0SNITw==
Decrypted   : hi