Skip to content

Commit 972969c

Browse files
authored
fix(ciphers): eliminate static mutable Cipher and bind IV to ciphertext in AESEncryption (#7767)
* fix(ciphers): eliminate static mutable Cipher and bind IV to ciphertext in AESEncryption * fix(ciphers): use explicit GCMParameterSpec, validate 28-byte minimum payload, and add auth tests * fix(tests): keep static imports within PMD limit in AESEncryptionTest
1 parent 4e45cd1 commit 972969c

2 files changed

Lines changed: 124 additions & 18 deletions

File tree

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

Lines changed: 61 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,11 @@
11
package com.thealgorithms.ciphers;
22

3+
import java.nio.ByteBuffer;
4+
import java.nio.charset.StandardCharsets;
35
import java.security.InvalidAlgorithmParameterException;
46
import java.security.InvalidKeyException;
57
import java.security.NoSuchAlgorithmException;
8+
import java.security.SecureRandom;
69
import javax.crypto.BadPaddingException;
710
import javax.crypto.Cipher;
811
import javax.crypto.IllegalBlockSizeException;
@@ -18,12 +21,15 @@
1821
* underlying bytes.
1922
*/
2023
public final class AESEncryption {
24+
private static final int GCM_IV_LENGTH = 12;
25+
private static final int GCM_TAG_LENGTH = 128;
26+
private static final int MIN_CIPHERTEXT_LENGTH = GCM_IV_LENGTH + GCM_TAG_LENGTH / Byte.SIZE;
27+
private static final char[] HEX_ARRAY = "0123456789ABCDEF".toCharArray();
28+
private static final SecureRandom SECURE_RANDOM = new SecureRandom();
29+
2130
private AESEncryption() {
2231
}
2332

24-
private static final char[] HEX_ARRAY = "0123456789ABCDEF".toCharArray();
25-
private static Cipher aesCipher;
26-
2733
/**
2834
* 1. Generate a plain text for encryption 2. Get a secret key (printed in
2935
* hexadecimal form). In actual use this must be encrypted and kept safe.
@@ -55,34 +61,71 @@ public static SecretKey getSecretEncryptionKey() throws NoSuchAlgorithmException
5561
}
5662

5763
/**
58-
* Encrypts plainText in AES using the secret key
64+
* Encrypts {@code plainText} (UTF-8) with AES-GCM using {@code secKey}.
5965
*
60-
* @return byteCipherText (The encrypted text)
61-
* @throws NoSuchPaddingException (from Cipher)
66+
* <p>Each call generates a fresh 12-byte random IV and uses an explicit 128-bit (16-byte)
67+
* GCM authentication tag. The returned byte array is formatted as
68+
* {@code IV || ciphertext || authentication tag} (a 12-byte IV followed by the ciphertext
69+
* and 16-byte authentication tag).
70+
*
71+
* @param plainText the plaintext string to encrypt
72+
* @param secKey the AES secret key used for encryption
73+
* @return byte array formatted as {@code IV || ciphertext || authentication tag}
6274
* @throws NoSuchAlgorithmException (from Cipher)
75+
* @throws NoSuchPaddingException (from Cipher)
6376
* @throws InvalidKeyException (from Cipher)
64-
* @throws BadPaddingException (from Cipher)
77+
* @throws InvalidAlgorithmParameterException (from Cipher)
6578
* @throws IllegalBlockSizeException (from Cipher)
79+
* @throws BadPaddingException (from Cipher)
6680
*/
67-
public static byte[] encryptText(String plainText, SecretKey secKey) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
68-
// AES defaults to AES/ECB/PKCS5Padding in Java 7
69-
aesCipher = Cipher.getInstance("AES/GCM/NoPadding");
70-
aesCipher.init(Cipher.ENCRYPT_MODE, secKey);
71-
return aesCipher.doFinal(plainText.getBytes());
81+
public static byte[] encryptText(String plainText, SecretKey secKey) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException {
82+
byte[] iv = new byte[GCM_IV_LENGTH];
83+
SECURE_RANDOM.nextBytes(iv);
84+
85+
Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
86+
GCMParameterSpec gcmParameterSpec = new GCMParameterSpec(GCM_TAG_LENGTH, iv);
87+
cipher.init(Cipher.ENCRYPT_MODE, secKey, gcmParameterSpec);
88+
byte[] cipherBytes = cipher.doFinal(plainText.getBytes(StandardCharsets.UTF_8));
89+
90+
ByteBuffer buffer = ByteBuffer.allocate(iv.length + cipherBytes.length);
91+
buffer.put(iv);
92+
buffer.put(cipherBytes);
93+
return buffer.array();
7294
}
7395

7496
/**
75-
* Decrypts encrypted byte array using the key used for encryption.
97+
* Decrypts a payload formatted as {@code IV || ciphertext || authentication tag} using
98+
* {@code secKey}.
99+
*
100+
* <p>The payload must contain a 12-byte IV followed by the ciphertext and a 16-byte (128-bit)
101+
* GCM authentication tag (at least 28 bytes in total).
76102
*
77-
* @return plainText
103+
* @param byteCipherText encrypted payload formatted as {@code IV || ciphertext || authentication tag}
104+
* @param secKey the AES secret key used during encryption
105+
* @return decrypted UTF-8 plaintext string
106+
* @throws IllegalArgumentException if {@code byteCipherText} is {@code null} or shorter than 28 bytes
107+
* @throws NoSuchAlgorithmException (from Cipher)
108+
* @throws NoSuchPaddingException (from Cipher)
109+
* @throws InvalidKeyException (from Cipher)
110+
* @throws InvalidAlgorithmParameterException (from Cipher)
111+
* @throws IllegalBlockSizeException (from Cipher)
112+
* @throws BadPaddingException if authentication tag verification or decryption fails
78113
*/
79114
public static String decryptText(byte[] byteCipherText, SecretKey secKey) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException, InvalidAlgorithmParameterException {
80-
// AES defaults to AES/ECB/PKCS5Padding in Java 7
115+
if (byteCipherText == null || byteCipherText.length < MIN_CIPHERTEXT_LENGTH) {
116+
throw new IllegalArgumentException("Ciphertext is too short");
117+
}
118+
ByteBuffer buffer = ByteBuffer.wrap(byteCipherText);
119+
byte[] iv = new byte[GCM_IV_LENGTH];
120+
buffer.get(iv);
121+
byte[] cipherBytes = new byte[buffer.remaining()];
122+
buffer.get(cipherBytes);
123+
81124
Cipher decryptionCipher = Cipher.getInstance("AES/GCM/NoPadding");
82-
GCMParameterSpec gcmParameterSpec = new GCMParameterSpec(128, aesCipher.getIV());
125+
GCMParameterSpec gcmParameterSpec = new GCMParameterSpec(GCM_TAG_LENGTH, iv);
83126
decryptionCipher.init(Cipher.DECRYPT_MODE, secKey, gcmParameterSpec);
84-
byte[] bytePlainText = decryptionCipher.doFinal(byteCipherText);
85-
return new String(bytePlainText);
127+
byte[] bytePlainText = decryptionCipher.doFinal(cipherBytes);
128+
return new String(bytePlainText, StandardCharsets.UTF_8);
86129
}
87130

88131
/**

‎src/test/java/com/thealgorithms/ciphers/AESEncryptionTest.java‎

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,11 @@
22

33
import static org.junit.jupiter.api.Assertions.assertEquals;
44
import static org.junit.jupiter.api.Assertions.assertNotNull;
5+
import static org.junit.jupiter.api.Assertions.assertThrows;
56
import static org.junit.jupiter.api.Assertions.assertTrue;
67

8+
import java.util.Arrays;
9+
import javax.crypto.AEADBadTagException;
710
import javax.crypto.SecretKey;
811
import org.junit.jupiter.api.Test;
912

@@ -59,4 +62,64 @@ public void testBytesToHex() {
5962
String hex = AESEncryption.bytesToHex(bytes);
6063
assertEquals("00010F10FF", hex, "Hex representation should match the expected value");
6164
}
65+
66+
@Test
67+
public void testMultipleEncryptionsAndDecryptions() throws Exception {
68+
SecretKey key = AESEncryption.getSecretEncryptionKey();
69+
byte[] cipher1 = AESEncryption.encryptText("First Message", key);
70+
byte[] cipher2 = AESEncryption.encryptText("Second Message", key);
71+
72+
assertEquals("First Message", AESEncryption.decryptText(cipher1, key));
73+
assertEquals("Second Message", AESEncryption.decryptText(cipher2, key));
74+
}
75+
76+
@Test
77+
public void testShortCiphertextThrowsException() throws Exception {
78+
SecretKey key = AESEncryption.getSecretEncryptionKey();
79+
assertThrows(IllegalArgumentException.class, () -> AESEncryption.decryptText(null, key));
80+
assertThrows(IllegalArgumentException.class, () -> AESEncryption.decryptText(new byte[27], key));
81+
}
82+
83+
@Test
84+
public void testEmptyPlaintextRoundTrip() throws Exception {
85+
SecretKey key = AESEncryption.getSecretEncryptionKey();
86+
byte[] cipherText = AESEncryption.encryptText("", key);
87+
88+
assertEquals(28, cipherText.length, "Empty plaintext should produce 12-byte IV + 16-byte tag");
89+
assertEquals("", AESEncryption.decryptText(cipherText, key));
90+
}
91+
92+
@Test
93+
public void testFreshRandomIvPerEncryption() throws Exception {
94+
SecretKey key = AESEncryption.getSecretEncryptionKey();
95+
byte[] cipher1 = AESEncryption.encryptText("Same Message", key);
96+
byte[] cipher2 = AESEncryption.encryptText("Same Message", key);
97+
98+
assertTrue(!Arrays.equals(cipher1, cipher2), "Each encryption should use a fresh random IV");
99+
assertEquals("Same Message", AESEncryption.decryptText(cipher1, key));
100+
assertEquals("Same Message", AESEncryption.decryptText(cipher2, key));
101+
}
102+
103+
@Test
104+
public void testModifiedCiphertextFailsAuthentication() throws Exception {
105+
SecretKey key = AESEncryption.getSecretEncryptionKey();
106+
byte[] cipherText = AESEncryption.encryptText("Authenticated Message", key);
107+
108+
byte[] modifiedCiphertext = cipherText.clone();
109+
modifiedCiphertext[12] ^= 0x01;
110+
assertThrows(AEADBadTagException.class, () -> AESEncryption.decryptText(modifiedCiphertext, key));
111+
112+
byte[] modifiedTag = cipherText.clone();
113+
modifiedTag[modifiedTag.length - 1] ^= 0x01;
114+
assertThrows(AEADBadTagException.class, () -> AESEncryption.decryptText(modifiedTag, key));
115+
}
116+
117+
@Test
118+
public void testDifferentKeyFailsAuthentication() throws Exception {
119+
SecretKey key1 = AESEncryption.getSecretEncryptionKey();
120+
SecretKey key2 = AESEncryption.getSecretEncryptionKey();
121+
byte[] cipherText = AESEncryption.encryptText("Secret Message", key1);
122+
123+
assertThrows(AEADBadTagException.class, () -> AESEncryption.decryptText(cipherText, key2));
124+
}
62125
}

0 commit comments

Comments
 (0)