Skip to content

fix(ciphers): eliminate static mutable Cipher and bind IV to ciphertext in AESEncryption - #7767

Open
Bhumit267 wants to merge 3 commits into
TheAlgorithms:masterfrom
Bhumit267:fix/aes-encryption-static-cipher
Open

Bhumit267 wants to merge 3 commits into
TheAlgorithms:masterfrom
Bhumit267:fix/aes-encryption-static-cipher

Conversation

@Bhumit267

Copy link
Copy Markdown
Contributor
  • I have read CONTRIBUTING.md.
  • This pull request is all my own work -- I have not plagiarized it.
  • All filenames are in PascalCase.
  • All functions and variable names follow Java naming conventions.
  • All new algorithms have a URL in their comments that points to Wikipedia or other similar explanations.
  • All new algorithms include a corresponding test class that validates their functionality.
  • All new code is formatted with clang-format -i --style=file path/to/your/file.java

Fixes #7763

Description

In AESEncryption.java, private static Cipher aesCipher; was stored as a mutable static variable. When decrypting, decryptText() relied on aesCipher.getIV().

This caused several serious issues:

  1. IV Cross-Contamination & Tag Mismatch: If encryptText() was called on multiple plaintexts ($M_1, M_2$), aesCipher was updated with the IV generated for $M_2$. Decrypting $M_1$'s ciphertext subsequently failed with javax.crypto.AEADBadTagException: Tag mismatch!.
  2. NullPointerException: Calling decryptText() without first running encryptText() in the same JVM session resulted in an NPE because aesCipher was null.
  3. Thread Safety & State Leaks: The static state made the cipher unsafe for concurrent usage across threads.

Changes

  • Eliminated private static Cipher aesCipher;, making encryption and decryption completely stateless and thread-safe.
  • Standardized AES-GCM IV management by prepending the 12-byte IV to the ciphertext payload (IV || Ciphertext + Tag) and extracting it during decryption.
  • Preserved existing public method signatures (encryptText(String, SecretKey) and decryptText(byte[], SecretKey)).
  • Added regression tests in AESEncryptionTest.java verifying multiple consecutive encryptions/decryptions and validating error handling for short ciphertexts.

Verification

  • mvn test -Dtest=AESEncryptionTest passes (7/7 tests pass).
  • mvn checkstyle:check passes with 0 violations.

@codecov-commenter

codecov-commenter commented Nov 19, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 82.65%. Comparing base (e79b0f1) to head (89cecdb).
⚠️ Report is 20 commits behind head on master.

Additional details and impacted files
@@             Coverage Diff              @@
##             master    #7767      +/-   ##
============================================
+ Coverage     82.42%   82.65%   +0.22%     
- Complexity     8508     8618     +110     
============================================
  Files           847      848       +1     
  Lines         26289    26481     +192     
  Branches       5133     5182      +49     
============================================
+ Hits          21670    21888     +218     
+ Misses         3828     3809      -19     
+ Partials        791      784       -7     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@DenizAltunkapan DenizAltunkapan left a comment

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.

Thanks for removing the shared Cipher and making the encrypted output self-contained. Before merging, please make encryption and decryption agree on the GCM parameters, validate the full minimum payload length, and document and test the resulting format.

aesCipher.init(Cipher.ENCRYPT_MODE, secKey);
return aesCipher.doFinal(plainText.getBytes());
Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
cipher.init(Cipher.ENCRYPT_MODE, secKey);

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.

Decryption assumes a 12-byte IV and a 128-bit tag, while this initialization leaves both choices to the JCE provider. Please use an explicit GCMParameterSpec with the same tag length and a fresh, securely generated 12-byte IV for each encryption. This makes the byte layout consistent across providers.

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. encryptText now generates a fresh 12-byte IV via SecureRandom on each invocation and initializes the cipher with an explicit GCMParameterSpec(GCM_TAG_LENGTH, iv) so encryption and decryption agree on the 12-byte IV and 128-bit authentication tag across JCE providers.

*/
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.length < GCM_IV_LENGTH) {

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.

Even an empty plaintext produces 28 bytes (a 12-byte IV plus a 16-byte authentication tag). Please validate GCM_IV_LENGTH + GCM_TAG_LENGTH / Byte.SIZE here. A 27-byte input currently passes this check and reaches doFinal, where it is rejected by the provider.

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. decryptText now checks byteCipherText == null || byteCipherText.length < MIN_CIPHERTEXT_LENGTH, where MIN_CIPHERTEXT_LENGTH is GCM_IV_LENGTH + GCM_TAG_LENGTH / Byte.SIZE (28 bytes), rejecting inputs below the minimum payload length before reaching doFinal.


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.

}

@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.

@Bhumit267

Copy link
Copy Markdown
Contributor Author

@DenizAltunkapan Thank you for the review. All requested changes have been implemented and verified (latest commit: 89cecdb3, following e96e34e5):

Summary of Changes

  • Explicit GCM parameters (AESEncryption.encryptText): Generates a fresh 12-byte IV via SecureRandom on each invocation and initializes the cipher with an explicit GCMParameterSpec(GCM_TAG_LENGTH, iv) (128-bit authentication tag) so encryption and decryption enforce the same layout across JCE providers.
  • Full minimum payload validation (AESEncryption.decryptText): Validates byteCipherText == null || byteCipherText.length < MIN_CIPHERTEXT_LENGTH (GCM_IV_LENGTH + GCM_TAG_LENGTH / Byte.SIZE, 28 bytes) before calling doFinal, throwing IllegalArgumentException on null or truncated payloads.
  • Javadoc documentation: Documented the IV || ciphertext || authentication tag byte layout—including the 12-byte IV, 16-byte (128-bit) authentication tag, and 28-byte minimum payload requirement—in both encryptText and decryptText.

Tests & Verification

  • Added regression tests in AESEncryptionTest:
    • 27-byte rejection boundary and null input (IllegalArgumentException)
    • 28-byte empty-plaintext round trip
    • Fresh random IV generation across repeated encryptions of identical plaintext
    • AEADBadTagException rejection on modified ciphertext, modified authentication tags, and decryption with a different key
  • mvn test -Dtest=AESEncryptionTest: 11/11 tests passing
  • mvn checkstyle:check and mvn spotbugs:check: 0 violations / 0 warnings
  • All GitHub Actions CI checks (Build, Clang format linter, CodeQL, AnalyzeJava, AnalyzeActions, check_structure, run_infer) passed on 89cecdb3.

Ready for another look whenever you have a moment!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[BUG] AESEncryption: Static mutable Cipher causes IV cross-contamination, NPE, and decryption failures

3 participants