import javax.crypto.Cipher; import javax.crypto.KeyGenerator; import javax.crypto.SecretKey; public class AESEncryption { public static void main(String[] args) throws Exception { String plainText = "This is a plain text to encrypt."; // Generate AES key KeyGenerator keyGen = KeyGenerator.getInstance("AES"); SecretKey aesKey = keyGen.generateKey(); // Initialize Cipher with AES algorithm and encrypt mode Cipher cipher = Cipher.getInstance("AES"); cipher.init(Cipher.ENCRYPT_MODE, aesKey); // Encrypt the data byte[] cipherText = cipher.update(plainText.getBytes()); byte[] finalCipherText = cipher.doFinal(); System.out.println("Encrypted Text: " + new String(finalCipherText)); } }
import javax.crypto.Cipher; import java.security.KeyPair; import java.security.KeyPairGenerator; public class RSADecryption { public static void main(String[] args) throws Exception { byte[] cipherText = "Bk6IzffPQDTjpPmvWmw=".getBytes(); // Generate RSA key pair KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA"); KeyPair keyPair = keyGen.generateKeyPair(); // Initialize Cipher with RSA algorithm and decrypt mode Cipher cipher = Cipher.getInstance("RSA"); cipher.init(Cipher.DECRYPT_MODE, keyPair.getPrivate()); // Decrypt the data byte[] plainText = cipher.update(cipherText); byte[] finalPlainText = cipher.doFinal(); System.out.println("Decrypted Text: " + new String(finalPlainText)); } }In the above examples, we have used the javax.crypto package to perform encryption and decryption operations using the Cipher class. The update method is used to update the Cipher with the input data and return the processed data in the form of byte arrays. The javax.crypto package is provided by the Java Cryptography Extension (JCE) library.