Skip to content

Commit 209c7ec

Browse files
Ensure spec length is correct
1 parent 9d248fb commit 209c7ec

File tree

1 file changed

+7
-3
lines changed

1 file changed

+7
-3
lines changed

src/main/java/com/amazonaws/encryptionsdk/internal/AesGcmJceKeyCipher.java

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -29,14 +29,15 @@ class AesGcmJceKeyCipher extends JceKeyCipher {
2929
private static final int NONCE_LENGTH = 12;
3030
private static final int TAG_LENGTH = 128;
3131
private static final String TRANSFORMATION = "AES/GCM/NoPadding";
32+
private static final int SPEC_LENGTH = Integer.BYTES + Integer.BYTES + NONCE_LENGTH;
3233

3334
AesGcmJceKeyCipher(SecretKey key) {
3435
super(key, key);
3536
}
3637

3738
private static byte[] specToBytes(final GCMParameterSpec spec) {
3839
final byte[] nonce = spec.getIV();
39-
final byte[] result = new byte[Integer.BYTES + Integer.BYTES + nonce.length];
40+
final byte[] result = new byte[SPEC_LENGTH];
4041
final ByteBuffer buffer = ByteBuffer.wrap(result);
4142
buffer.putInt(spec.getTLen());
4243
buffer.putInt(nonce.length);
@@ -45,16 +46,19 @@ private static byte[] specToBytes(final GCMParameterSpec spec) {
4546
}
4647

4748
private static GCMParameterSpec bytesToSpec(final byte[] data, final int offset) throws InvalidKeyException {
48-
final ByteBuffer buffer = ByteBuffer.wrap(data, offset, data.length - offset);
49+
if (data.length - offset != SPEC_LENGTH) {
50+
throw new InvalidKeyException("Algorithm specification was an invalid data size");
51+
}
4952

53+
final ByteBuffer buffer = ByteBuffer.wrap(data, offset, SPEC_LENGTH);
5054
final int tagLen = buffer.getInt();
5155
final int nonceLen = buffer.getInt();
5256

5357
if (tagLen != TAG_LENGTH) {
5458
throw new InvalidKeyException(String.format("Authentication tag length must be %s", TAG_LENGTH));
5559
}
5660

57-
if (nonceLen != NONCE_LENGTH || buffer.remaining() != NONCE_LENGTH) {
61+
if (nonceLen != NONCE_LENGTH) {
5862
throw new InvalidKeyException(String.format("Initialization vector (IV) length must be %s", NONCE_LENGTH));
5963
}
6064

0 commit comments

Comments
 (0)