AwsKmsAead implements Aead { @Override public byte[] encrypt(final byte[] plaintext, final byte[] associatedData) throws GeneralSecurityException { try { EncryptRequest req = new EncryptRequest().withKeyId(keyArn).withPlaintext(ByteBuffer.wrap(plaintext)); if (associatedData != null && associatedData.length != 0) { req = req.addEncryptionContextEntry("associatedData", BinaryUtils.toHex(associatedData)); } return kmsClient.encrypt(req).getCiphertextBlob().array(); } catch (AmazonServiceException e) { throw new GeneralSecurityException("encryption failed", e); } } AwsKmsAead(AWSKMS kmsClient, String keyUri); @Override byte[] encrypt(final byte[] plaintext, final byte[] associatedData); @Override byte[] decrypt(final byte[] ciphertext, final byte[] associatedData);  }
@Test public void testEncryptShouldThrowExceptionIfRequestFailed() throws Exception { AmazonServiceException exception = mock(AmazonServiceException.class); when(mockKms.encrypt(isA(EncryptRequest.class))) .thenThrow(exception); Aead aead = new AwsKmsAead(mockKms, KEY_ID); byte[] aad = Random.randBytes(20); byte[] message = Random.randBytes(20); try { aead.encrypt(message, aad); fail("Expected GeneralSecurityException"); } catch (GeneralSecurityException e) { } }