Skip to content

Commit

Permalink
Fix ArrayIndexOutOfBoundsException when no space needed
Browse files Browse the repository at this point in the history
  • Loading branch information
Greg Rubin committed Mar 12, 2024
1 parent 31fdb38 commit 6cffebe
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 3 deletions.
6 changes: 3 additions & 3 deletions src/com/amazon/corretto/crypto/provider/AesGcmSpi.java
Original file line number Diff line number Diff line change
Expand Up @@ -1006,9 +1006,9 @@ private void checkOutputBuffer(
if (inputLength < 0 || outputOffset < 0) {
throw new ArrayIndexOutOfBoundsException();
}
// Allow outputOffset to index into a 0-length empty array. We must trust that the rest of the
// code doesn't actually do this.
if (outputOffset > output.length || (outputOffset == output.length && output.length != 0)) {
// We only allow outputOffset == output.length if we don't actually need any space for data
if (outputOffset > output.length
|| (outputOffset == output.length && requiredBufferSpace > 0)) {
throw new ArrayIndexOutOfBoundsException();
}

Expand Down
17 changes: 17 additions & 0 deletions tst/com/amazon/corretto/crypto/provider/test/AesTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -1383,6 +1383,23 @@ public void arrayIndexDoesNotResetEncrypt() throws Exception {
assertArraysHexEquals(plaintext, amznC.doFinal(ciphertext));
}

@Test
public void emptyPlaintextAtEndOfArray() throws GeneralSecurityException {
final GCMParameterSpec spec = new GCMParameterSpec(128, randomIV());
amznC.init(Cipher.ENCRYPT_MODE, key, spec);
final byte[] ciphertext = amznC.doFinal();

// Decrypt into empty array
amznC.init(Cipher.DECRYPT_MODE, key, spec);
assertEquals(0, amznC.doFinal(ciphertext, 0, ciphertext.length, new byte[0], 0));

// Decrypt into non-empty array
assertEquals(0, amznC.doFinal(ciphertext, 0, ciphertext.length, new byte[16], 0));

// Decrypt to end of non-empty array
assertEquals(0, amznC.doFinal(ciphertext, 0, ciphertext.length, new byte[16], 16));
}

private byte[] randomIV() {
return TestUtil.getRandomBytes(16);
}
Expand Down

0 comments on commit 6cffebe

Please sign in to comment.