import java.util.Base64; import javax.crypto.Cipher; import javax.crypto.KeyGenerator; import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec; public class AES { static Cipher my_cipher; public static void main(String[] args) throws Exception { // Build the key on the server. KeyGenerator keyGenerator = KeyGenerator.getInstance("AES"); keyGenerator.init(128); SecretKey my_secretKey = keyGenerator.generateKey(); // Prepare a version of the key to send to the client String encodedKey = Base64.getEncoder().encodeToString(my_secretKey.getEncoded()); System.out.println("\nThe Key: "+encodedKey+"\n"); System.out.println("The key length is: "+ encodedKey.length()+"\n"); // Rebuild the key using SecretKeySpec on the client. byte[] decodedKey = Base64.getDecoder().decode(encodedKey); SecretKey originalKey = new SecretKeySpec(decodedKey, 0, decodedKey.length, "AES"); my_cipher = Cipher.getInstance("AES"); // On the Server String plainText = "A Simple Demonstration of AES"; System.out.println("Plain Text Before Encryption: " + plainText+"\n"); String encryptedText = encrypt(plainText, my_secretKey); System.out.println("Encrypted Text After Encryption: " + encryptedText+"\n"); // On the Client String decryptedText = decrypt(encryptedText, originalKey); System.out.println("Decrypted Text After Decryption: " + decryptedText+"\n"); } public static String encrypt(String plainText, SecretKey a_secretKey) throws Exception { byte[] plainTextByte = plainText.getBytes(); my_cipher.init(Cipher.ENCRYPT_MODE, a_secretKey); byte[] encryptedByte = my_cipher.doFinal(plainTextByte); Base64.Encoder encoder = Base64.getEncoder(); String encryptedText = encoder.encodeToString(encryptedByte); return encryptedText; } public static String decrypt(String encryptedText, SecretKey a_secretKey) throws Exception { Base64.Decoder decoder = Base64.getDecoder(); byte[] encryptedTextByte = decoder.decode(encryptedText); my_cipher.init(Cipher.DECRYPT_MODE, a_secretKey); byte[] decryptedByte = my_cipher.doFinal(encryptedTextByte); String decryptedText = new String(decryptedByte); return decryptedText; } }