33import java .security .InvalidKeyException ;
44import java .security .NoSuchAlgorithmException ;
55import javax .crypto .*;
6+ import javax .crypto .spec .GCMParameterSpec ;
7+ import java .security .InvalidAlgorithmParameterException ;
68
79/**
810 * This example program shows how AES encryption and decryption can be done in
1315public class AESEncryption {
1416
1517 private static final char [] HEX_ARRAY = "0123456789ABCDEF" .toCharArray ();
18+ private static Cipher aesCipher ;
1619
1720 /**
1821 * 1. Generate a plain text for encryption 2. Get a secret key (printed in
@@ -62,7 +65,7 @@ public static SecretKey getSecretEncryptionKey()
6265 public static byte [] encryptText (String plainText , SecretKey secKey )
6366 throws NoSuchAlgorithmException , NoSuchPaddingException , InvalidKeyException , IllegalBlockSizeException , BadPaddingException {
6467 // AES defaults to AES/ECB/PKCS5Padding in Java 7
65- Cipher aesCipher = Cipher .getInstance ("AES" );
68+ aesCipher = Cipher .getInstance ("AES/GCM/NoPadding " );
6669 aesCipher .init (Cipher .ENCRYPT_MODE , secKey );
6770 return aesCipher .doFinal (plainText .getBytes ());
6871 }
@@ -73,11 +76,13 @@ public static byte[] encryptText(String plainText, SecretKey secKey)
7376 * @return plainText
7477 */
7578 public static String decryptText (byte [] byteCipherText , SecretKey secKey )
76- throws NoSuchAlgorithmException , NoSuchPaddingException , InvalidKeyException , IllegalBlockSizeException , BadPaddingException {
79+ throws NoSuchAlgorithmException , NoSuchPaddingException , InvalidKeyException ,
80+ IllegalBlockSizeException , BadPaddingException , InvalidAlgorithmParameterException {
7781 // AES defaults to AES/ECB/PKCS5Padding in Java 7
78- Cipher aesCipher = Cipher .getInstance ("AES" );
79- aesCipher .init (Cipher .DECRYPT_MODE , secKey );
80- byte [] bytePlainText = aesCipher .doFinal (byteCipherText );
82+ Cipher decryptionCipher = Cipher .getInstance ("AES/GCM/NoPadding" );
83+ GCMParameterSpec gcmParameterSpec = new GCMParameterSpec (128 , aesCipher .getIV ());
84+ decryptionCipher .init (Cipher .DECRYPT_MODE , secKey , gcmParameterSpec );
85+ byte [] bytePlainText = decryptionCipher .doFinal (byteCipherText );
8186 return new String (bytePlainText );
8287 }
8388
0 commit comments