Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
79 changes: 61 additions & 18 deletions src/main/java/com/thealgorithms/ciphers/AESEncryption.java
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
package com.thealgorithms.ciphers;

import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
Expand All @@ -18,12 +21,15 @@
* underlying bytes.
*/
public final class AESEncryption {
private static final int GCM_IV_LENGTH = 12;
private static final int GCM_TAG_LENGTH = 128;
private static final int MIN_CIPHERTEXT_LENGTH = GCM_IV_LENGTH + GCM_TAG_LENGTH / Byte.SIZE;
private static final char[] HEX_ARRAY = "0123456789ABCDEF".toCharArray();
private static final SecureRandom SECURE_RANDOM = new SecureRandom();

private AESEncryption() {
}

private static final char[] HEX_ARRAY = "0123456789ABCDEF".toCharArray();
private static Cipher aesCipher;

/**
* 1. Generate a plain text for encryption 2. Get a secret key (printed in
* hexadecimal form). In actual use this must be encrypted and kept safe.
Expand Down Expand Up @@ -55,34 +61,71 @@ public static SecretKey getSecretEncryptionKey() throws NoSuchAlgorithmException
}

/**
* Encrypts plainText in AES using the secret key
* Encrypts {@code plainText} (UTF-8) with AES-GCM using {@code secKey}.
*
* @return byteCipherText (The encrypted text)
* @throws NoSuchPaddingException (from Cipher)
* <p>Each call generates a fresh 12-byte random IV and uses an explicit 128-bit (16-byte)
* GCM authentication tag. The returned byte array is formatted as
* {@code IV || ciphertext || authentication tag} (a 12-byte IV followed by the ciphertext
* and 16-byte authentication tag).
*
* @param plainText the plaintext string to encrypt
* @param secKey the AES secret key used for encryption
* @return byte array formatted as {@code IV || ciphertext || authentication tag}
* @throws NoSuchAlgorithmException (from Cipher)
* @throws NoSuchPaddingException (from Cipher)
* @throws InvalidKeyException (from Cipher)
* @throws BadPaddingException (from Cipher)
* @throws InvalidAlgorithmParameterException (from Cipher)
* @throws IllegalBlockSizeException (from Cipher)
* @throws BadPaddingException (from Cipher)
*/
public static byte[] encryptText(String plainText, SecretKey secKey) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
// AES defaults to AES/ECB/PKCS5Padding in Java 7
aesCipher = Cipher.getInstance("AES/GCM/NoPadding");
aesCipher.init(Cipher.ENCRYPT_MODE, secKey);
return aesCipher.doFinal(plainText.getBytes());
public static byte[] encryptText(String plainText, SecretKey secKey) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException {
byte[] iv = new byte[GCM_IV_LENGTH];
SECURE_RANDOM.nextBytes(iv);

Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
GCMParameterSpec gcmParameterSpec = new GCMParameterSpec(GCM_TAG_LENGTH, iv);
cipher.init(Cipher.ENCRYPT_MODE, secKey, gcmParameterSpec);
byte[] cipherBytes = cipher.doFinal(plainText.getBytes(StandardCharsets.UTF_8));

ByteBuffer buffer = ByteBuffer.allocate(iv.length + cipherBytes.length);
buffer.put(iv);
buffer.put(cipherBytes);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please document IV || ciphertext || authentication tag in the Javadoc for both encryptText and decryptText, including the 12-byte IV and 16-byte tag, so callers know what bytes to store and pass back.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Addressed in e96e34e5. Updated the Javadoc for both encryptText and decryptText to explicitly document the IV || ciphertext || authentication tag layout, including the 12-byte IV, 16-byte (128-bit) tag, and 28-byte minimum payload length.

return buffer.array();
}

/**
* Decrypts encrypted byte array using the key used for encryption.
* Decrypts a payload formatted as {@code IV || ciphertext || authentication tag} using
* {@code secKey}.
*
* <p>The payload must contain a 12-byte IV followed by the ciphertext and a 16-byte (128-bit)
* GCM authentication tag (at least 28 bytes in total).
*
* @return plainText
* @param byteCipherText encrypted payload formatted as {@code IV || ciphertext || authentication tag}
* @param secKey the AES secret key used during encryption
* @return decrypted UTF-8 plaintext string
* @throws IllegalArgumentException if {@code byteCipherText} is {@code null} or shorter than 28 bytes
* @throws NoSuchAlgorithmException (from Cipher)
* @throws NoSuchPaddingException (from Cipher)
* @throws InvalidKeyException (from Cipher)
* @throws InvalidAlgorithmParameterException (from Cipher)
* @throws IllegalBlockSizeException (from Cipher)
* @throws BadPaddingException if authentication tag verification or decryption fails
*/
public static String decryptText(byte[] byteCipherText, SecretKey secKey) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException, InvalidAlgorithmParameterException {
// AES defaults to AES/ECB/PKCS5Padding in Java 7
if (byteCipherText == null || byteCipherText.length < MIN_CIPHERTEXT_LENGTH) {
throw new IllegalArgumentException("Ciphertext is too short");
}
ByteBuffer buffer = ByteBuffer.wrap(byteCipherText);
byte[] iv = new byte[GCM_IV_LENGTH];
buffer.get(iv);
byte[] cipherBytes = new byte[buffer.remaining()];
buffer.get(cipherBytes);

Cipher decryptionCipher = Cipher.getInstance("AES/GCM/NoPadding");
GCMParameterSpec gcmParameterSpec = new GCMParameterSpec(128, aesCipher.getIV());
GCMParameterSpec gcmParameterSpec = new GCMParameterSpec(GCM_TAG_LENGTH, iv);
decryptionCipher.init(Cipher.DECRYPT_MODE, secKey, gcmParameterSpec);
byte[] bytePlainText = decryptionCipher.doFinal(byteCipherText);
return new String(bytePlainText);
byte[] bytePlainText = decryptionCipher.doFinal(cipherBytes);
return new String(bytePlainText, StandardCharsets.UTF_8);
}

/**
Expand Down
63 changes: 63 additions & 0 deletions src/test/java/com/thealgorithms/ciphers/AESEncryptionTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,11 @@

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;

import java.util.Arrays;
import javax.crypto.AEADBadTagException;
import javax.crypto.SecretKey;
import org.junit.jupiter.api.Test;

Expand Down Expand Up @@ -59,4 +62,64 @@ public void testBytesToHex() {
String hex = AESEncryption.bytesToHex(bytes);
assertEquals("00010F10FF", hex, "Hex representation should match the expected value");
}

@Test
public void testMultipleEncryptionsAndDecryptions() throws Exception {
SecretKey key = AESEncryption.getSecretEncryptionKey();
byte[] cipher1 = AESEncryption.encryptText("First Message", key);
byte[] cipher2 = AESEncryption.encryptText("Second Message", key);

assertEquals("First Message", AESEncryption.decryptText(cipher1, key));
assertEquals("Second Message", AESEncryption.decryptText(cipher2, key));
}

@Test
public void testShortCiphertextThrowsException() throws Exception {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please add a test at the 27-byte rejection boundary and a successful 28-byte empty-plaintext round trip. Also add authentication tests that verify that decryption rejects modified ciphertext and a different key.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Addressed in e96e34e5. Added tests covering the 27-byte rejection boundary (and null input), a 28-byte empty-plaintext round trip, distinct IVs across repeated encryptions, and AEADBadTagException verification for modified ciphertext, modified authentication tags, and decryption with a different key.

SecretKey key = AESEncryption.getSecretEncryptionKey();
assertThrows(IllegalArgumentException.class, () -> AESEncryption.decryptText(null, key));
assertThrows(IllegalArgumentException.class, () -> AESEncryption.decryptText(new byte[27], key));
}

@Test
public void testEmptyPlaintextRoundTrip() throws Exception {
SecretKey key = AESEncryption.getSecretEncryptionKey();
byte[] cipherText = AESEncryption.encryptText("", key);

assertEquals(28, cipherText.length, "Empty plaintext should produce 12-byte IV + 16-byte tag");
assertEquals("", AESEncryption.decryptText(cipherText, key));
}

@Test
public void testFreshRandomIvPerEncryption() throws Exception {
SecretKey key = AESEncryption.getSecretEncryptionKey();
byte[] cipher1 = AESEncryption.encryptText("Same Message", key);
byte[] cipher2 = AESEncryption.encryptText("Same Message", key);

assertTrue(!Arrays.equals(cipher1, cipher2), "Each encryption should use a fresh random IV");
assertEquals("Same Message", AESEncryption.decryptText(cipher1, key));
assertEquals("Same Message", AESEncryption.decryptText(cipher2, key));
}

@Test
public void testModifiedCiphertextFailsAuthentication() throws Exception {
SecretKey key = AESEncryption.getSecretEncryptionKey();
byte[] cipherText = AESEncryption.encryptText("Authenticated Message", key);

byte[] modifiedCiphertext = cipherText.clone();
modifiedCiphertext[12] ^= 0x01;
assertThrows(AEADBadTagException.class, () -> AESEncryption.decryptText(modifiedCiphertext, key));

byte[] modifiedTag = cipherText.clone();
modifiedTag[modifiedTag.length - 1] ^= 0x01;
assertThrows(AEADBadTagException.class, () -> AESEncryption.decryptText(modifiedTag, key));
}

@Test
public void testDifferentKeyFailsAuthentication() throws Exception {
SecretKey key1 = AESEncryption.getSecretEncryptionKey();
SecretKey key2 = AESEncryption.getSecretEncryptionKey();
byte[] cipherText = AESEncryption.encryptText("Secret Message", key1);

assertThrows(AEADBadTagException.class, () -> AESEncryption.decryptText(cipherText, key2));
}
}