Skip to content

Commit f2e0126

Browse files
authored
Use GCM mode in AES (fixes TheAlgorithms#3324) (TheAlgorithms#3325)
1 parent 8803b7f commit f2e0126

File tree

1 file changed

+10
-5
lines changed

1 file changed

+10
-5
lines changed

src/main/java/com/thealgorithms/ciphers/AESEncryption.java

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,8 @@
33
import java.security.InvalidKeyException;
44
import java.security.NoSuchAlgorithmException;
55
import 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
@@ -13,6 +15,7 @@
1315
public 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

Comments
 (0)