001package ca.bc.webarts.tools; 002 003import java.util.Base64; 004 005import javax.crypto.Cipher; 006import javax.crypto.KeyGenerator; 007import javax.crypto.SecretKey; 008 009/** Example only: See StringEncrypter instead. **/ 010public class EncryptDecryptAES { 011 static Cipher cipher; 012 013 public static void main(String[] args) throws Exception { 014 KeyGenerator keyGenerator = KeyGenerator.getInstance("AES"); 015 keyGenerator.init(128); 016 SecretKey secretKey = keyGenerator.generateKey(); 017 cipher = Cipher.getInstance("AES"); 018 019 String plainText = "AES Symmetric Encryption Decryption"; 020 System.out.println("Plain Text Before Encryption: " + plainText); 021 022 String encryptedText = encrypt(plainText, secretKey); 023 System.out.println("Encrypted Text After Encryption: " + encryptedText); 024 025 String decryptedText = decrypt(encryptedText, secretKey); 026 System.out.println("Decrypted Text After Decryption: " + decryptedText); 027 } 028 029 public static String encrypt(String plainText, SecretKey secretKey) 030 throws Exception { 031 byte[] plainTextByte = plainText.getBytes(); 032 cipher.init(Cipher.ENCRYPT_MODE, secretKey); 033 byte[] encryptedByte = cipher.doFinal(plainTextByte); 034 Base64.Encoder encoder = Base64.getEncoder(); 035 String encryptedText = encoder.encodeToString(encryptedByte); 036 return encryptedText; 037 } 038 039 public static String decrypt(String encryptedText, SecretKey secretKey) 040 throws Exception { 041 Base64.Decoder decoder = Base64.getDecoder(); 042 byte[] encryptedTextByte = decoder.decode(encryptedText); 043 cipher.init(Cipher.DECRYPT_MODE, secretKey); 044 byte[] decryptedByte = cipher.doFinal(encryptedTextByte); 045 String decryptedText = new String(decryptedByte); 046 return decryptedText; 047 } 048}