diff --git a/src/main/java/com/thealgorithms/ciphers/AESEncryption.java b/src/main/java/com/thealgorithms/ciphers/AESEncryption.java index 6f155e73f47d..c231645c66a7 100644 --- a/src/main/java/com/thealgorithms/ciphers/AESEncryption.java +++ b/src/main/java/com/thealgorithms/ciphers/AESEncryption.java @@ -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; @@ -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. @@ -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) + *

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); + 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}. + * + *

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); } /** diff --git a/src/test/java/com/thealgorithms/ciphers/AESEncryptionTest.java b/src/test/java/com/thealgorithms/ciphers/AESEncryptionTest.java index 2f0831e35064..3b1d42ff3faa 100644 --- a/src/test/java/com/thealgorithms/ciphers/AESEncryptionTest.java +++ b/src/test/java/com/thealgorithms/ciphers/AESEncryptionTest.java @@ -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; @@ -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 { + 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)); + } }