index
int64
0
0
repo_id
stringlengths
9
205
file_path
stringlengths
31
246
content
stringlengths
1
12.2M
__index_level_0__
int64
0
10k
0
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/crypto
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/crypto/examples/BasicEncryptionExampleTest.java
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package com.amazonaws.crypto.examples; import com.amazonaws.encryptionsdk.kms.KMSTestFixtures; import org.junit.Test; public class BasicEncryptionExampleTest { @Test public void testEncryptAndDecrypt() { BasicEncryptionExample.encryptAndDecrypt(KMSTestFixtures.TEST_KEY_IDS[0]); } }
700
0
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/crypto
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/crypto/examples/BasicMultiRegionKeyEncryptionExampleTest.java
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package com.amazonaws.crypto.examples; import com.amazonaws.encryptionsdk.kms.KMSTestFixtures; import org.junit.Test; public class BasicMultiRegionKeyEncryptionExampleTest { @Test public void testEncryptAndDecrypt() { BasicMultiRegionKeyEncryptionExample.encryptAndDecrypt( KMSTestFixtures.US_EAST_1_MULTI_REGION_KEY_ID, KMSTestFixtures.US_WEST_2_MULTI_REGION_KEY_ID); } }
701
0
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/crypto
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/crypto/examples/SetCommitmentPolicyExampleTest.java
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package com.amazonaws.crypto.examples; import com.amazonaws.encryptionsdk.kms.KMSTestFixtures; import org.junit.Test; public class SetCommitmentPolicyExampleTest { @Test public void testEncryptAndDecrypt() { SetCommitmentPolicyExample.encryptAndDecrypt(KMSTestFixtures.TEST_KEY_IDS[0]); } }
702
0
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/crypto
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/crypto/examples/DiscoveryDecryptionExampleTest.java
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package com.amazonaws.crypto.examples; import com.amazonaws.encryptionsdk.kms.KMSTestFixtures; import org.junit.Test; public class DiscoveryDecryptionExampleTest { @Test public void testEncryptAndDecrypt() { DiscoveryDecryptionExample.encryptAndDecrypt( KMSTestFixtures.TEST_KEY_IDS[0], KMSTestFixtures.PARTITION, KMSTestFixtures.ACCOUNT_ID); } }
703
0
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk/DefaultCryptoMaterialsManagerTest.java
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package com.amazonaws.encryptionsdk; import static com.amazonaws.encryptionsdk.multi.MultipleProviderFactory.buildMultiProvider; import static java.util.Collections.singletonMap; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.fail; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.argThat; import static org.mockito.ArgumentMatchers.same; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; import com.amazonaws.encryptionsdk.exception.AwsCryptoException; import com.amazonaws.encryptionsdk.exception.CannotUnwrapDataKeyException; import com.amazonaws.encryptionsdk.exception.NoSuchMasterKeyException; import com.amazonaws.encryptionsdk.exception.UnsupportedProviderException; import com.amazonaws.encryptionsdk.internal.Constants; import com.amazonaws.encryptionsdk.internal.StaticMasterKey; import com.amazonaws.encryptionsdk.internal.TrailingSignatureAlgorithm; import com.amazonaws.encryptionsdk.model.DecryptionMaterials; import com.amazonaws.encryptionsdk.model.DecryptionMaterialsRequest; import com.amazonaws.encryptionsdk.model.EncryptionMaterials; import com.amazonaws.encryptionsdk.model.EncryptionMaterialsRequest; import java.nio.charset.StandardCharsets; import java.security.Signature; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.function.Consumer; import org.junit.Test; public class DefaultCryptoMaterialsManagerTest { private static final MasterKey<?> mk1 = new StaticMasterKey("mk1"); private static final MasterKey<?> mk2 = new StaticMasterKey("mk2"); private static final CommitmentPolicy commitmentPolicy = TestUtils.DEFAULT_TEST_COMMITMENT_POLICY; @Test public void encrypt_testBasicFunctionality() throws Exception { EncryptionMaterialsRequest req = EncryptionMaterialsRequest.newBuilder().setCommitmentPolicy(commitmentPolicy).build(); EncryptionMaterials result = new DefaultCryptoMaterialsManager(mk1).getMaterialsForEncrypt(req); assertNotNull(result.getCleartextDataKey()); assertNotNull(result.getEncryptionContext()); assertEquals( CryptoAlgorithm.ALG_AES_256_GCM_HKDF_SHA512_COMMIT_KEY_ECDSA_P384, result.getAlgorithm()); assertEquals(1, result.getEncryptedDataKeys().size()); assertEquals(1, result.getMasterKeys().size()); assertEquals(mk1, result.getMasterKeys().get(0)); } @Test public void encrypt_testNonCommittingDefaultAlgorithm() throws Exception { EncryptionMaterialsRequest req = EncryptionMaterialsRequest.newBuilder() .setCommitmentPolicy(CommitmentPolicy.ForbidEncryptAllowDecrypt) .build(); EncryptionMaterials result = new DefaultCryptoMaterialsManager(mk1).getMaterialsForEncrypt(req); assertEquals( CryptoAlgorithm.ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA384_ECDSA_P384, result.getAlgorithm()); } @Test public void encrypt_testCommittingDefaultAlgorithm() throws Exception { final List<CommitmentPolicy> requireWritePolicies = Arrays.asList( CommitmentPolicy.RequireEncryptRequireDecrypt, CommitmentPolicy.RequireEncryptAllowDecrypt); for (CommitmentPolicy policy : requireWritePolicies) { EncryptionMaterialsRequest req = EncryptionMaterialsRequest.newBuilder().setCommitmentPolicy(policy).build(); EncryptionMaterials result = new DefaultCryptoMaterialsManager(mk1).getMaterialsForEncrypt(req); assertEquals( CryptoAlgorithm.ALG_AES_256_GCM_HKDF_SHA512_COMMIT_KEY_ECDSA_P384, result.getAlgorithm()); } } @Test public void encrypt_noSignatureKeyOnUnsignedAlgo() throws Exception { CryptoAlgorithm[] algorithms = new CryptoAlgorithm[] { CryptoAlgorithm.ALG_AES_128_GCM_IV12_TAG16_HKDF_SHA256, CryptoAlgorithm.ALG_AES_128_GCM_IV12_TAG16_NO_KDF, CryptoAlgorithm.ALG_AES_192_GCM_IV12_TAG16_HKDF_SHA256, CryptoAlgorithm.ALG_AES_192_GCM_IV12_TAG16_NO_KDF, CryptoAlgorithm.ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA256, CryptoAlgorithm.ALG_AES_256_GCM_IV12_TAG16_NO_KDF, CryptoAlgorithm.ALG_AES_256_GCM_HKDF_SHA512_COMMIT_KEY }; for (CryptoAlgorithm algo : algorithms) { EncryptionMaterialsRequest req = EncryptionMaterialsRequest.newBuilder() .setCommitmentPolicy(commitmentPolicy) .setRequestedAlgorithm(algo) .build(); EncryptionMaterials result = new DefaultCryptoMaterialsManager(mk1).getMaterialsForEncrypt(req); assertNull(result.getTrailingSignatureKey()); assertEquals(0, result.getEncryptionContext().size()); assertEquals(algo, result.getAlgorithm()); } } @Test public void encrypt_hasSignatureKeyForSignedAlgo() throws Exception { CryptoAlgorithm[] algorithms = new CryptoAlgorithm[] { CryptoAlgorithm.ALG_AES_128_GCM_IV12_TAG16_HKDF_SHA256_ECDSA_P256, CryptoAlgorithm.ALG_AES_192_GCM_IV12_TAG16_HKDF_SHA384_ECDSA_P384, CryptoAlgorithm.ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA384_ECDSA_P384, CryptoAlgorithm.ALG_AES_256_GCM_HKDF_SHA512_COMMIT_KEY_ECDSA_P384 }; for (CryptoAlgorithm algo : algorithms) { EncryptionMaterialsRequest req = EncryptionMaterialsRequest.newBuilder() .setCommitmentPolicy(commitmentPolicy) .setRequestedAlgorithm(algo) .build(); EncryptionMaterials result = new DefaultCryptoMaterialsManager(mk1).getMaterialsForEncrypt(req); assertNotNull(result.getTrailingSignatureKey()); assertEquals(1, result.getEncryptionContext().size()); assertNotNull(result.getEncryptionContext().get(Constants.EC_PUBLIC_KEY_FIELD)); assertEquals(algo, result.getAlgorithm()); } } @Test public void encrypt_dispatchesMultipleMasterKeys() throws Exception { MasterKey<?> mk1_spy = spy(mk1); MasterKey<?> mk2_spy = spy(mk2); DataKey[] mk1_datakey = new DataKey[1]; doAnswer( invocation -> { Object dk = invocation.callRealMethod(); mk1_datakey[0] = (DataKey) dk; return dk; }) .when(mk1_spy) .generateDataKey(any(), any()); MasterKeyProvider<?> mkp = buildMultiProvider(mk1_spy, mk2_spy); EncryptionMaterialsRequest req = EncryptionMaterialsRequest.newBuilder() .setCommitmentPolicy(commitmentPolicy) .setContext(singletonMap("foo", "bar")) .build(); EncryptionMaterials result = new DefaultCryptoMaterialsManager(mkp).getMaterialsForEncrypt(req); //noinspection unchecked verify(mk1_spy) .generateDataKey( any(), // there's a weird generics issue here without downcasting to (Map) (Map) argThat((Map m) -> Objects.equals(m.get("foo"), "bar"))); //noinspection unchecked verify(mk2_spy) .encryptDataKey( any(), (Map) argThat((Map m) -> Objects.equals(m.get("foo"), "bar")), same(mk1_datakey[0])); assertArrayEquals( mk1_datakey[0].getKey().getEncoded(), result.getCleartextDataKey().getEncoded()); } @Test public void encrypt_forwardsPlaintextWhenAvailable() throws Exception { MasterKey<?> mk1_spy = spy(mk1); EncryptionMaterialsRequest request = EncryptionMaterialsRequest.newBuilder() .setCommitmentPolicy(commitmentPolicy) .setPlaintext(new byte[1]) .build(); new DefaultCryptoMaterialsManager(mk1_spy).getMaterialsForEncrypt(request); verify(mk1_spy) .getMasterKeysForEncryption( argThat(req -> Arrays.equals(req.getPlaintext(), new byte[1]) && !req.isStreaming())); } @Test public void encrypt_forwardsPlaintextSizeWhenAvailable() throws Exception { MasterKey<?> mk1_spy = spy(mk1); EncryptionMaterialsRequest request = EncryptionMaterialsRequest.newBuilder() .setCommitmentPolicy(commitmentPolicy) .setPlaintextSize(1) .build(); new DefaultCryptoMaterialsManager(mk1_spy).getMaterialsForEncrypt(request); verify(mk1_spy) .getMasterKeysForEncryption(argThat(req -> req.getSize() == 1 && !req.isStreaming())); } @Test public void encrypt_setsStreamingWhenNoSizeAvailable() throws Exception { MasterKey<?> mk1_spy = spy(mk1); EncryptionMaterialsRequest request = EncryptionMaterialsRequest.newBuilder().setCommitmentPolicy(commitmentPolicy).build(); new DefaultCryptoMaterialsManager(mk1_spy).getMaterialsForEncrypt(request); verify(mk1_spy).getMasterKeysForEncryption(argThat(MasterKeyRequest::isStreaming)); } @Test(expected = IllegalArgumentException.class) public void encrypt_whenECContextKeyPresent_throws() throws Exception { EncryptionMaterialsRequest req = EncryptionMaterialsRequest.newBuilder() .setCommitmentPolicy(commitmentPolicy) .setRequestedAlgorithm( CryptoAlgorithm.ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA384_ECDSA_P384) .setContext(singletonMap(Constants.EC_PUBLIC_KEY_FIELD, "some EC key")) .build(); new DefaultCryptoMaterialsManager(mk1).getMaterialsForEncrypt(req); } @Test(expected = IllegalArgumentException.class) public void encrypt_whenNoMasterKeys_throws() throws Exception { EncryptionMaterialsRequest req = EncryptionMaterialsRequest.newBuilder().setCommitmentPolicy(commitmentPolicy).build(); new DefaultCryptoMaterialsManager( new MasterKeyProvider() { @Override public String getDefaultProviderId() { return "provider ID"; } @Override public MasterKey getMasterKey(String provider, String keyId) throws UnsupportedProviderException, NoSuchMasterKeyException { throw new NoSuchMasterKeyException(); } @Override public List getMasterKeysForEncryption(MasterKeyRequest request) { return Collections.emptyList(); } @Override public DataKey decryptDataKey( CryptoAlgorithm algorithm, Collection encryptedDataKeys, Map encryptionContext) throws UnsupportedProviderException, AwsCryptoException { return null; } }) .getMaterialsForEncrypt(req); } private EncryptionMaterials easyGenMaterials( Consumer<EncryptionMaterialsRequest.Builder> customizer) { EncryptionMaterialsRequest.Builder request = EncryptionMaterialsRequest.newBuilder().setCommitmentPolicy(commitmentPolicy); customizer.accept(request); return new DefaultCryptoMaterialsManager(mk1).getMaterialsForEncrypt(request.build()); } private DecryptionMaterialsRequest decryptReqFromMaterials(EncryptionMaterials result) { return DecryptionMaterialsRequest.newBuilder() .setEncryptionContext(result.getEncryptionContext()) .setEncryptedDataKeys(result.getEncryptedDataKeys()) .setAlgorithm(result.getAlgorithm()) .build(); } @Test public void decrypt_testSimpleRoundTrip() throws Exception { for (CryptoAlgorithm algorithm : CryptoAlgorithm.values()) { CommitmentPolicy policy = algorithm.isCommitting() ? CommitmentPolicy.RequireEncryptRequireDecrypt : CommitmentPolicy.ForbidEncryptAllowDecrypt; EncryptionMaterials encryptMaterials = easyGenMaterials(builder -> builder.setRequestedAlgorithm(algorithm)); DecryptionMaterials decryptMaterials = new DefaultCryptoMaterialsManager(mk1) .decryptMaterials(decryptReqFromMaterials(encryptMaterials)); assertArrayEquals( decryptMaterials.getDataKey().getKey().getEncoded(), encryptMaterials.getCleartextDataKey().getEncoded()); if (encryptMaterials.getTrailingSignatureKey() == null) { assertNull(decryptMaterials.getTrailingSignatureKey()); } else { Signature sig = Signature.getInstance( TrailingSignatureAlgorithm.forCryptoAlgorithm(algorithm).getHashAndSignAlgorithm()); sig.initSign(encryptMaterials.getTrailingSignatureKey()); byte[] data = "hello world".getBytes(StandardCharsets.UTF_8); sig.update(data); byte[] signature = sig.sign(); sig.initVerify(decryptMaterials.getTrailingSignatureKey()); sig.update(data); sig.verify(signature); } } } @Test(expected = CannotUnwrapDataKeyException.class) public void decrypt_onDecryptFailure() throws Exception { new DefaultCryptoMaterialsManager(mock(MasterKeyProvider.class)) .decryptMaterials(decryptReqFromMaterials(easyGenMaterials(ignored -> {}))); } @Test public void decrypt_whenTrailingSigMissing_throwsException() throws Exception { for (CryptoAlgorithm algorithm : CryptoAlgorithm.values()) { // Only test algorithms without key commitment if (algorithm.getMessageFormatVersion() != 1) { continue; } if (algorithm.getTrailingSignatureLength() == 0) { continue; } EncryptionMaterials encryptMaterials = easyGenMaterials(builder -> builder.setRequestedAlgorithm(algorithm)); DecryptionMaterialsRequest request = DecryptionMaterialsRequest.newBuilder() .setEncryptedDataKeys(encryptMaterials.getEncryptedDataKeys()) .setAlgorithm(algorithm) .setEncryptionContext(Collections.emptyMap()) .build(); try { new DefaultCryptoMaterialsManager(mk1).decryptMaterials(request); fail("expected exception"); } catch (AwsCryptoException e) { // ok continue; } } } }
704
0
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk/FastTestsOnlySuite.java
package com.amazonaws.encryptionsdk; import java.util.concurrent.TimeUnit; import org.junit.ClassRule; import org.junit.experimental.categories.Categories; import org.junit.rules.TestRule; import org.junit.rules.Timeout; import org.junit.runner.Description; import org.junit.runner.RunWith; import org.junit.runner.Runner; import org.junit.runners.Suite; import org.junit.runners.model.InitializationError; import org.junit.runners.model.RunnerBuilder; import org.junit.runners.model.Statement; /** * This test suite is intended to assist in rapid development; it filters out some of the slower, * more exhaustive tests in the overall test suite to allow for a rapid edit-test cycle. */ @RunWith(FastTestsOnlySuite.CustomRunner.class) @Suite.SuiteClasses({AllTestsSuite.class}) @Categories.ExcludeCategory(SlowTestCategory.class) public class FastTestsOnlySuite { private static InheritableThreadLocal<Boolean> IS_FAST_TEST_SUITE_ACTIVE = new InheritableThreadLocal<Boolean>() { @Override protected Boolean initialValue() { return false; } }; // This method is used to adjust DataProviders to provide a smaller subset of their test cases // when the fast tests // are selected public static boolean isFastTestSuiteActive() { return IS_FAST_TEST_SUITE_ACTIVE.get(); } // Require that this fast suite completes relatively quickly. If you're seeing this timeout get // hit, it's time to // pare down tests some more. As a general rule of thumb, we should avoid any single test taking // more than 10s, and // try to keep the number of such slow tests to a minimum. @ClassRule public static Timeout timeout = new Timeout(2, TimeUnit.MINUTES); @ClassRule public static EnableFastSuite enableFastSuite = new EnableFastSuite(); // TestRules run over the execution of tests, but not over the generation of parameterized test // data... private static class EnableFastSuite implements TestRule { @Override public Statement apply(Statement base, Description description) { return new Statement() { @Override public void evaluate() throws Throwable { Boolean oldValue = IS_FAST_TEST_SUITE_ACTIVE.get(); try { IS_FAST_TEST_SUITE_ACTIVE.set(true); base.evaluate(); } finally { IS_FAST_TEST_SUITE_ACTIVE.set(oldValue); } } }; } } // ... so we also need a custom TestRunner that will pass the flag on to the parameterized test // data generators. public static class CustomRunner extends Categories { public CustomRunner(Class<?> klass, RunnerBuilder builder) throws InitializationError { super( klass, new RunnerBuilder() { @Override public Runner runnerForClass(Class<?> testClass) throws Throwable { Boolean oldValue = IS_FAST_TEST_SUITE_ACTIVE.get(); try { IS_FAST_TEST_SUITE_ACTIVE.set(true); Runner r = builder.runnerForClass(testClass); return r; } finally { IS_FAST_TEST_SUITE_ACTIVE.set(oldValue); } } }); } } }
705
0
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk/AwsCryptoTest.java
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package com.amazonaws.encryptionsdk; import static com.amazonaws.encryptionsdk.FastTestsOnlySuite.isFastTestSuiteActive; import static com.amazonaws.encryptionsdk.TestUtils.assertThrows; import static java.util.Collections.singletonMap; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.reset; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import com.amazonaws.encryptionsdk.caching.CachingCryptoMaterialsManager; import com.amazonaws.encryptionsdk.caching.LocalCryptoMaterialsCache; import com.amazonaws.encryptionsdk.exception.AwsCryptoException; import com.amazonaws.encryptionsdk.exception.BadCiphertextException; import com.amazonaws.encryptionsdk.internal.StaticMasterKey; import com.amazonaws.encryptionsdk.internal.TestIOUtils; import com.amazonaws.encryptionsdk.internal.Utils; import com.amazonaws.encryptionsdk.jce.JceMasterKey; import com.amazonaws.encryptionsdk.model.CiphertextType; import com.amazonaws.encryptionsdk.model.DecryptionMaterials; import com.amazonaws.encryptionsdk.model.DecryptionMaterialsRequest; import com.amazonaws.encryptionsdk.model.EncryptionMaterials; import com.amazonaws.encryptionsdk.model.EncryptionMaterialsRequest; import com.amazonaws.encryptionsdk.multi.MultipleProviderFactory; import com.amazonaws.util.IOUtils; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Arrays; import java.util.EnumSet; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; import org.junit.Before; import org.junit.Test; public class AwsCryptoTest { private StaticMasterKey masterKeyProvider; private AwsCrypto forbidCommitmentClient_; private AwsCrypto encryptionClient_; private AwsCrypto noMaxEdksClient_; private AwsCrypto maxEdksClient_; private static final CommitmentPolicy commitmentPolicy = TestUtils.DEFAULT_TEST_COMMITMENT_POLICY; private static final int MESSAGE_FORMAT_MAX_EDKS = (1 << 16) - 1; List<CommitmentPolicy> requireWriteCommitmentPolicies = Arrays.asList( CommitmentPolicy.RequireEncryptAllowDecrypt, CommitmentPolicy.RequireEncryptRequireDecrypt); @Before public void init() { masterKeyProvider = spy(new StaticMasterKey("testmaterial")); forbidCommitmentClient_ = AwsCrypto.builder() .withCommitmentPolicy(CommitmentPolicy.ForbidEncryptAllowDecrypt) .build(); forbidCommitmentClient_.setEncryptionAlgorithm( CryptoAlgorithm.ALG_AES_128_GCM_IV12_TAG16_HKDF_SHA256); encryptionClient_ = AwsCrypto.standard(); encryptionClient_.setEncryptionAlgorithm( CryptoAlgorithm.ALG_AES_256_GCM_HKDF_SHA512_COMMIT_KEY); noMaxEdksClient_ = AwsCrypto.builder() .withCommitmentPolicy(CommitmentPolicy.RequireEncryptAllowDecrypt) .withEncryptionAlgorithm(CryptoAlgorithm.ALG_AES_256_GCM_HKDF_SHA512_COMMIT_KEY) .build(); maxEdksClient_ = AwsCrypto.builder() .withMaxEncryptedDataKeys(3) .withCommitmentPolicy(CommitmentPolicy.RequireEncryptAllowDecrypt) .withEncryptionAlgorithm(CryptoAlgorithm.ALG_AES_256_GCM_HKDF_SHA512_COMMIT_KEY) .build(); } private void doEncryptDecrypt( final CryptoAlgorithm cryptoAlg, final int byteSize, final int frameSize) { final byte[] plaintextBytes = new byte[byteSize]; final Map<String, String> encryptionContext = new HashMap<String, String>(1); encryptionContext.put("ENC1", "Encrypt-decrypt test with %d" + byteSize); AwsCrypto client = cryptoAlg.isCommitting() ? encryptionClient_ : forbidCommitmentClient_; client.setEncryptionAlgorithm(cryptoAlg); client.setEncryptionFrameSize(frameSize); final byte[] cipherText = client.encryptData(masterKeyProvider, plaintextBytes, encryptionContext).getResult(); final byte[] decryptedText = client.decryptData(masterKeyProvider, cipherText).getResult(); assertArrayEquals("Bad encrypt/decrypt for " + cryptoAlg, plaintextBytes, decryptedText); } private void doTamperedEncryptDecrypt( final CryptoAlgorithm cryptoAlg, final int byteSize, final int frameSize) { final byte[] plaintextBytes = new byte[byteSize]; final Map<String, String> encryptionContext = new HashMap<String, String>(1); encryptionContext.put("ENC1", "Encrypt-decrypt test with %d" + byteSize); AwsCrypto client = cryptoAlg.isCommitting() ? encryptionClient_ : forbidCommitmentClient_; client.setEncryptionAlgorithm(cryptoAlg); client.setEncryptionFrameSize(frameSize); final byte[] cipherText = client.encryptData(masterKeyProvider, plaintextBytes, encryptionContext).getResult(); cipherText[cipherText.length - 2] ^= (byte) 0xff; try { client.decryptData(masterKeyProvider, cipherText).getResult(); fail("Expected BadCiphertextException"); } catch (final BadCiphertextException ex) { // Expected exception } } private void doTruncatedEncryptDecrypt( final CryptoAlgorithm cryptoAlg, final int byteSize, final int frameSize) { final byte[] plaintextBytes = new byte[byteSize]; final Map<String, String> encryptionContext = new HashMap<>(1); encryptionContext.put("ENC1", "Encrypt-decrypt test with %d" + byteSize); AwsCrypto client = cryptoAlg.isCommitting() ? encryptionClient_ : forbidCommitmentClient_; client.setEncryptionAlgorithm(cryptoAlg); client.setEncryptionFrameSize(frameSize); final byte[] cipherText = client.encryptData(masterKeyProvider, plaintextBytes, encryptionContext).getResult(); final byte[] truncatedCipherText = Arrays.copyOf(cipherText, cipherText.length - 1); try { client.decryptData(masterKeyProvider, truncatedCipherText).getResult(); fail("Expected BadCiphertextException"); } catch (final BadCiphertextException ex) { // Expected exception } } private void doEncryptDecryptWithParsedCiphertext( final CryptoAlgorithm cryptoAlg, final int byteSize, final int frameSize) { final byte[] plaintextBytes = new byte[byteSize]; final Map<String, String> encryptionContext = new HashMap<String, String>(1); encryptionContext.put("ENC1", "Encrypt-decrypt test with %d" + byteSize); AwsCrypto client = cryptoAlg.isCommitting() ? encryptionClient_ : forbidCommitmentClient_; client.setEncryptionAlgorithm(cryptoAlg); client.setEncryptionFrameSize(frameSize); final byte[] cipherText = client.encryptData(masterKeyProvider, plaintextBytes, encryptionContext).getResult(); ParsedCiphertext pCt = new ParsedCiphertext(cipherText); assertEquals(client.getEncryptionAlgorithm(), pCt.getCryptoAlgoId()); assertEquals(CiphertextType.CUSTOMER_AUTHENTICATED_ENCRYPTED_DATA, pCt.getType()); assertEquals(1, pCt.getEncryptedKeyBlobCount()); assertEquals(pCt.getEncryptedKeyBlobCount(), pCt.getEncryptedKeyBlobs().size()); assertEquals( masterKeyProvider.getProviderId(), pCt.getEncryptedKeyBlobs().get(0).getProviderId()); for (Map.Entry<String, String> e : encryptionContext.entrySet()) { assertEquals(e.getValue(), pCt.getEncryptionContextMap().get(e.getKey())); } final byte[] decryptedText = client.decryptData(masterKeyProvider, pCt).getResult(); assertArrayEquals(plaintextBytes, decryptedText); } @Test public void encryptDecrypt() { for (final CryptoAlgorithm cryptoAlg : EnumSet.allOf(CryptoAlgorithm.class)) { // Only test with crypto algs without commitment, since those // are the only ones we can encrypt with if (cryptoAlg.getMessageFormatVersion() != 1) { continue; } final int[] frameSizeToTest = TestUtils.getFrameSizesToTest(cryptoAlg); for (int i = 0; i < frameSizeToTest.length; i++) { final int frameSize = frameSizeToTest[i]; int[] bytesToTest = { 0, 1, frameSize - 1, frameSize, frameSize + 1, (int) (frameSize * 1.5), frameSize * 2, 1000000 }; for (int j = 0; j < bytesToTest.length; j++) { final int byteSize = bytesToTest[j]; if (byteSize > 500_000 && isFastTestSuiteActive()) { continue; } if (byteSize >= 0) { doEncryptDecrypt(cryptoAlg, byteSize, frameSize); } } } } } @Test public void encryptDecryptWithBadSignature() { for (final CryptoAlgorithm cryptoAlg : EnumSet.allOf(CryptoAlgorithm.class)) { // Only test with crypto algs without commitment, since those // are the only ones we can encrypt with if (cryptoAlg.getMessageFormatVersion() != 1) { continue; } if (cryptoAlg.getTrailingSignatureAlgo() == null) { continue; } final int[] frameSizeToTest = TestUtils.getFrameSizesToTest(cryptoAlg); for (int i = 0; i < frameSizeToTest.length; i++) { final int frameSize = frameSizeToTest[i]; int[] bytesToTest = { 0, 1, frameSize - 1, frameSize, frameSize + 1, (int) (frameSize * 1.5), frameSize * 2, 1000000 }; for (int j = 0; j < bytesToTest.length; j++) { final int byteSize = bytesToTest[j]; if (byteSize > 500_000 && isFastTestSuiteActive()) { continue; } if (byteSize >= 0) { doTamperedEncryptDecrypt(cryptoAlg, byteSize, frameSize); } } } } } @Test public void encryptDecryptWithTruncatedCiphertext() { for (final CryptoAlgorithm cryptoAlg : EnumSet.allOf(CryptoAlgorithm.class)) { // Only test with crypto algs without commitment, since those // are the only ones we can encrypt with if (cryptoAlg.getMessageFormatVersion() != 1) { continue; } final int[] frameSizeToTest = TestUtils.getFrameSizesToTest(cryptoAlg); for (int i = 0; i < frameSizeToTest.length; i++) { final int frameSize = frameSizeToTest[i]; int[] bytesToTest = { 0, 1, frameSize - 1, frameSize, frameSize + 1, (int) (frameSize * 1.5), frameSize * 2, 1000000 }; for (int j = 0; j < bytesToTest.length; j++) { final int byteSize = bytesToTest[j]; if (byteSize > 500_000) { continue; } if (byteSize >= 0) { doTruncatedEncryptDecrypt(cryptoAlg, byteSize, frameSize); } } } } } @Test public void encryptDecryptWithParsedCiphertext() { for (final CryptoAlgorithm cryptoAlg : EnumSet.allOf(CryptoAlgorithm.class)) { final int[] frameSizeToTest = TestUtils.getFrameSizesToTest(cryptoAlg); for (int i = 0; i < frameSizeToTest.length; i++) { final int frameSize = frameSizeToTest[i]; int[] bytesToTest = { 0, 1, frameSize - 1, frameSize, frameSize + 1, (int) (frameSize * 1.5), frameSize * 2, 1000000 }; for (int j = 0; j < bytesToTest.length; j++) { final int byteSize = bytesToTest[j]; if (byteSize > 500_000 && isFastTestSuiteActive()) { continue; } if (byteSize >= 0) { doEncryptDecryptWithParsedCiphertext(cryptoAlg, byteSize, frameSize); } } } } } @Test public void encryptDecryptWithCustomManager() throws Exception { boolean[] didDecrypt = new boolean[] {false}; CryptoMaterialsManager manager = new CryptoMaterialsManager() { @Override public EncryptionMaterials getMaterialsForEncrypt(EncryptionMaterialsRequest request) { request = request.toBuilder().setContext(singletonMap("foo", "bar")).build(); EncryptionMaterials encryptionMaterials = new DefaultCryptoMaterialsManager(masterKeyProvider) .getMaterialsForEncrypt(request); return encryptionMaterials; } @Override public DecryptionMaterials decryptMaterials(DecryptionMaterialsRequest request) { didDecrypt[0] = true; return new DefaultCryptoMaterialsManager(masterKeyProvider).decryptMaterials(request); } }; byte[] plaintext = new byte[100]; CryptoResult<byte[], ?> ciphertext = encryptionClient_.encryptData(manager, plaintext); assertEquals("bar", ciphertext.getEncryptionContext().get("foo")); // TODO decrypt assertFalse(didDecrypt[0]); CryptoResult<byte[], ?> plaintextResult = encryptionClient_.decryptData(manager, ciphertext.getResult()); assertArrayEquals(plaintext, plaintextResult.getResult()); assertTrue(didDecrypt[0]); } @Test public void whenCustomCMMIgnoresAlgorithm_throws() throws Exception { boolean[] didDecrypt = new boolean[] {false}; CryptoMaterialsManager manager = new CryptoMaterialsManager() { @Override public EncryptionMaterials getMaterialsForEncrypt(EncryptionMaterialsRequest request) { request = request.toBuilder().setRequestedAlgorithm(null).build(); EncryptionMaterials encryptionMaterials = new DefaultCryptoMaterialsManager(masterKeyProvider) .getMaterialsForEncrypt(request); return encryptionMaterials; } @Override public DecryptionMaterials decryptMaterials(DecryptionMaterialsRequest request) { didDecrypt[0] = true; return new DefaultCryptoMaterialsManager(masterKeyProvider).decryptMaterials(request); } }; encryptionClient_.setEncryptionAlgorithm( CryptoAlgorithm.ALG_AES_256_GCM_HKDF_SHA512_COMMIT_KEY); byte[] plaintext = new byte[100]; assertThrows(AwsCryptoException.class, () -> encryptionClient_.encryptData(manager, plaintext)); assertThrows( AwsCryptoException.class, () -> encryptionClient_.estimateCiphertextSize(manager, 12345)); assertThrows( AwsCryptoException.class, () -> encryptionClient_ .createEncryptingStream(manager, new ByteArrayOutputStream()) .write(0)); assertThrows( AwsCryptoException.class, () -> encryptionClient_ .createEncryptingStream(manager, new ByteArrayInputStream(new byte[1024 * 1024])) .read()); } @Test public void whenCustomCMMUsesCommittingAlgorithmWithForbidPolicy_throws() throws Exception { CryptoMaterialsManager manager = new CryptoMaterialsManager() { @Override public EncryptionMaterials getMaterialsForEncrypt(EncryptionMaterialsRequest request) { EncryptionMaterials encryptionMaterials = new DefaultCryptoMaterialsManager(masterKeyProvider) .getMaterialsForEncrypt(request); return encryptionMaterials.toBuilder() .setAlgorithm(CryptoAlgorithm.ALG_AES_256_GCM_HKDF_SHA512_COMMIT_KEY_ECDSA_P384) .build(); } @Override public DecryptionMaterials decryptMaterials(DecryptionMaterialsRequest request) { return new DefaultCryptoMaterialsManager(masterKeyProvider).decryptMaterials(request); } }; // create client with null encryption algorithm and ForbidEncrypt policy final AwsCrypto client = AwsCrypto.builder() .withCommitmentPolicy(CommitmentPolicy.ForbidEncryptAllowDecrypt) .build(); byte[] plaintext = new byte[100]; assertThrows(AwsCryptoException.class, () -> client.encryptData(manager, plaintext)); assertThrows(AwsCryptoException.class, () -> client.estimateCiphertextSize(manager, 12345)); assertThrows( AwsCryptoException.class, () -> client.createEncryptingStream(manager, new ByteArrayOutputStream()).write(0)); assertThrows( AwsCryptoException.class, () -> client .createEncryptingStream(manager, new ByteArrayInputStream(new byte[1024 * 1024])) .read()); } @Test public void whenDecrypting_invokesMKPOnce() throws Exception { byte[] data = encryptionClient_.encryptData(masterKeyProvider, new byte[1]).getResult(); reset(masterKeyProvider); encryptionClient_.decryptData(masterKeyProvider, data); verify(masterKeyProvider, times(1)).decryptDataKey(any(), any(), any()); } private void doEstimateCiphertextSize( final CryptoAlgorithm cryptoAlg, final int inLen, final int frameSize) { final byte[] plaintext = TestIOUtils.generateRandomPlaintext(inLen); final Map<String, String> encryptionContext = new HashMap<String, String>(1); encryptionContext.put("ENC1", "Ciphertext size estimation test with " + inLen); AwsCrypto client = cryptoAlg.isCommitting() ? encryptionClient_ : forbidCommitmentClient_; client.setEncryptionAlgorithm(cryptoAlg); client.setEncryptionFrameSize(frameSize); final long estimatedCiphertextSize = client.estimateCiphertextSize(masterKeyProvider, inLen, encryptionContext); final byte[] cipherText = client.encryptData(masterKeyProvider, plaintext, encryptionContext).getResult(); // The estimate should be close (within 16 bytes) and never less than reality final String errMsg = "Bad estimation for " + cryptoAlg + " expected: <" + estimatedCiphertextSize + "> but was: <" + cipherText.length + ">"; assertTrue(errMsg, estimatedCiphertextSize - cipherText.length >= 0); assertTrue(errMsg, estimatedCiphertextSize - cipherText.length <= 16); } @Test public void estimateCiphertextSize() { for (final CryptoAlgorithm cryptoAlg : EnumSet.allOf(CryptoAlgorithm.class)) { // Only test with crypto algs without commitment, since those // are the only ones we can encrypt with if (cryptoAlg.getMessageFormatVersion() != 1) { continue; } final int[] frameSizeToTest = TestUtils.getFrameSizesToTest(cryptoAlg); for (int i = 0; i < frameSizeToTest.length; i++) { final int frameSize = frameSizeToTest[i]; int[] bytesToTest = { 0, 1, frameSize - 1, frameSize, frameSize + 1, (int) (frameSize * 1.5), frameSize * 2, 1000000 }; for (int j = 0; j < bytesToTest.length; j++) { final int byteSize = bytesToTest[j]; if (byteSize > 500_000 && isFastTestSuiteActive()) { continue; } if (byteSize >= 0) { doEstimateCiphertextSize(cryptoAlg, byteSize, frameSize); } } } } } @Test public void estimateCiphertextSizeWithoutEncContext() { final int inLen = 1000000; final byte[] plaintext = TestIOUtils.generateRandomPlaintext(inLen); encryptionClient_.setEncryptionFrameSize(AwsCrypto.getDefaultFrameSize()); final long estimatedCiphertextSize = encryptionClient_.estimateCiphertextSize(masterKeyProvider, inLen); final byte[] cipherText = encryptionClient_.encryptData(masterKeyProvider, plaintext).getResult(); final String errMsg = "Bad estimation expected: <" + estimatedCiphertextSize + "> but was: <" + cipherText.length + ">"; assertTrue(errMsg, estimatedCiphertextSize - cipherText.length >= 0); assertTrue(errMsg, estimatedCiphertextSize - cipherText.length <= 16); } @Test public void estimateCiphertextSize_usesCachedKeys() throws Exception { // Make sure estimateCiphertextSize works with cached CMMs CryptoMaterialsManager cmm = spy(new DefaultCryptoMaterialsManager(masterKeyProvider)); CachingCryptoMaterialsManager cache = CachingCryptoMaterialsManager.newBuilder() .withBackingMaterialsManager(cmm) .withMaxAge(Long.MAX_VALUE, TimeUnit.SECONDS) .withCache(new LocalCryptoMaterialsCache(1)) .withMessageUseLimit(9999) .withByteUseLimit(501) .build(); // These estimates should be cached, and should not consume any bytes from the byte use limit. encryptionClient_.estimateCiphertextSize(cache, 500, new HashMap<>()); encryptionClient_.estimateCiphertextSize(cache, 500, new HashMap<>()); encryptionClient_.encryptData(cache, new byte[500]); verify(cmm, times(1)).getMaterialsForEncrypt(any()); } @Test public void encryptDecryptWithoutEncContext() { final int ptSize = 1000000; // 1MB final byte[] plaintextBytes = TestIOUtils.generateRandomPlaintext(ptSize); final byte[] cipherText = encryptionClient_.encryptData(masterKeyProvider, plaintextBytes).getResult(); final byte[] decryptedText = encryptionClient_.decryptData(masterKeyProvider, cipherText).getResult(); assertArrayEquals(plaintextBytes, decryptedText); } @Test public void encryptDecryptString() { final int ptSize = 1000000; // 1MB final String plaintextString = TestIOUtils.generateRandomString(ptSize); final Map<String, String> encryptionContext = new HashMap<String, String>(1); encryptionContext.put("ENC1", "Test Encryption Context"); final String ciphertext = encryptionClient_ .encryptString(masterKeyProvider, plaintextString, encryptionContext) .getResult(); final String decryptedText = encryptionClient_.decryptString(masterKeyProvider, ciphertext).getResult(); assertEquals(plaintextString, decryptedText); } @Test public void encryptDecryptStringWithoutEncContext() { final int ptSize = 1000000; // 1MB final String plaintextString = TestIOUtils.generateRandomString(ptSize); final String cipherText = encryptionClient_.encryptString(masterKeyProvider, plaintextString).getResult(); final String decryptedText = encryptionClient_.decryptString(masterKeyProvider, cipherText).getResult(); assertEquals(plaintextString, decryptedText); } @Test public void encryptBytesDecryptString() { final int ptSize = 1000000; // 1MB final String plaintext = TestIOUtils.generateRandomString(ptSize); final Map<String, String> encryptionContext = new HashMap<String, String>(1); encryptionContext.put("ENC1", "Test Encryption Context"); final byte[] cipherText = encryptionClient_ .encryptData( masterKeyProvider, plaintext.getBytes(StandardCharsets.UTF_8), encryptionContext) .getResult(); final String decryptedText = encryptionClient_ .decryptString(masterKeyProvider, Utils.encodeBase64String(cipherText)) .getResult(); assertEquals(plaintext, decryptedText); } @Test public void encryptStringDecryptBytes() { final int ptSize = 1000000; // 1MB final byte[] plaintextBytes = TestIOUtils.generateRandomPlaintext(ptSize); final String plaintextString = new String(plaintextBytes, StandardCharsets.UTF_8); final Map<String, String> encryptionContext = new HashMap<String, String>(1); encryptionContext.put("ENC1", "Test Encryption Context"); final String ciphertext = encryptionClient_ .encryptString(masterKeyProvider, plaintextString, encryptionContext) .getResult(); final byte[] decryptedText = encryptionClient_ .decryptData(masterKeyProvider, Utils.decodeBase64String(ciphertext)) .getResult(); assertArrayEquals(plaintextString.getBytes(StandardCharsets.UTF_8), decryptedText); } @Test public void emptyEncryptionContext() { final int ptSize = 1000000; // 1MB final byte[] plaintextBytes = TestIOUtils.generateRandomPlaintext(ptSize); final Map<String, String> encryptionContext = new HashMap<String, String>(0); final byte[] cipherText = encryptionClient_ .encryptData(masterKeyProvider, plaintextBytes, encryptionContext) .getResult(); final byte[] decryptedText = encryptionClient_.decryptData(masterKeyProvider, cipherText).getResult(); assertArrayEquals(plaintextBytes, decryptedText); } @Test public void decryptMessageWithKeyCommitment() { final byte[] cipherText = Utils.decodeBase64String(TestUtils.messageWithCommitKeyBase64); JceMasterKey masterKey = TestUtils.messageWithCommitKeyMasterKey; final CryptoResult decryptedText = encryptionClient_.decryptData(masterKey, cipherText); assertEquals(TestUtils.messageWithCommitKeyCryptoAlgorithm, decryptedText.getCryptoAlgorithm()); assertArrayEquals( Utils.decodeBase64String(TestUtils.messageWithCommitKeyMessageIdBase64), decryptedText.getHeaders().getMessageId()); assertArrayEquals( Utils.decodeBase64String(TestUtils.messageWithCommitKeyCommitmentBase64), decryptedText.getHeaders().getSuiteData()); assertArrayEquals( TestUtils.messageWithCommitKeyExpectedResult.getBytes(), (byte[]) decryptedText.getResult()); } @Test public void decryptMessageWithInvalidKeyCommitment() { final byte[] cipherText = Utils.decodeBase64String(TestUtils.invalidMessageWithCommitKeyBase64); JceMasterKey masterKey = TestUtils.invalidMessageWithCommitKeyMasterKey; assertThrows( BadCiphertextException.class, "Key commitment validation failed. Key identity does not " + "match the identity asserted in the message. Halting processing of this message.", () -> encryptionClient_.decryptData(masterKey, cipherText)); } // Test that all the parameters that aren't allowed to be null (i.e. all of them) result in // immediate NPEs if // invoked with null args @Test public void assertNullChecks() throws Exception { byte[] buf = new byte[1]; HashMap<String, String> context = new HashMap<>(); MasterKeyProvider provider = masterKeyProvider; CryptoMaterialsManager cmm = new DefaultCryptoMaterialsManager(masterKeyProvider); InputStream is = new ByteArrayInputStream(new byte[0]); OutputStream os = new ByteArrayOutputStream(); byte[] ciphertext = encryptionClient_.encryptData(cmm, buf).getResult(); String stringCiphertext = encryptionClient_.encryptString(cmm, "hello, world").getResult(); TestUtils.assertNullChecks( encryptionClient_, "estimateCiphertextSize", MasterKeyProvider.class, provider, Integer.TYPE, 42, Map.class, context); TestUtils.assertNullChecks( encryptionClient_, "estimateCiphertextSize", CryptoMaterialsManager.class, cmm, Integer.TYPE, 42, Map.class, context); TestUtils.assertNullChecks( encryptionClient_, "estimateCiphertextSize", MasterKeyProvider.class, provider, Integer.TYPE, 42); TestUtils.assertNullChecks( encryptionClient_, "estimateCiphertextSize", CryptoMaterialsManager.class, cmm, Integer.TYPE, 42); TestUtils.assertNullChecks( encryptionClient_, "encryptData", MasterKeyProvider.class, provider, byte[].class, buf, Map.class, context); TestUtils.assertNullChecks( encryptionClient_, "encryptData", CryptoMaterialsManager.class, cmm, byte[].class, buf, Map.class, context); TestUtils.assertNullChecks( encryptionClient_, "encryptData", MasterKeyProvider.class, provider, byte[].class, buf); TestUtils.assertNullChecks( encryptionClient_, "encryptData", CryptoMaterialsManager.class, cmm, byte[].class, buf); TestUtils.assertNullChecks( encryptionClient_, "encryptString", MasterKeyProvider.class, provider, String.class, "", Map.class, context); TestUtils.assertNullChecks( encryptionClient_, "encryptString", CryptoMaterialsManager.class, cmm, String.class, "", Map.class, context); TestUtils.assertNullChecks( encryptionClient_, "encryptString", MasterKeyProvider.class, provider, String.class, ""); TestUtils.assertNullChecks( encryptionClient_, "encryptString", CryptoMaterialsManager.class, cmm, String.class, ""); TestUtils.assertNullChecks( encryptionClient_, "decryptData", MasterKeyProvider.class, provider, byte[].class, ciphertext); TestUtils.assertNullChecks( encryptionClient_, "decryptData", CryptoMaterialsManager.class, cmm, byte[].class, ciphertext); TestUtils.assertNullChecks( encryptionClient_, "decryptData", MasterKeyProvider.class, provider, ParsedCiphertext.class, new ParsedCiphertext(ciphertext)); TestUtils.assertNullChecks( encryptionClient_, "decryptData", CryptoMaterialsManager.class, cmm, ParsedCiphertext.class, new ParsedCiphertext(ciphertext)); TestUtils.assertNullChecks( encryptionClient_, "decryptString", MasterKeyProvider.class, provider, String.class, stringCiphertext); TestUtils.assertNullChecks( encryptionClient_, "decryptString", CryptoMaterialsManager.class, cmm, String.class, stringCiphertext); TestUtils.assertNullChecks( encryptionClient_, "createEncryptingStream", MasterKeyProvider.class, provider, OutputStream.class, os, Map.class, context); TestUtils.assertNullChecks( encryptionClient_, "createEncryptingStream", CryptoMaterialsManager.class, cmm, OutputStream.class, os, Map.class, context); TestUtils.assertNullChecks( encryptionClient_, "createEncryptingStream", MasterKeyProvider.class, provider, OutputStream.class, os); TestUtils.assertNullChecks( encryptionClient_, "createEncryptingStream", CryptoMaterialsManager.class, cmm, OutputStream.class, os); TestUtils.assertNullChecks( encryptionClient_, "createEncryptingStream", MasterKeyProvider.class, provider, InputStream.class, is, Map.class, context); TestUtils.assertNullChecks( encryptionClient_, "createEncryptingStream", CryptoMaterialsManager.class, cmm, InputStream.class, is, Map.class, context); TestUtils.assertNullChecks( encryptionClient_, "createEncryptingStream", MasterKeyProvider.class, provider, InputStream.class, is); TestUtils.assertNullChecks( encryptionClient_, "createEncryptingStream", CryptoMaterialsManager.class, cmm, InputStream.class, is); TestUtils.assertNullChecks( encryptionClient_, "createDecryptingStream", MasterKeyProvider.class, provider, OutputStream.class, os); TestUtils.assertNullChecks( encryptionClient_, "createDecryptingStream", CryptoMaterialsManager.class, cmm, OutputStream.class, os); TestUtils.assertNullChecks( encryptionClient_, "createDecryptingStream", MasterKeyProvider.class, provider, InputStream.class, is); TestUtils.assertNullChecks( encryptionClient_, "createDecryptingStream", CryptoMaterialsManager.class, cmm, InputStream.class, is); } @Test public void setValidFrameSize() throws IOException { final int setFrameSize = TestUtils.DEFAULT_TEST_CRYPTO_ALG.getBlockSize() * 2; encryptionClient_.setEncryptionFrameSize(setFrameSize); final int getFrameSize = encryptionClient_.getEncryptionFrameSize(); assertEquals(setFrameSize, getFrameSize); } @Test public void unalignedFrameSizesAreAccepted() throws IOException { final int frameSize = TestUtils.DEFAULT_TEST_CRYPTO_ALG.getBlockSize() - 1; encryptionClient_.setEncryptionFrameSize(frameSize); assertEquals(frameSize, encryptionClient_.getEncryptionFrameSize()); } @Test(expected = IllegalArgumentException.class) public void setNegativeFrameSize() throws IOException { encryptionClient_.setEncryptionFrameSize(-1); } @Test public void setCryptoAlgorithm() throws IOException { final CryptoAlgorithm setCryptoAlgorithm = CryptoAlgorithm.ALG_AES_256_GCM_HKDF_SHA512_COMMIT_KEY; encryptionClient_.setEncryptionAlgorithm(setCryptoAlgorithm); final CryptoAlgorithm getCryptoAlgorithm = encryptionClient_.getEncryptionAlgorithm(); assertEquals(setCryptoAlgorithm, getCryptoAlgorithm); } @Test(expected = NullPointerException.class) public void buildWithNullCommitmentPolicy() throws IOException { AwsCrypto.builder().withCommitmentPolicy(null).build(); } @Test public void forbidAndSetCommittingCryptoAlgorithm() throws IOException { final CryptoAlgorithm setCryptoAlgorithm = CryptoAlgorithm.ALG_AES_256_GCM_HKDF_SHA512_COMMIT_KEY; assertThrows( AwsCryptoException.class, () -> AwsCrypto.builder() .withCommitmentPolicy(CommitmentPolicy.ForbidEncryptAllowDecrypt) .build() .setEncryptionAlgorithm(setCryptoAlgorithm)); } @Test public void requireAndSetNonCommittingCryptoAlgorithm() throws IOException { final CryptoAlgorithm setCryptoAlgorithm = CryptoAlgorithm.ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA384_ECDSA_P384; // Default case assertThrows( AwsCryptoException.class, () -> AwsCrypto.standard().setEncryptionAlgorithm(setCryptoAlgorithm)); // Test explicitly for every relevant policy for (CommitmentPolicy policy : requireWriteCommitmentPolicies) { assertThrows( AwsCryptoException.class, () -> AwsCrypto.builder() .withCommitmentPolicy(policy) .build() .setEncryptionAlgorithm(setCryptoAlgorithm)); } } @Test public void forbidAndBuildWithCommittingCryptoAlgorithm() throws IOException { final CryptoAlgorithm setCryptoAlgorithm = CryptoAlgorithm.ALG_AES_256_GCM_HKDF_SHA512_COMMIT_KEY; assertThrows( AwsCryptoException.class, () -> AwsCrypto.builder() .withCommitmentPolicy(CommitmentPolicy.ForbidEncryptAllowDecrypt) .withEncryptionAlgorithm(setCryptoAlgorithm) .build()); } @Test public void requireAndBuildWithNonCommittingCryptoAlgorithm() throws IOException { final CryptoAlgorithm setCryptoAlgorithm = CryptoAlgorithm.ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA384_ECDSA_P384; // Test default case assertThrows( AwsCryptoException.class, () -> AwsCrypto.builder().withEncryptionAlgorithm(setCryptoAlgorithm).build()); // Test explicitly for every relevant policy for (CommitmentPolicy policy : requireWriteCommitmentPolicies) { assertThrows( AwsCryptoException.class, () -> AwsCrypto.builder() .withCommitmentPolicy(policy) .withEncryptionAlgorithm(setCryptoAlgorithm) .build()); } } @Test public void requireCommitmentOnDecryptFailsNonCommitting() throws IOException { // Create non-committing ciphertext forbidCommitmentClient_.setEncryptionAlgorithm( CryptoAlgorithm.ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA384_ECDSA_P384); final byte[] cipherText = forbidCommitmentClient_ .encryptData(masterKeyProvider, new byte[1], new HashMap<>()) .getResult(); // Test explicit policy set assertThrows( AwsCryptoException.class, () -> AwsCrypto.builder() .withCommitmentPolicy(CommitmentPolicy.RequireEncryptRequireDecrypt) .build() .decryptData(masterKeyProvider, cipherText)); // Test default builder behavior assertThrows( AwsCryptoException.class, () -> AwsCrypto.builder().build().decryptData(masterKeyProvider, cipherText)); // Test input stream assertThrows( AwsCryptoException.class, () -> AwsCrypto.builder() .build() .createDecryptingStream(masterKeyProvider, new ByteArrayInputStream(cipherText)) .read()); // Test output stream assertThrows( AwsCryptoException.class, () -> AwsCrypto.builder() .build() .createDecryptingStream(masterKeyProvider, new ByteArrayOutputStream()) .write(cipherText)); } @Test public void whenCustomCMMUsesNonCommittingAlgorithmWithRequirePolicy_throws() throws Exception { CryptoMaterialsManager manager = new CryptoMaterialsManager() { @Override public EncryptionMaterials getMaterialsForEncrypt(EncryptionMaterialsRequest request) { EncryptionMaterials encryptionMaterials = new DefaultCryptoMaterialsManager(masterKeyProvider) .getMaterialsForEncrypt(request); return encryptionMaterials.toBuilder() .setAlgorithm(CryptoAlgorithm.ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA384_ECDSA_P384) .build(); } @Override public DecryptionMaterials decryptMaterials(DecryptionMaterialsRequest request) { return new DefaultCryptoMaterialsManager(masterKeyProvider).decryptMaterials(request); } }; for (CommitmentPolicy policy : requireWriteCommitmentPolicies) { // create client with null encryption algorithm and a policy that requires encryption final AwsCrypto client = AwsCrypto.builder().withCommitmentPolicy(policy).build(); byte[] plaintext = new byte[100]; assertThrows(AwsCryptoException.class, () -> client.encryptData(manager, plaintext)); assertThrows(AwsCryptoException.class, () -> client.estimateCiphertextSize(manager, 12345)); assertThrows( AwsCryptoException.class, () -> client.createEncryptingStream(manager, new ByteArrayOutputStream()).write(0)); assertThrows( AwsCryptoException.class, () -> client .createEncryptingStream(manager, new ByteArrayInputStream(new byte[1024 * 1024])) .read()); } } @Test public void testDecryptMessageWithInvalidCommitment() { for (final CryptoAlgorithm cryptoAlg : CryptoAlgorithm.values()) { if (!cryptoAlg.isCommitting()) { continue; } final Map<String, String> encryptionContext = new HashMap<String, String>(1); encryptionContext.put("Commitment", "Commitment test for %s" + cryptoAlg); encryptionClient_.setEncryptionAlgorithm(cryptoAlg); byte[] plaintextBytes = new byte[16]; // Actual content doesn't matter final byte[] cipherText = encryptionClient_ .encryptData(masterKeyProvider, plaintextBytes, encryptionContext) .getResult(); // Find the commitment value ParsedCiphertext parsed = new ParsedCiphertext(cipherText); final int headerLength = parsed.getOffset(); // The commitment value is immediately prior to the header tag for v2 encrypted messages final int endOfCommitment = headerLength - parsed.getHeaderTag().length; // The commitment is 32 bytes long, but if we just index one back from the endOfCommitment we // know // that we are within it. cipherText[endOfCommitment - 1] ^= 0x01; // Tamper with the commitment value // Since commitment is verified prior to the header tag, we don't need to worry about actually // creating a colliding tag but can just verify that the exception indicates an incorrect // commitment // value. assertThrows( BadCiphertextException.class, "Key commitment validation failed. Key identity does " + "not match the identity asserted in the message. Halting processing of this message.", () -> encryptionClient_.decryptData(masterKeyProvider, cipherText)); } } @Test(expected = IllegalArgumentException.class) public void setNegativeMaxEdks() { AwsCrypto.builder().withMaxEncryptedDataKeys(-1); } @Test(expected = IllegalArgumentException.class) public void setZeroMaxEdks() { AwsCrypto.builder().withMaxEncryptedDataKeys(0); } @Test public void setValidMaxEdks() { for (final int i : new int[] { 1, 10, MESSAGE_FORMAT_MAX_EDKS, MESSAGE_FORMAT_MAX_EDKS + 1, Integer.MAX_VALUE }) { AwsCrypto.builder().withMaxEncryptedDataKeys(i); } } private MasterKeyProvider<?> providerWithEdks(int numEdks) { List<MasterKeyProvider<?>> providers = new ArrayList<>(); for (int i = 0; i < numEdks; i++) { providers.add(masterKeyProvider); } return MultipleProviderFactory.buildMultiProvider(providers); } @Test public void encryptDecryptWithLessThanMaxEdks() { MasterKeyProvider<?> provider = providerWithEdks(2); CryptoResult<byte[], ?> result = maxEdksClient_.encryptData(provider, new byte[] {1}); ParsedCiphertext ciphertext = new ParsedCiphertext(result.getResult()); assertEquals(ciphertext.getEncryptedKeyBlobCount(), 2); maxEdksClient_.decryptData(provider, ciphertext); } @Test public void encryptDecryptWithMaxEdks() { MasterKeyProvider<?> provider = providerWithEdks(3); CryptoResult<byte[], ?> result = maxEdksClient_.encryptData(provider, new byte[] {1}); ParsedCiphertext ciphertext = new ParsedCiphertext(result.getResult()); assertEquals(ciphertext.getEncryptedKeyBlobCount(), 3); maxEdksClient_.decryptData(provider, ciphertext); } @Test public void noEncryptWithMoreThanMaxEdks() { MasterKeyProvider<?> provider = providerWithEdks(4); assertThrows( AwsCryptoException.class, "Encrypted data keys exceed maxEncryptedDataKeys", () -> maxEdksClient_.encryptData(provider, new byte[] {1})); } @Test public void noDecryptWithMoreThanMaxEdks() { MasterKeyProvider<?> provider = providerWithEdks(4); CryptoResult<byte[], ?> result = noMaxEdksClient_.encryptData(provider, new byte[] {1}); ParsedCiphertext ciphertext = new ParsedCiphertext(result.getResult()); assertThrows( AwsCryptoException.class, "Ciphertext encrypted data keys exceed maxEncryptedDataKeys", () -> maxEdksClient_.decryptData(provider, ciphertext)); } @Test public void encryptDecryptWithNoMaxEdks() { MasterKeyProvider<?> provider = providerWithEdks(MESSAGE_FORMAT_MAX_EDKS); CryptoResult<byte[], ?> result = noMaxEdksClient_.encryptData(provider, new byte[] {1}); ParsedCiphertext ciphertext = new ParsedCiphertext(result.getResult()); assertEquals(ciphertext.getEncryptedKeyBlobCount(), MESSAGE_FORMAT_MAX_EDKS); noMaxEdksClient_.decryptData(provider, ciphertext); } @Test public void encryptDecryptStreamWithLessThanMaxEdks() throws IOException { MasterKeyProvider<?> provider = providerWithEdks(2); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); CryptoOutputStream<?> encryptStream = maxEdksClient_.createEncryptingStream(provider, byteArrayOutputStream); IOUtils.copy(new ByteArrayInputStream(new byte[] {1}), encryptStream); encryptStream.close(); byte[] ciphertext = byteArrayOutputStream.toByteArray(); assertEquals(new ParsedCiphertext(ciphertext).getEncryptedKeyBlobCount(), 2); byteArrayOutputStream.reset(); CryptoOutputStream<?> decryptStream = maxEdksClient_.createDecryptingStream(provider, byteArrayOutputStream); IOUtils.copy(new ByteArrayInputStream(ciphertext), decryptStream); decryptStream.close(); } @Test public void encryptDecryptStreamWithMaxEdks() throws IOException { MasterKeyProvider<?> provider = providerWithEdks(3); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); CryptoOutputStream<?> encryptStream = maxEdksClient_.createEncryptingStream(provider, byteArrayOutputStream); IOUtils.copy(new ByteArrayInputStream(new byte[] {1}), encryptStream); encryptStream.close(); byte[] ciphertext = byteArrayOutputStream.toByteArray(); assertEquals(new ParsedCiphertext(ciphertext).getEncryptedKeyBlobCount(), 3); byteArrayOutputStream.reset(); CryptoOutputStream<?> decryptStream = maxEdksClient_.createDecryptingStream(provider, byteArrayOutputStream); IOUtils.copy(new ByteArrayInputStream(ciphertext), decryptStream); decryptStream.close(); } @Test public void noEncryptStreamWithMoreThanMaxEdks() { ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); CryptoOutputStream<?> encryptStream = maxEdksClient_.createEncryptingStream(providerWithEdks(4), byteArrayOutputStream); assertThrows( AwsCryptoException.class, "Encrypted data keys exceed maxEncryptedDataKeys", () -> IOUtils.copy(new ByteArrayInputStream(new byte[] {1}), encryptStream)); } @Test public void noDecryptStreamWithMoreThanMaxEdks() throws IOException { MasterKeyProvider<?> provider = providerWithEdks(4); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); CryptoOutputStream<?> encryptStream = noMaxEdksClient_.createEncryptingStream(provider, byteArrayOutputStream); IOUtils.copy(new ByteArrayInputStream(new byte[] {1}), encryptStream); encryptStream.close(); byte[] ciphertext = byteArrayOutputStream.toByteArray(); byteArrayOutputStream.reset(); CryptoOutputStream<?> decryptStream = maxEdksClient_.createDecryptingStream(provider, byteArrayOutputStream); assertThrows( AwsCryptoException.class, "Ciphertext encrypted data keys exceed maxEncryptedDataKeys", () -> IOUtils.copy(new ByteArrayInputStream(ciphertext), decryptStream)); } @Test public void encryptDecryptStreamWithNoMaxEdks() throws IOException { MasterKeyProvider<?> provider = providerWithEdks(MESSAGE_FORMAT_MAX_EDKS); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); CryptoOutputStream<?> encryptStream = noMaxEdksClient_.createEncryptingStream(provider, byteArrayOutputStream); IOUtils.copy(new ByteArrayInputStream(new byte[] {1}), encryptStream); encryptStream.close(); byte[] ciphertext = byteArrayOutputStream.toByteArray(); assertEquals( new ParsedCiphertext(ciphertext).getEncryptedKeyBlobCount(), MESSAGE_FORMAT_MAX_EDKS); byteArrayOutputStream.reset(); CryptoOutputStream<?> decryptStream = noMaxEdksClient_.createDecryptingStream(provider, byteArrayOutputStream); IOUtils.copy(new ByteArrayInputStream(ciphertext), decryptStream); decryptStream.close(); } }
706
0
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk/TestUtils.java
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package com.amazonaws.encryptionsdk; import static java.lang.String.format; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import com.amazonaws.encryptionsdk.jce.JceMasterKey; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Arrays; import java.util.concurrent.ThreadLocalRandom; import java.util.concurrent.atomic.AtomicReference; import javax.crypto.spec.SecretKeySpec; public class TestUtils { public static final CryptoAlgorithm DEFAULT_TEST_CRYPTO_ALG = CryptoAlgorithm.ALG_AES_256_GCM_HKDF_SHA512_COMMIT_KEY_ECDSA_P384; public static final CommitmentPolicy DEFAULT_TEST_COMMITMENT_POLICY = CommitmentPolicy.RequireEncryptRequireDecrypt; // Handcrafted message for testing decryption of messages with committed keys public static final String messageWithCommitKeyBase64 = "AgR4TfvRMU2dVZJbgXIyxeNtbj" + "5eIw8BiTDiwsHyQ/Z9wXkAAAABAAxQcm92aWRlck5hbWUAGUtleUlkAAAAgAAAAAz45sc3cDvJZ7D4P3sAM" + "KE7d/w8ziQt2C0qHsy1Qu2E2q92eIGE/kLnF/Y003HKvTxx7xv2Zv83YuOdwHML5QIAABAAF88I9zPbUQSf" + "OlzLXv+uIY2+m/E6j2PMsbgeHVH/L0wLqQlY+5CL0z3xnNOMIZae/////wAAAAEAAAAAAAAAAAAAAAEAAAA" + "OSZBKHHRpTwXOFTQVGapXXj5CwXBMouBB2ucaIJVm"; public static final JceMasterKey messageWithCommitKeyMasterKey = JceMasterKey.getInstance( new SecretKeySpec(new byte[32], "AES"), "ProviderName", "KeyId", "AES/GCM/NoPadding"); public static final String messageWithCommitKeyMessageIdBase64 = "TfvRMU2dVZJbgXIyxeNtbj5eIw8BiTDiwsHyQ/Z9wXk="; public static final String messageWithCommitKeyCommitmentBase64 = "F88I9zPbUQSfOlzLXv+uIY2+m/E6j2PMsbgeHVH/L0w="; public static final String messageWithCommitKeyDEKBase64 = "+p6+whPVw9kOrYLZFMRBJ2n6Vli6T/7TkjDouS+25s0="; public static final CryptoAlgorithm messageWithCommitKeyCryptoAlgorithm = CryptoAlgorithm.ALG_AES_256_GCM_HKDF_SHA512_COMMIT_KEY; public static final String messageWithCommitKeyExpectedResult = "GoodCommitment"; // Handcrafted message for testing decryption of messages with invalid committed keys public static final String invalidMessageWithCommitKeyBase64 = "AgR4b1/73X5ErILpj0aSQIx6wNnH" + "LEcNLxPzA0m6vYRr7kAAAAABAAxQcm92aWRlck5hbWUAGUtleUlkAAAAgAAAAAypJmXwyizUr3/pyvIAMHL" + "U/i5GhZlGayeYC5w/CjUobyGwN4QpeMB0XpNDGTM0f1Zx72V4uM2H5wMjy/hm2wIAABAAAAECAwQFBgcICQ" + "oLDA0ODxAREhMUFRYXGBkaGxwdHh/pQM2VSvliz2Qgi5JZf2ta/////wAAAAEAAAAAAAAAAAAAAAEAAAANS" + "4Id4+dVHhPrvuJHEiOswo6YGSRjSGX3VDrt+0s="; public static final JceMasterKey invalidMessageWithCommitKeyMasterKey = JceMasterKey.getInstance( new SecretKeySpec(new byte[32], "AES"), "ProviderName", "KeyId", "AES/GCM/NoPadding"); // avoid spending time generating random data on every test case by caching some random test // vectors private static final AtomicReference<byte[]> RANDOM_CACHE = new AtomicReference<>(new byte[0]); private static byte[] ensureRandomCached(int length) { byte[] buf = RANDOM_CACHE.get(); if (buf.length >= length) { return buf; } byte[] newBuf = new byte[length]; ThreadLocalRandom.current().nextBytes(newBuf); return RANDOM_CACHE.updateAndGet( oldBuf -> { if (oldBuf.length < newBuf.length) { return newBuf; } else { return oldBuf; } }); } @FunctionalInterface public interface ThrowingRunnable { void run() throws Throwable; } public static void assertThrows( Class<? extends Throwable> throwableClass, ThrowingRunnable callback) { try { callback.run(); } catch (Throwable t) { if (throwableClass.isAssignableFrom(t.getClass())) { // ok return; } } fail("Expected exception of type " + throwableClass); } /** * Asserts that calling {@code callback} results in a {@code throwableClass} (or sub-class) being * thrown which has {@link Throwable#getMessage()} containing {@code message}. */ public static void assertThrows( Class<? extends Throwable> throwableClass, String message, ThrowingRunnable callback) { try { callback.run(); fail("Expected exception of type " + throwableClass); } catch (Throwable t) { assertTrue( format("Exception of wrong type. Was %s but expected %s", t.getClass(), throwableClass), throwableClass.isAssignableFrom(t.getClass())); assertTrue( format( "Exception did not contain the expected message. Actual: \"%s\" did not contain \"%s\"", t.getMessage(), message), t.getMessage().contains(message)); } } public static void assertThrows(ThrowingRunnable callback) { assertThrows(Throwable.class, callback); } /** * Asserts that substituting any argument with null causes a NPE to be thrown. * * <p>Usage: * * <pre>{@code * assertNullChecks( * myAwsCrypto, * "createDecryptingStream", * CryptoMaterialsManager.class, myCMM, * InputStream.class, myIS * ); * }</pre> * * @param callee * @param methodName * @param args * @throws Exception */ public static void assertNullChecks( Object callee, String methodName, // Class, value Object... args) throws Exception { ArrayList<Class> parameterTypes = new ArrayList<>(); for (int i = 0; i < args.length; i += 2) { parameterTypes.add((Class) args[i]); } Method m = callee.getClass().getMethod(methodName, parameterTypes.toArray(new Class[0])); for (int i = 0; i < args.length / 2; i++) { if (args[i * 2 + 1] == null) { // already null, which means null is ok here continue; } if (parameterTypes.get(i).isPrimitive()) { // can't be null continue; } Object[] modifiedArgs = new Object[args.length / 2]; for (int j = 0; j < args.length / 2; j++) { modifiedArgs[j] = args[j * 2 + 1]; if (j == i) { modifiedArgs[j] = null; } } try { m.invoke(callee, modifiedArgs); fail("Expected NullPointerException"); } catch (InvocationTargetException e) { if (e.getCause().getClass() == NullPointerException.class) { continue; } fail("Expected NullPointerException, got: " + e.getCause()); } } } public static byte[] toByteArray(InputStream is) throws IOException { byte[] buffer = new byte[4096]; int offset = 0; int rv; while (true) { rv = is.read(buffer, offset, buffer.length - offset); if (rv <= 0) { break; } offset += rv; if (offset == buffer.length) { if (buffer.length == Integer.MAX_VALUE) { throw new IOException("Input data exceeds maximum array size"); } int newSize = Math.toIntExact(Math.min(Integer.MAX_VALUE, 2L * buffer.length)); byte[] newBuffer = new byte[newSize]; System.arraycopy(buffer, 0, newBuffer, 0, buffer.length); buffer = newBuffer; } } return Arrays.copyOfRange(buffer, 0, offset); } public static byte[] insecureRandomBytes(int length) { byte[] buf = new byte[length]; System.arraycopy(ensureRandomCached(length), 0, buf, 0, length); return buf; } public static ByteArrayInputStream insecureRandomStream(int length) { return new ByteArrayInputStream(ensureRandomCached(length), 0, length); } public static int[] getFrameSizesToTest(final CryptoAlgorithm cryptoAlg) { final int blockSize = cryptoAlg.getBlockSize(); final int[] frameSizeToTest = { 0, blockSize - 1, blockSize, blockSize + 1, blockSize * 2, blockSize * 10, blockSize * 10 + 1, AwsCrypto.getDefaultFrameSize() }; return frameSizeToTest; } /** * Converts an array of unsigned bytes (represented as int values between 0 and 255 inclusive) to * an array of Java primitive type byte, which are by definition signed. * * @param unsignedBytes An array on unsigned bytes * @return An array of signed bytes */ public static byte[] unsignedBytesToSignedBytes(final int[] unsignedBytes) { byte[] signedBytes = new byte[unsignedBytes.length]; for (int i = 0; i < unsignedBytes.length; i++) { if (unsignedBytes[i] > 255) { throw new IllegalArgumentException("Encountered unsigned byte value > 255"); } signedBytes[i] = (byte) (unsignedBytes[i] & 0xff); } return signedBytes; } /** * Converts an array of Java primitive type bytes (which are by definition signed) to an array of * unsigned bytes (represented as int values between 0 and 255 inclusive). * * @param signedBytes An array of signed bytes * @return An array of unsigned bytes */ public static int[] signedBytesToUnsignedBytes(final byte[] signedBytes) { int[] unsignedBytes = new int[signedBytes.length]; for (int i = 0; i < signedBytes.length; i++) { unsignedBytes[i] = ((int) signedBytes[i]) & 0xff; } return unsignedBytes; } }
707
0
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk/IntegrationTestSuite.java
package com.amazonaws.encryptionsdk; import com.amazonaws.encryptionsdk.kms.KMSProviderBuilderIntegrationTests; import com.amazonaws.encryptionsdk.kms.MaxEncryptedDataKeysIntegrationTest; import com.amazonaws.encryptionsdk.kms.XCompatKmsDecryptTest; import org.junit.runner.RunWith; import org.junit.runners.Suite; @RunWith(Suite.class) @Suite.SuiteClasses({ XCompatKmsDecryptTest.class, KMSProviderBuilderIntegrationTests.class, MaxEncryptedDataKeysIntegrationTest.class, com.amazonaws.encryptionsdk.kms.KMSProviderBuilderIntegrationTests.class, com.amazonaws.encryptionsdk.kms.MaxEncryptedDataKeysIntegrationTest.class, com.amazonaws.encryptionsdk.kms.XCompatKmsDecryptTest.class }) public class IntegrationTestSuite {}
708
0
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk/SlowTestCategory.java
package com.amazonaws.encryptionsdk; /** * JUnit category marking tests to be excluded from the FastTestsOnlySuite. Usage: <code> * @Category(SlowTestCategory.class) * @Test * public void mySlowTest() { * // encrypt a couple terabytes of test data * } * </code> */ public interface SlowTestCategory {}
709
0
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk/CryptoAlgorithmTest.java
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package com.amazonaws.encryptionsdk; import static com.amazonaws.encryptionsdk.TestUtils.assertThrows; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import com.amazonaws.encryptionsdk.exception.BadCiphertextException; import com.amazonaws.encryptionsdk.internal.EncryptionHandler; import com.amazonaws.encryptionsdk.internal.StaticMasterKey; import com.amazonaws.encryptionsdk.internal.Utils; import com.amazonaws.encryptionsdk.model.CiphertextHeaders; import com.amazonaws.encryptionsdk.model.EncryptionMaterials; import com.amazonaws.encryptionsdk.model.EncryptionMaterialsRequest; import java.security.InvalidKeyException; import java.util.Collections; import java.util.Map; import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec; import org.junit.Test; public class CryptoAlgorithmTest { @Test public void testDeserialization() { for (CryptoAlgorithm algorithm : CryptoAlgorithm.values()) { assertEquals( algorithm.toString(), algorithm, CryptoAlgorithm.deserialize(algorithm.getMessageFormatVersion(), algorithm.getValue())); } } @Test public void testGetCommittedEncryptionKey() throws InvalidKeyException { CryptoAlgorithm algorithm = TestUtils.messageWithCommitKeyCryptoAlgorithm; SecretKeySpec secretKey = new SecretKeySpec( Utils.decodeBase64String(TestUtils.messageWithCommitKeyDEKBase64), algorithm.getDataKeyAlgo()); CiphertextHeaders headers = new ParsedCiphertext(Utils.decodeBase64String(TestUtils.messageWithCommitKeyBase64)); SecretKey key = algorithm.getEncryptionKeyFromDataKey(secretKey, headers); assertNotNull(key); assertEquals(algorithm.getKeyAlgo(), key.getAlgorithm()); } @Test public void testGetCommittedEncryptionKeyIncorrectCommitment() throws InvalidKeyException { CryptoAlgorithm algorithm = TestUtils.messageWithCommitKeyCryptoAlgorithm; SecretKeySpec secretKey = new SecretKeySpec( Utils.decodeBase64String(TestUtils.messageWithCommitKeyDEKBase64), algorithm.getDataKeyAlgo()); CiphertextHeaders headers = new ParsedCiphertext(Utils.decodeBase64String(TestUtils.messageWithCommitKeyBase64)); // Set header to an incorrect commitment value headers.setSuiteData(new byte[algorithm.getSuiteDataLength()]); assertThrows( BadCiphertextException.class, "Key commitment validation failed. Key identity does not match the " + "identity asserted in the message. Halting processing of this message.", () -> algorithm.getEncryptionKeyFromDataKey(secretKey, headers)); } @Test public void testGetCommittedEncryptionKeyIncorrectKeySpecAlgorithm() throws InvalidKeyException { CryptoAlgorithm algorithm = TestUtils.messageWithCommitKeyCryptoAlgorithm; SecretKeySpec secretKey = new SecretKeySpec(new byte[algorithm.getDataKeyLength()], "incorrectAlgorithm"); CiphertextHeaders headers = new ParsedCiphertext(Utils.decodeBase64String(TestUtils.messageWithCommitKeyBase64)); assertThrows( InvalidKeyException.class, "DataKey of incorrect algorithm.", () -> algorithm.getEncryptionKeyFromDataKey(secretKey, headers)); } @Test public void testGetCommittedEncryptionKeyIncorrectLength() throws InvalidKeyException { CryptoAlgorithm algorithm = TestUtils.messageWithCommitKeyCryptoAlgorithm; SecretKeySpec secretKey = new SecretKeySpec(new byte[1], "HkdfSHA512"); CiphertextHeaders headers = new ParsedCiphertext(Utils.decodeBase64String(TestUtils.messageWithCommitKeyBase64)); assertThrows( IllegalArgumentException.class, "DataKey of incorrect length.", () -> algorithm.getEncryptionKeyFromDataKey(secretKey, headers)); } @Test public void testGetUnCommittedEncryptionKey() throws InvalidKeyException { CryptoAlgorithm algo = CryptoAlgorithm.ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA256; SecretKeySpec secretKey = new SecretKeySpec(new byte[algo.getDataKeyLength()], algo.getDataKeyAlgo()); CiphertextHeaders headers = getTestHeaders(algo); SecretKey key = algo.getEncryptionKeyFromDataKey(secretKey, headers); assertNotNull(key); assertEquals(algo.getKeyAlgo(), key.getAlgorithm()); } @Test public void testGetUnCommittedEncryptionKeyFromDataKeyIncorrectKeySpecAlgorithm() throws InvalidKeyException { CryptoAlgorithm algo = CryptoAlgorithm.ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA256; SecretKeySpec secretKey = new SecretKeySpec(new byte[algo.getDataKeyLength()], "incorrectAlgorithm"); CiphertextHeaders headers = getTestHeaders(algo); assertThrows( InvalidKeyException.class, "DataKey of incorrect algorithm.", () -> TestUtils.messageWithCommitKeyCryptoAlgorithm.getEncryptionKeyFromDataKey( secretKey, headers)); } @Test public void testGetUnCommittedEncryptionKeyIncorrectLength() throws InvalidKeyException { SecretKeySpec secretKey = new SecretKeySpec(new byte[1], "HkdfSHA512"); CiphertextHeaders headers = new ParsedCiphertext(Utils.decodeBase64String(TestUtils.messageWithCommitKeyBase64)); assertThrows( IllegalArgumentException.class, "DataKey of incorrect length.", () -> TestUtils.messageWithCommitKeyCryptoAlgorithm.getEncryptionKeyFromDataKey( secretKey, headers)); } private ParsedCiphertext getTestHeaders(CryptoAlgorithm algo) { // Generate test headers final int frameSize_ = AwsCrypto.getDefaultFrameSize(); final Map<String, String> encryptionContext = Collections.<String, String>emptyMap(); final CommitmentPolicy policy = CommitmentPolicy.ForbidEncryptAllowDecrypt; final EncryptionMaterialsRequest encryptionMaterialsRequest = EncryptionMaterialsRequest.newBuilder() .setContext(encryptionContext) .setRequestedAlgorithm(algo) .setCommitmentPolicy(policy) .build(); final StaticMasterKey masterKeyProvider = new StaticMasterKey("mock"); final EncryptionMaterials encryptionMaterials = new DefaultCryptoMaterialsManager(masterKeyProvider) .getMaterialsForEncrypt(encryptionMaterialsRequest); final EncryptionHandler encryptionHandler = new EncryptionHandler(frameSize_, encryptionMaterials, policy); final byte[] in = new byte[0]; final int ciphertextLen = encryptionHandler.estimateOutputSize(in.length); final byte[] ciphertext = new byte[ciphertextLen]; encryptionHandler.processBytes(in, 0, in.length, ciphertext, 0); return new ParsedCiphertext(ciphertext); } }
710
0
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk/XCompatDecryptTest.java
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package com.amazonaws.encryptionsdk; import static org.junit.Assert.assertArrayEquals; import com.amazonaws.encryptionsdk.internal.Utils; import com.amazonaws.encryptionsdk.jce.JceMasterKey; import com.amazonaws.encryptionsdk.multi.MultipleProviderFactory; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import java.io.File; import java.io.StringReader; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Paths; import java.security.KeyFactory; import java.security.PrivateKey; import java.security.spec.PKCS8EncodedKeySpec; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.crypto.spec.SecretKeySpec; import org.apache.commons.lang3.StringUtils; import org.bouncycastle.util.io.pem.PemReader; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; @RunWith(Parameterized.class) public class XCompatDecryptTest { private static final String STATIC_XCOMPAT_NAME = "static-aws-xcompat"; private static final String AES_GCM = "AES/GCM/NoPadding"; private static final byte XCOMPAT_MESSAGE_VERSION = 1; private String plaintextFileName; private String ciphertextFileName; private MasterKeyProvider masterKeyProvider; public XCompatDecryptTest( String plaintextFileName, String ciphertextFileName, MasterKeyProvider masterKeyProvider) throws Exception { this.plaintextFileName = plaintextFileName; this.ciphertextFileName = ciphertextFileName; this.masterKeyProvider = masterKeyProvider; } @Parameters(name = "{index}: testDecryptFromFile({0}, {1}, {2})") public static Collection<Object[]> data() throws Exception { String baseDirName; baseDirName = System.getProperty("staticCompatibilityResourcesDir"); if (baseDirName == null) { baseDirName = XCompatDecryptTest.class.getProtectionDomain().getCodeSource().getLocation().getPath() + "aws_encryption_sdk_resources"; } List<Object[]> testCases_ = new ArrayList<Object[]>(); String ciphertextManifestName = StringUtils.join( new String[] {baseDirName, "manifests", "ciphertext.manifest"}, File.separator); File ciphertextManifestFile = new File(ciphertextManifestName); if (!ciphertextManifestFile.exists()) { return Collections.emptySet(); } ObjectMapper ciphertextManifestMapper = new ObjectMapper(); Map<String, Object> ciphertextManifest = ciphertextManifestMapper.readValue( ciphertextManifestFile, new TypeReference<Map<String, Object>>() {}); HashMap<String, HashMap<String, byte[]>> staticKeyMap = new HashMap<String, HashMap<String, byte[]>>(); Map<String, Object> testKeys = (Map<String, Object>) ciphertextManifest.get("test_keys"); for (Map.Entry<String, Object> keyType : testKeys.entrySet()) { Map<String, Object> keys = (Map<String, Object>) keyType.getValue(); HashMap<String, byte[]> thisKeyType = new HashMap<String, byte[]>(); for (Map.Entry<String, Object> key : keys.entrySet()) { Map<String, Object> thisKey = (Map<String, Object>) key.getValue(); String keyRaw = new String( StringUtils.join( (List<String>) thisKey.get("key"), (String) thisKey.getOrDefault("line_separator", "")) .getBytes(), StandardCharsets.UTF_8); byte[] keyBytes; switch ((String) thisKey.get("encoding")) { case "base64": keyBytes = Utils.decodeBase64String(keyRaw); break; case "pem": PemReader pemReader = new PemReader(new StringReader(keyRaw)); keyBytes = pemReader.readPemObject().getContent(); break; case "raw": default: keyBytes = keyRaw.getBytes(); } thisKeyType.put((String) key.getKey(), keyBytes); } staticKeyMap.put((String) keyType.getKey(), thisKeyType); } final KeyFactory rsaKeyFactory = KeyFactory.getInstance("RSA"); List<Map<String, Object>> testCases = (List<Map<String, Object>>) ciphertextManifest.get("test_cases"); for (Map<String, Object> testCase : testCases) { Map<String, String> plaintext = (Map<String, String>) testCase.get("plaintext"); Map<String, String> ciphertext = (Map<String, String>) testCase.get("ciphertext"); short algId = (short) Integer.parseInt((String) testCase.get("algorithm"), 16); CryptoAlgorithm encryptionAlgorithm = CryptoAlgorithm.deserialize(XCOMPAT_MESSAGE_VERSION, algId); List<Map<String, Object>> masterKeys = (List<Map<String, Object>>) testCase.get("master_keys"); List<JceMasterKey> allMasterKeys = new ArrayList<JceMasterKey>(); for (Map<String, Object> aMasterKey : masterKeys) { String providerId = (String) aMasterKey.get("provider_id"); if (providerId.equals(STATIC_XCOMPAT_NAME) && (boolean) aMasterKey.get("decryptable")) { String paddingAlgorithm = (String) aMasterKey.getOrDefault("padding_algorithm", ""); String paddingHash = (String) aMasterKey.getOrDefault("padding_hash", ""); Integer keyBits = (Integer) aMasterKey.getOrDefault("key_bits", encryptionAlgorithm.getDataKeyLength() * 8); String keyId = (String) aMasterKey.get("encryption_algorithm") + "." + keyBits.toString() + "." + paddingAlgorithm + "." + paddingHash; String encAlg = (String) aMasterKey.get("encryption_algorithm"); switch (encAlg.toUpperCase()) { case "RSA": String cipherBase = "RSA/ECB/"; String cipherName; switch (paddingAlgorithm) { case "OAEP-MGF1": cipherName = cipherBase + "OAEPWith" + paddingHash + "AndMGF1Padding"; break; case "PKCS1": cipherName = cipherBase + paddingAlgorithm + "Padding"; break; default: throw new IllegalArgumentException( "Unknown padding algorithm: " + paddingAlgorithm); } PrivateKey privKey = rsaKeyFactory.generatePrivate( new PKCS8EncodedKeySpec(staticKeyMap.get("RSA").get(keyBits.toString()))); allMasterKeys.add( JceMasterKey.getInstance(null, privKey, STATIC_XCOMPAT_NAME, keyId, cipherName)); break; case "AES": SecretKeySpec spec = new SecretKeySpec( staticKeyMap.get("AES").get(keyBits.toString()), 0, encryptionAlgorithm.getDataKeyLength(), encryptionAlgorithm.getDataKeyAlgo()); allMasterKeys.add( JceMasterKey.getInstance(spec, STATIC_XCOMPAT_NAME, keyId, AES_GCM)); break; default: throw new IllegalArgumentException( "Unknown encryption algorithm: " + encAlg.toUpperCase()); } } } if (allMasterKeys.size() > 0) { final MasterKeyProvider<?> provider = MultipleProviderFactory.buildMultiProvider(allMasterKeys); testCases_.add( new Object[] { baseDirName + File.separator + plaintext.get("filename"), baseDirName + File.separator + ciphertext.get("filename"), provider }); } } return testCases_; } @Test public void testDecryptFromFile() throws Exception { AwsCrypto crypto = AwsCrypto.standard(); byte ciphertextBytes[] = Files.readAllBytes(Paths.get(ciphertextFileName)); byte plaintextBytes[] = Files.readAllBytes(Paths.get(plaintextFileName)); final CryptoResult decryptResult = crypto.decryptData(masterKeyProvider, ciphertextBytes); assertArrayEquals(plaintextBytes, (byte[]) decryptResult.getResult()); } }
711
0
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk/AllTestsSuite.java
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package com.amazonaws.encryptionsdk; import com.amazonaws.crypto.examples.BasicEncryptionExampleTest; import com.amazonaws.crypto.examples.BasicMultiRegionKeyEncryptionExampleTest; import com.amazonaws.crypto.examples.DiscoveryDecryptionExampleTest; import com.amazonaws.crypto.examples.DiscoveryMultiRegionDecryptionExampleTest; import com.amazonaws.crypto.examples.MultipleCmkEncryptExampleTest; import com.amazonaws.crypto.examples.RestrictRegionExampleTest; import com.amazonaws.crypto.examples.SetCommitmentPolicyExampleTest; import com.amazonaws.crypto.examples.SetEncryptionAlgorithmExampleTest; import com.amazonaws.crypto.examples.SimpleDataKeyCachingExampleTest; import com.amazonaws.encryptionsdk.caching.CacheIdentifierTests; import com.amazonaws.encryptionsdk.caching.CachingCryptoMaterialsManagerTest; import com.amazonaws.encryptionsdk.caching.LocalCryptoMaterialsCacheTest; import com.amazonaws.encryptionsdk.caching.LocalCryptoMaterialsCacheThreadStormTest; import com.amazonaws.encryptionsdk.caching.NullCryptoMaterialsCacheTest; import com.amazonaws.encryptionsdk.internal.*; import com.amazonaws.encryptionsdk.jce.JceMasterKeyTest; import com.amazonaws.encryptionsdk.jce.KeyStoreProviderTest; import com.amazonaws.encryptionsdk.kms.AwsKmsMrkAwareMasterKeyProviderTest; import com.amazonaws.encryptionsdk.kms.AwsKmsMrkAwareMasterKeyTest; import com.amazonaws.encryptionsdk.kms.DiscoveryFilterTest; import com.amazonaws.encryptionsdk.kms.KMSProviderBuilderMockTests; import com.amazonaws.encryptionsdk.kms.KmsMasterKeyProviderTest; import com.amazonaws.encryptionsdk.kms.KmsMasterKeyTest; import com.amazonaws.encryptionsdk.model.CipherBlockHeadersTest; import com.amazonaws.encryptionsdk.model.CipherFrameHeadersTest; import com.amazonaws.encryptionsdk.model.CiphertextHeadersTest; import com.amazonaws.encryptionsdk.model.DecryptionMaterialsRequestTest; import com.amazonaws.encryptionsdk.model.EncryptionMaterialsRequestTest; import com.amazonaws.encryptionsdk.model.KeyBlobTest; import com.amazonaws.encryptionsdk.multi.MultipleMasterKeyTest; import org.junit.runner.RunWith; import org.junit.runners.Suite; @RunWith(Suite.class) @Suite.SuiteClasses({ CryptoAlgorithmTest.class, CiphertextHeadersTest.class, BlockDecryptionHandlerTest.class, BlockEncryptionHandlerTest.class, CipherHandlerTest.class, DecryptionHandlerTest.class, EncContextSerializerTest.class, EncryptionHandlerTest.class, FrameDecryptionHandlerTest.class, FrameEncryptionHandlerTest.class, PrimitivesParserTest.class, KeyStoreProviderTest.class, CipherBlockHeadersTest.class, CipherFrameHeadersTest.class, KeyBlobTest.class, DecryptionMaterialsRequestTest.class, MultipleMasterKeyTest.class, AwsCryptoTest.class, CryptoInputStreamTest.class, CryptoOutputStreamTest.class, TestVectorRunner.class, XCompatDecryptTest.class, DefaultCryptoMaterialsManagerTest.class, NullCryptoMaterialsCacheTest.class, AwsKmsCmkArnInfoTest.class, CacheIdentifierTests.class, CachingCryptoMaterialsManagerTest.class, LocalCryptoMaterialsCacheTest.class, LocalCryptoMaterialsCacheThreadStormTest.class, UtilsTest.class, MultipleMasterKeyTest.class, KMSProviderBuilderMockTests.class, JceMasterKeyTest.class, KmsMasterKeyProviderTest.class, KmsMasterKeyTest.class, DiscoveryFilterTest.class, CommittedKeyTest.class, EncryptionMaterialsRequestTest.class, CommitmentKATRunner.class, BasicEncryptionExampleTest.class, BasicMultiRegionKeyEncryptionExampleTest.class, DiscoveryDecryptionExampleTest.class, DiscoveryMultiRegionDecryptionExampleTest.class, MultipleCmkEncryptExampleTest.class, RestrictRegionExampleTest.class, SimpleDataKeyCachingExampleTest.class, SetEncryptionAlgorithmExampleTest.class, SetCommitmentPolicyExampleTest.class, ParsedCiphertextTest.class, AwsKmsMrkAwareMasterKeyProviderTest.class, AwsKmsMrkAwareMasterKeyTest.class, VersionInfoTest.class, com.amazonaws.encryptionsdk.kmssdkv2.AwsKmsMrkAwareMasterKeyProviderTest.class, com.amazonaws.encryptionsdk.kmssdkv2.AwsKmsMrkAwareMasterKeyTest.class, com.amazonaws.encryptionsdk.kmssdkv2.KmsMasterKeyProviderTest.class, com.amazonaws.encryptionsdk.kmssdkv2.KmsMasterKeyTest.class, }) public class AllTestsSuite {}
712
0
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk/CryptoInputStreamTest.java
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package com.amazonaws.encryptionsdk; import static com.amazonaws.encryptionsdk.TestUtils.assertThrows; import static com.amazonaws.encryptionsdk.TestUtils.insecureRandomBytes; import static com.amazonaws.encryptionsdk.internal.TestIOUtils.getSha256Hash; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; import com.amazonaws.encryptionsdk.exception.BadCiphertextException; import com.amazonaws.encryptionsdk.internal.TestIOUtils; import com.amazonaws.encryptionsdk.jce.JceMasterKey; import com.amazonaws.encryptionsdk.model.EncryptionMaterialsRequest; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.security.SecureRandom; import java.util.ArrayList; import java.util.Collection; import java.util.EnumSet; import java.util.HashMap; import java.util.Map; import java.util.function.Consumer; import javax.crypto.spec.SecretKeySpec; import org.bouncycastle.util.Arrays; import org.junit.Before; import org.junit.Test; import org.junit.experimental.runners.Enclosed; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.mockito.ArgumentCaptor; @RunWith(Enclosed.class) public class CryptoInputStreamTest { private static final SecureRandom RND = new SecureRandom(); private static final MasterKey<JceMasterKey> customerMasterKey; private static final CommitmentPolicy commitmentPolicy = TestUtils.DEFAULT_TEST_COMMITMENT_POLICY; static { byte[] rawKey = new byte[16]; RND.nextBytes(rawKey); customerMasterKey = JceMasterKey.getInstance( new SecretKeySpec(rawKey, "AES"), "mockProvider", "mockKey", "AES/GCM/NoPadding"); } private static void testRoundTrip( int dataSize, Consumer<AwsCrypto> customizer, Callback onEncrypt, Callback onDecrypt, CommitmentPolicy commitmentPolicy) throws Exception { AwsCrypto awsCrypto = AwsCrypto.builder().withCommitmentPolicy(commitmentPolicy).build(); customizer.accept(awsCrypto); byte[] plaintext = insecureRandomBytes(dataSize); ByteArrayInputStream inputStream = new ByteArrayInputStream(plaintext); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); onEncrypt.process(awsCrypto, inputStream, outputStream); inputStream = new ByteArrayInputStream(outputStream.toByteArray()); outputStream = new ByteArrayOutputStream(); onDecrypt.process(awsCrypto, inputStream, outputStream); assertArrayEquals(getSha256Hash(plaintext), getSha256Hash(outputStream.toByteArray())); } private interface Callback { void process(AwsCrypto crypto, InputStream inStream, OutputStream outStream) throws Exception; } private static Callback encryptWithContext(Map<String, String> encryptionContext) { return (awsCrypto, inStream, outStream) -> { final InputStream cryptoStream = awsCrypto.createEncryptingStream(customerMasterKey, inStream, encryptionContext); TestIOUtils.copyInStreamToOutStream(cryptoStream, outStream); }; } private static Callback encryptWithoutContext() { return (awsCrypto, inStream, outStream) -> { final InputStream cryptoStream = awsCrypto.createEncryptingStream(customerMasterKey, inStream); TestIOUtils.copyInStreamToOutStream(cryptoStream, outStream); }; } private static Callback basicDecrypt(int readLen) { return (awsCrypto, inStream, outStream) -> { final InputStream cryptoStream = awsCrypto.createDecryptingStream(customerMasterKey, inStream); TestIOUtils.copyInStreamToOutStream(cryptoStream, outStream, readLen); }; } private static Callback basicDecrypt() { return (awsCrypto, inStream, outStream) -> { final InputStream cryptoStream = awsCrypto.createDecryptingStream(customerMasterKey, inStream); TestIOUtils.copyInStreamToOutStream(cryptoStream, outStream); }; } @RunWith(Parameterized.class) public static class ParameterizedEncryptDecryptTest { private final CryptoAlgorithm cryptoAlg; private final int byteSize, frameSize, readLen; public ParameterizedEncryptDecryptTest( CryptoAlgorithm cryptoAlg, int byteSize, int frameSize, int readLen) { this.cryptoAlg = cryptoAlg; this.byteSize = byteSize; this.frameSize = frameSize; this.readLen = readLen; } @Parameterized.Parameters( name = "{index}: encryptDecrypt(algorithm={0}, byteSize={1}, frameSize={2}, readLen={3})") public static Collection<Object[]> encryptDecryptParams() { ArrayList<Object[]> testCases = new ArrayList<>(); // We'll run more exhaustive tests on the first algorithm, then go lighter weight on the rest. boolean firstAlgorithm = true; for (final CryptoAlgorithm cryptoAlg : EnumSet.allOf(CryptoAlgorithm.class)) { final int[] frameSizeToTest = TestUtils.getFrameSizesToTest(cryptoAlg); // Our bytesToTest and readLenVals arrays tend to have the bigger numbers towards the end - // we'll chop off // the last few as they take the longest and don't really add that much more coverage. int skipLastNSizes; if (!FastTestsOnlySuite.isFastTestSuiteActive()) { skipLastNSizes = 0; } else if (firstAlgorithm) { // We'll run more tests for the first algorithm in the list - but not go quite so far as // running the // 1MB tests. skipLastNSizes = 1; } else { skipLastNSizes = 2; } // iterate over frame size to test for (final int frameSize : frameSizeToTest) { int[] bytesToTest = { 0, 1, frameSize - 1, frameSize, frameSize + 1, (int) (frameSize * 1.5), frameSize * 2, 1000000 }; bytesToTest = Arrays.copyOfRange(bytesToTest, 0, bytesToTest.length - skipLastNSizes); // iterate over byte size to test for (final int byteSize : bytesToTest) { int[] readLenVals = {1, byteSize - 1, byteSize, byteSize + 1, byteSize * 2, 1000000}; readLenVals = Arrays.copyOfRange(readLenVals, 0, readLenVals.length - skipLastNSizes); // iterate over read lengths to test for (final int readLen : readLenVals) { if (byteSize >= 0 && readLen > 0) { testCases.add(new Object[] {cryptoAlg, byteSize, frameSize, readLen}); } } } } firstAlgorithm = false; } return testCases; } @Test public void encryptDecrypt() throws Exception { final CommitmentPolicy commitmentPolicy = cryptoAlg.isCommitting() ? CommitmentPolicy.RequireEncryptRequireDecrypt : CommitmentPolicy.ForbidEncryptAllowDecrypt; testRoundTrip( byteSize, awsCrypto -> { awsCrypto.setEncryptionAlgorithm(cryptoAlg); awsCrypto.setEncryptionFrameSize(frameSize); }, encryptWithoutContext(), basicDecrypt(readLen), commitmentPolicy); } } public static class NonParameterized { private AwsCrypto encryptionClient_; @Before public void setup() throws IOException { encryptionClient_ = AwsCrypto.standard(); } @Test public void doEncryptDecryptWithoutEncContext() throws Exception { testRoundTrip( 1_000_000, awsCrypto -> {}, encryptWithoutContext(), basicDecrypt(), CommitmentPolicy.RequireEncryptRequireDecrypt); } @Test public void encryptBytesDecryptStream() throws Exception { Map<String, String> encryptionContext = new HashMap<>(1); encryptionContext.put("ENC", "encryptBytesDecryptStream"); testRoundTrip( 1_000_000, awsCrypto -> {}, (AwsCrypto awsCrypto, InputStream inStream, OutputStream outStream) -> { ByteArrayOutputStream inbuf = new ByteArrayOutputStream(); TestIOUtils.copyInStreamToOutStream(inStream, inbuf); CryptoResult<byte[], ?> ciphertext = awsCrypto.encryptData(customerMasterKey, inbuf.toByteArray(), encryptionContext); outStream.write(ciphertext.getResult()); }, basicDecrypt(), CommitmentPolicy.RequireEncryptRequireDecrypt); } @Test public void encryptStreamDecryptBytes() throws Exception { Map<String, String> encryptionContext = new HashMap<>(1); encryptionContext.put("ENC", "encryptStreamDecryptBytes"); testRoundTrip( 1_000_000, awsCrypto -> {}, encryptWithContext(encryptionContext), (AwsCrypto awsCrypto, InputStream inStream, OutputStream outStream) -> { ByteArrayOutputStream inbuf = new ByteArrayOutputStream(); TestIOUtils.copyInStreamToOutStream(inStream, inbuf); CryptoResult<byte[], ?> ciphertext = awsCrypto.decryptData(customerMasterKey, inbuf.toByteArray()); outStream.write(ciphertext.getResult()); }, CommitmentPolicy.RequireEncryptRequireDecrypt); } @Test public void encryptOSDecryptIS() throws Exception { Map<String, String> encryptionContext = new HashMap<>(1); encryptionContext.put("ENC", "encryptOSDecryptIS"); testRoundTrip( 1_000_000, awsCrypto -> {}, (awsCrypto, inStream, outStream) -> { OutputStream cryptoOS = awsCrypto.createEncryptingStream(customerMasterKey, outStream, encryptionContext); TestIOUtils.copyInStreamToOutStream(inStream, cryptoOS); }, basicDecrypt(), CommitmentPolicy.RequireEncryptRequireDecrypt); } private void singleByteCopyLoop(InputStream is, OutputStream os) throws Exception { int rv; while (-1 != (rv = is.read())) { os.write(rv); } is.close(); os.close(); } @Test public void singleByteRead() throws Exception { Map<String, String> encryptionContext = new HashMap<>(1); encryptionContext.put("ENC", "singleByteRead"); testRoundTrip( 1_000_000, awsCrypto -> {}, (awsCrypto, inStream, outStream) -> { InputStream is = awsCrypto.createEncryptingStream(customerMasterKey, inStream, encryptionContext); singleByteCopyLoop(is, outStream); }, (awsCrypto, inStream, outStream) -> { InputStream is = awsCrypto.createDecryptingStream(customerMasterKey, inStream); singleByteCopyLoop(is, outStream); }, CommitmentPolicy.RequireEncryptRequireDecrypt); } @SuppressWarnings({"ConstantConditions", "ResultOfMethodCallIgnored"}) @Test(expected = NullPointerException.class) public void whenNullBufferPassed_andNoOffsetArgs_readThrowsNPE() throws BadCiphertextException, IOException { final Map<String, String> encryptionContext = new HashMap<>(1); encryptionContext.put("ENC", "nullReadBuffer"); final InputStream inStream = new ByteArrayInputStream(TestUtils.insecureRandomBytes(2048)); final InputStream encryptionInStream = encryptionClient_.createEncryptingStream(customerMasterKey, inStream, encryptionContext); encryptionInStream.read(null); } @SuppressWarnings({"ConstantConditions", "ResultOfMethodCallIgnored"}) @Test(expected = NullPointerException.class) public void whenNullBufferPassed_andOffsetArgsPassed_readThrowsNPE() throws BadCiphertextException, IOException { final Map<String, String> encryptionContext = new HashMap<>(1); encryptionContext.put("ENC", "nullReadBuffer2"); final InputStream inStream = new ByteArrayInputStream(TestUtils.insecureRandomBytes(2048)); final InputStream encryptionInStream = encryptionClient_.createEncryptingStream(customerMasterKey, inStream, encryptionContext); encryptionInStream.read(null, 0, 0); } @Test public void zeroReadLen() throws BadCiphertextException, IOException { final Map<String, String> encryptionContext = new HashMap<>(1); encryptionContext.put("ENC", "zeroReadLen"); final InputStream inStream = new ByteArrayInputStream(TestUtils.insecureRandomBytes(2048)); final InputStream encryptionInStream = encryptionClient_.createEncryptingStream(customerMasterKey, inStream, encryptionContext); final byte[] tempBytes = new byte[0]; final int readLen = encryptionInStream.read(tempBytes); assertEquals(readLen, 0); } @SuppressWarnings("ResultOfMethodCallIgnored") @Test(expected = IllegalArgumentException.class) public void negativeReadLen() throws BadCiphertextException, IOException { final Map<String, String> encryptionContext = new HashMap<>(1); encryptionContext.put("ENC", "negativeReadLen"); final InputStream inStream = new ByteArrayInputStream(TestUtils.insecureRandomBytes(2048)); final InputStream encryptionInStream = encryptionClient_.createEncryptingStream(customerMasterKey, inStream, encryptionContext); final byte[] tempBytes = new byte[1]; encryptionInStream.read(tempBytes, 0, -1); } @SuppressWarnings("ResultOfMethodCallIgnored") @Test(expected = IllegalArgumentException.class) public void negativeReadOffset() throws BadCiphertextException, IOException { final Map<String, String> encryptionContext = new HashMap<>(1); encryptionContext.put("ENC", "negativeReadOffset"); final InputStream inStream = new ByteArrayInputStream(TestUtils.insecureRandomBytes(2048)); final InputStream encryptionInStream = encryptionClient_.createEncryptingStream(customerMasterKey, inStream, encryptionContext); byte[] tempBytes = new byte[1]; encryptionInStream.read(tempBytes, -1, tempBytes.length); } @SuppressWarnings("ResultOfMethodCallIgnored") @Test(expected = ArrayIndexOutOfBoundsException.class) public void invalidReadOffset() throws BadCiphertextException, IOException { final Map<String, String> encryptionContext = new HashMap<>(1); encryptionContext.put("ENC", "invalidReadOffset"); final InputStream inStream = new ByteArrayInputStream(TestUtils.insecureRandomBytes(2048)); final InputStream encryptionInStream = encryptionClient_.createEncryptingStream(customerMasterKey, inStream, encryptionContext); final byte[] tempBytes = new byte[100]; encryptionInStream.read(tempBytes, tempBytes.length + 1, tempBytes.length); } @Test public void noOpStream() throws IOException { final Map<String, String> encryptionContext = new HashMap<>(1); encryptionContext.put("ENC", "noOpStream"); final InputStream inStream = new ByteArrayInputStream(TestUtils.insecureRandomBytes(2048)); final InputStream encryptionInStream = encryptionClient_.createEncryptingStream(customerMasterKey, inStream, encryptionContext); encryptionInStream.close(); } @Test public void decryptEmptyFile() throws IOException { final InputStream inStream = new ByteArrayInputStream(new byte[0]); final InputStream decryptionInStream = encryptionClient_.createDecryptingStream(customerMasterKey, inStream); final ByteArrayOutputStream outStream = new ByteArrayOutputStream(); TestIOUtils.copyInStreamToOutStream(decryptionInStream, outStream); assertEquals(0, outStream.size()); } @Test public void checkEncContext() throws Exception { Map<String, String> setEncryptionContext = new HashMap<>(1); setEncryptionContext.put("ENC", "checkEncContext"); testRoundTrip( 4096, awsCrypto -> {}, encryptWithContext(setEncryptionContext), (crypto, inStream, outStream) -> { CryptoInputStream<?> cis = crypto.createDecryptingStream(customerMasterKey, inStream); TestIOUtils.copyInStreamToOutStream(cis, outStream); // Note that the crypto result might have additional entries in its context, so only // check that // the entries we set were present, not that the entire map is equal CryptoResult<? extends CryptoInputStream<?>, ?> cryptoResult = cis.getCryptoResult(); setEncryptionContext.forEach( (k, v) -> assertEquals(v, cryptoResult.getEncryptionContext().get(k))); }, CommitmentPolicy.RequireEncryptRequireDecrypt); } @Test public void checkKeyId() throws Exception { testRoundTrip( 4096, awsCrypto -> {}, encryptWithoutContext(), (crypto, inStream, outStream) -> { CryptoInputStream<?> cis = crypto.createDecryptingStream(customerMasterKey, inStream); TestIOUtils.copyInStreamToOutStream(cis, outStream); CryptoResult<? extends CryptoInputStream<?>, ?> cryptoResult = cis.getCryptoResult(); final String returnedKeyId = cryptoResult.getMasterKeys().get(0).getKeyId(); assertEquals("mockKey", returnedKeyId); }, CommitmentPolicy.RequireEncryptRequireDecrypt); } @Test public void checkAvailable() throws IOException { final int byteSize = 128; final byte[] inBytes = TestIOUtils.generateRandomPlaintext(byteSize); final InputStream inStream = new ByteArrayInputStream(inBytes); final int frameSize = AwsCrypto.getDefaultFrameSize(); encryptionClient_.setEncryptionFrameSize(frameSize); Map<String, String> setEncryptionContext = new HashMap<>(1); setEncryptionContext.put("ENC", "Streaming Test"); // encryption final InputStream encryptionInStream = encryptionClient_.createEncryptingStream( customerMasterKey, inStream, setEncryptionContext); assertEquals(byteSize, encryptionInStream.available()); } @Test public void whenGetResultCalledTooEarly_noExceptionThrown() throws Exception { testRoundTrip( 1024, awsCrypto -> {}, (awsCrypto, inStream, outStream) -> { final CryptoInputStream<?> cryptoStream = awsCrypto.createEncryptingStream(customerMasterKey, inStream); // can invoke at any time on encrypt cryptoStream.getCryptoResult(); TestIOUtils.copyInStreamToOutStream(cryptoStream, outStream); cryptoStream.getCryptoResult(); }, (awsCrypto, inStream, outStream) -> { final CryptoInputStream<?> cryptoStream = awsCrypto.createDecryptingStream(customerMasterKey, inStream); // this will implicitly read the crypto headers cryptoStream.getCryptoResult(); TestIOUtils.copyInStreamToOutStream(cryptoStream, outStream); // still works cryptoStream.getCryptoResult(); }, CommitmentPolicy.RequireEncryptRequireDecrypt); } @Test(expected = BadCiphertextException.class) public void whenGetResultInvokedOnEmptyStream_exceptionThrown() throws IOException { final CryptoInputStream<?> cryptoStream = encryptionClient_.createDecryptingStream( customerMasterKey, new ByteArrayInputStream(new byte[0])); cryptoStream.getCryptoResult(); } @Test() public void encryptUsingCryptoMaterialsManager() throws Exception { RecordingMaterialsManager cmm = new RecordingMaterialsManager(customerMasterKey); testRoundTrip( 1024, awsCrypto -> {}, (crypto, inStream, outStream) -> { final CryptoInputStream<?> cryptoStream = crypto.createEncryptingStream(cmm, inStream); TestIOUtils.copyInStreamToOutStream(cryptoStream, outStream); assertEquals("bar", cryptoStream.getCryptoResult().getEncryptionContext().get("foo")); }, basicDecrypt(), commitmentPolicy); } @Test public void decryptUsingCryptoMaterialsManager() throws Exception { RecordingMaterialsManager cmm = new RecordingMaterialsManager(customerMasterKey); testRoundTrip( 1024, awsCrypto -> {}, encryptWithoutContext(), (crypto, inStream, outStream) -> { final CryptoInputStream<?> cryptoStream = crypto.createDecryptingStream(cmm, inStream); assertFalse(cmm.didDecrypt); TestIOUtils.copyInStreamToOutStream(cryptoStream, outStream); assertTrue(cmm.didDecrypt); }, commitmentPolicy); } @Test public void whenStreamSizeSetEarly_streamSizePassedToCMM() throws Exception { CryptoMaterialsManager cmm = spy(new DefaultCryptoMaterialsManager(customerMasterKey)); CryptoInputStream<?> is = AwsCrypto.standard().createEncryptingStream(cmm, new ByteArrayInputStream(new byte[1])); is.setMaxInputLength(1); is.read(); ArgumentCaptor<EncryptionMaterialsRequest> captor = ArgumentCaptor.forClass(EncryptionMaterialsRequest.class); verify(cmm).getMaterialsForEncrypt(captor.capture()); assertEquals(1L, captor.getValue().getPlaintextSize()); } @Test public void whenStreamSizeSetEarly_andExceeded_exceptionThrown() throws Exception { CryptoMaterialsManager cmm = spy(new DefaultCryptoMaterialsManager(customerMasterKey)); CryptoInputStream<?> is = AwsCrypto.standard().createEncryptingStream(cmm, new ByteArrayInputStream(new byte[2])); is.setMaxInputLength(1); assertThrows(() -> is.read(new byte[65536])); } @Test public void whenStreamSizeSetLate_andExceeded_exceptionThrown() throws Exception { CryptoMaterialsManager cmm = spy(new DefaultCryptoMaterialsManager(customerMasterKey)); CryptoInputStream<?> is = AwsCrypto.standard().createEncryptingStream(cmm, new ByteArrayInputStream(new byte[2])); assertThrows( () -> { is.read(); is.setMaxInputLength(1); is.read(new byte[65536]); }); } @Test public void whenStreamSizeSet_afterBeingExceeded_exceptionThrown() throws Exception { CryptoMaterialsManager cmm = spy(new DefaultCryptoMaterialsManager(customerMasterKey)); CryptoInputStream<?> is = AwsCrypto.standard() .createEncryptingStream(cmm, new ByteArrayInputStream(new byte[1024 * 1024])); assertThrows( () -> { is.read(); is.setMaxInputLength(1); }); } @Test public void whenStreamSizeNegative_setSizeThrows() throws Exception { CryptoInputStream<?> is = AwsCrypto.standard() .createEncryptingStream(customerMasterKey, new ByteArrayInputStream(new byte[0])); assertThrows(() -> is.setMaxInputLength(-1)); } @Test public void whenStreamSizeSet_roundTripSucceeds() throws Exception { testRoundTrip( 1024, awsCrypto -> {}, (awsCrypto, inStream, outStream) -> { final CryptoInputStream<?> cryptoStream = awsCrypto.createEncryptingStream(customerMasterKey, inStream); // we happen to know inStream is a ByteArrayInputStream which will give an accurate // number // of bytes remaining on .available() cryptoStream.setMaxInputLength(inStream.available()); TestIOUtils.copyInStreamToOutStream(cryptoStream, outStream); }, (awsCrypto, inStream, outStream) -> { final CryptoInputStream<?> cryptoStream = awsCrypto.createDecryptingStream(customerMasterKey, inStream); cryptoStream.setMaxInputLength(inStream.available()); TestIOUtils.copyInStreamToOutStream(cryptoStream, outStream); }, CommitmentPolicy.RequireEncryptRequireDecrypt); } } }
713
0
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk/CryptoOutputStreamTest.java
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package com.amazonaws.encryptionsdk; import static com.amazonaws.encryptionsdk.AwsCrypto.getDefaultFrameSize; import static com.amazonaws.encryptionsdk.FastTestsOnlySuite.isFastTestSuiteActive; import static com.amazonaws.encryptionsdk.TestUtils.assertThrows; import static com.amazonaws.encryptionsdk.TestUtils.insecureRandomBytes; import static com.amazonaws.encryptionsdk.TestUtils.toByteArray; import static com.amazonaws.encryptionsdk.internal.TestIOUtils.getSha256Hash; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; import com.amazonaws.encryptionsdk.exception.BadCiphertextException; import com.amazonaws.encryptionsdk.internal.TestIOUtils; import com.amazonaws.encryptionsdk.jce.JceMasterKey; import com.amazonaws.encryptionsdk.model.EncryptionMaterialsRequest; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.security.SecureRandom; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.EnumSet; import java.util.HashMap; import java.util.Map; import java.util.UUID; import java.util.concurrent.atomic.AtomicReference; import java.util.function.Consumer; import javax.crypto.spec.SecretKeySpec; import org.junit.Before; import org.junit.Test; import org.junit.experimental.runners.Enclosed; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.mockito.ArgumentCaptor; @RunWith(Enclosed.class) public class CryptoOutputStreamTest { private static final SecureRandom RND = new SecureRandom(); private static final MasterKey<JceMasterKey> customerMasterKey; private static final AtomicReference<byte[]> RANDOM_BUFFER = new AtomicReference<>(new byte[0]); private static final CommitmentPolicy commitmentPolicy = TestUtils.DEFAULT_TEST_COMMITMENT_POLICY; static { byte[] rawKey = new byte[16]; RND.nextBytes(rawKey); customerMasterKey = JceMasterKey.getInstance( new SecretKeySpec(rawKey, "AES"), "mockProvider", "mockKey", "AES/GCM/NoPadding"); } private static void testRoundTrip( int dataSize, Consumer<AwsCrypto> customizer, Callback onEncrypt, Callback onDecrypt, CommitmentPolicy commitmentPolicy) throws Exception { AwsCrypto awsCrypto = AwsCrypto.builder().withCommitmentPolicy(commitmentPolicy).build(); customizer.accept(awsCrypto); byte[] plaintext = insecureRandomBytes(dataSize); ByteArrayInputStream inputStream = new ByteArrayInputStream(plaintext); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); onEncrypt.process(awsCrypto, inputStream, outputStream); inputStream = new ByteArrayInputStream(outputStream.toByteArray()); outputStream = new ByteArrayOutputStream(); onDecrypt.process(awsCrypto, inputStream, outputStream); assertArrayEquals(getSha256Hash(plaintext), getSha256Hash(outputStream.toByteArray())); } private interface Callback { void process(AwsCrypto crypto, InputStream inStream, OutputStream outStream) throws Exception; } private static Callback encryptWithContext(Map<String, String> encryptionContext) { return (awsCrypto, inStream, outStream) -> { final OutputStream encryptionOutStream = awsCrypto.createEncryptingStream(customerMasterKey, outStream, encryptionContext); TestIOUtils.copyInStreamToOutStream(inStream, encryptionOutStream); }; } private static Callback encryptWithoutContext() { return (awsCrypto, inStream, outStream) -> { final OutputStream encryptionOutStream = awsCrypto.createEncryptingStream(customerMasterKey, outStream); TestIOUtils.copyInStreamToOutStream(inStream, encryptionOutStream); }; } private static Callback basicDecrypt(int readLen) { return (awsCrypto, inStream, outStream) -> { final OutputStream decryptionOutStream = awsCrypto.createDecryptingStream(customerMasterKey, outStream); TestIOUtils.copyInStreamToOutStream(inStream, decryptionOutStream, readLen); }; } private static Callback basicDecrypt() { return (awsCrypto, inStream, outStream) -> { final OutputStream decryptionOutStream = awsCrypto.createDecryptingStream(customerMasterKey, outStream); TestIOUtils.copyInStreamToOutStream(inStream, decryptionOutStream); }; } @RunWith(Parameterized.class) public static class ParameterizedEncryptDecryptTest { private final CryptoAlgorithm cryptoAlg; private final int byteSize, frameSize, readLen; public ParameterizedEncryptDecryptTest( CryptoAlgorithm cryptoAlg, int byteSize, int frameSize, int readLen) { this.cryptoAlg = cryptoAlg; this.byteSize = byteSize; this.frameSize = frameSize; this.readLen = readLen; } @Parameterized.Parameters( name = "{index}: encryptDecrypt(algorithm={0}, byteSize={1}, frameSize={2}, readLen={3})") public static Collection<Object[]> encryptDecryptParams() { ArrayList<Object[]> cases = new ArrayList<>(); for (final CryptoAlgorithm cryptoAlg : EnumSet.allOf(CryptoAlgorithm.class)) { final int[] frameSizeToTest = TestUtils.getFrameSizesToTest(cryptoAlg); // iterate over frame size to test for (int i = 0; i < frameSizeToTest.length; i++) { final int frameSize = frameSizeToTest[i]; int[] bytesToTest = { 0, 1, frameSize - 1, frameSize, frameSize + 1, (int) (frameSize * 1.5), frameSize * 2, 1000000 }; if (isFastTestSuiteActive()) { // Exclude the last two sizes, as they're the slowest bytesToTest = Arrays.copyOfRange(bytesToTest, 0, bytesToTest.length - 2); } // iterate over byte size to test for (int j = 0; j < bytesToTest.length; j++) { final int byteSize = bytesToTest[j]; int[] readLenVals = {byteSize - 1, byteSize, byteSize + 1, byteSize * 2, 1000000}; if (isFastTestSuiteActive()) { // Only test one read() call buffer length in the fast tests. This greatly cuts down // on // the combinatorial explosion of test cases here. readLenVals = Arrays.copyOfRange(readLenVals, 0, 1); } // iterate over read lengths to test for (int k = 0; k < readLenVals.length; k++) { final int readLen = readLenVals[k]; if (byteSize >= 0 && readLen > 0) { cases.add(new Object[] {cryptoAlg, byteSize, frameSize, readLen}); } } } } } return cases; } @Test public void encryptDecrypt() throws Exception { final Map<String, String> encryptionContext = new HashMap<String, String>(1); encryptionContext.put("ENC", "Streaming Test"); final CommitmentPolicy commitmentPolicy = cryptoAlg.isCommitting() ? CommitmentPolicy.RequireEncryptRequireDecrypt : CommitmentPolicy.ForbidEncryptAllowDecrypt; testRoundTrip( byteSize, awsCrypto -> { awsCrypto.setEncryptionFrameSize(frameSize); awsCrypto.setEncryptionAlgorithm(cryptoAlg); }, encryptWithContext(encryptionContext), basicDecrypt(readLen), commitmentPolicy); } } public static class NonParameterized { private AwsCrypto encryptionClient_; public NonParameterized() {} @Before public void setup() throws IOException { encryptionClient_ = AwsCrypto.standard(); } @Test public void singleByteWrite() throws Exception { final Map<String, String> encryptionContext = new HashMap<String, String>(1); encryptionContext.put("ENC", "Streaming Test"); testRoundTrip( 10_000, awsCrypto -> {}, (awsCrypto, inStream, outStream) -> { final OutputStream encryptionOutStream = awsCrypto.createEncryptingStream(customerMasterKey, outStream, encryptionContext); // write a single plaintext byte at a time final byte[] writeBytes = new byte[2048]; int read_len = 0; while (read_len >= 0) { read_len = inStream.read(writeBytes); if (read_len > 0) { for (int i = 0; i < read_len; i++) { encryptionOutStream.write(writeBytes[i]); } } } encryptionOutStream.close(); }, (awsCrypto, inStream, outStream) -> { final OutputStream decryptionOutStream = awsCrypto.createDecryptingStream(customerMasterKey, outStream); // write a single decrypted byte at a time final byte[] writeBytes = new byte[2048]; int read_len = 0; while (read_len >= 0) { read_len = inStream.read(writeBytes); if (read_len > 0) { for (int i = 0; i < read_len; i++) { decryptionOutStream.write(writeBytes[i]); } } } decryptionOutStream.close(); }, CommitmentPolicy.RequireEncryptRequireDecrypt); } @Test public void doEncryptDecryptWithoutEncContext() throws Exception { testRoundTrip( 1_000_000, awsCrypto -> {}, encryptWithoutContext(), basicDecrypt(), CommitmentPolicy.RequireEncryptRequireDecrypt); } @Test public void doEncryptDecryptWithContext() throws Exception { Map<String, String> encryptionContext = new HashMap<String, String>(1); encryptionContext.put("ENC", "Streaming Test: inputStreamCompatiblilty"); testRoundTrip( 1_000_000, awsCrypto -> awsCrypto.setEncryptionFrameSize(getDefaultFrameSize()), encryptWithContext(encryptionContext), basicDecrypt(), CommitmentPolicy.RequireEncryptRequireDecrypt); } @Test public void encryptOneShotDecryptStream() throws Exception { Map<String, String> encryptionContext = new HashMap<String, String>(1); encryptionContext.put("ENC", "encryptAPICompatibility"); testRoundTrip( 1_000_000, awsCrypto -> {}, (crypto, inStream, outStream) -> { outStream.write( encryptionClient_ .encryptData(customerMasterKey, toByteArray(inStream), encryptionContext) .getResult()); }, (crypto, inStream, outStream) -> { final OutputStream decryptionOutStream = encryptionClient_.createDecryptingStream(customerMasterKey, outStream); decryptionOutStream.write(toByteArray(inStream)); decryptionOutStream.close(); }, CommitmentPolicy.RequireEncryptRequireDecrypt); } @Test public void encryptStreamDecryptOneShot() throws Exception { Map<String, String> encryptionContext = new HashMap<String, String>(1); encryptionContext.put("ENC", "decryptAPICompatibility"); testRoundTrip( 1_000_000, awsCrypto -> {}, (crypto, inStream, outStream) -> { final OutputStream encryptionOutStream = encryptionClient_.createEncryptingStream( customerMasterKey, outStream, encryptionContext); TestIOUtils.copyInStreamToOutStream(inStream, encryptionOutStream); }, (crypto, inStream, outStream) -> { outStream.write( encryptionClient_ .decryptData(customerMasterKey, toByteArray(inStream)) .getResult()); }, CommitmentPolicy.RequireEncryptRequireDecrypt); } @Test(expected = IllegalArgumentException.class) public void nullWrite() throws IOException { final OutputStream outStream = new ByteArrayOutputStream(); final OutputStream encryptionOutStream = encryptionClient_.createEncryptingStream(customerMasterKey, outStream); encryptionOutStream.write(null); } @Test(expected = IllegalArgumentException.class) public void nullWrite2() throws BadCiphertextException, IOException { final OutputStream outStream = new ByteArrayOutputStream(); final OutputStream encryptionOutStream = encryptionClient_.createEncryptingStream(customerMasterKey, outStream); encryptionOutStream.write(null, 0, 0); } @Test(expected = IllegalArgumentException.class) public void negativeWriteLen() throws BadCiphertextException, IOException { final OutputStream outStream = new ByteArrayOutputStream(); final OutputStream encryptionOutStream = encryptionClient_.createEncryptingStream(customerMasterKey, outStream); final byte[] writeBytes = new byte[0]; encryptionOutStream.write(writeBytes, 0, -1); } @Test(expected = IllegalArgumentException.class) public void negativeWriteOffset() throws BadCiphertextException, IOException { final OutputStream outStream = new ByteArrayOutputStream(); final OutputStream encryptionOutStream = encryptionClient_.createEncryptingStream(customerMasterKey, outStream); final byte[] writeBytes = new byte[2048]; encryptionOutStream.write(writeBytes, -1, writeBytes.length); } @Test public void checkInvalidValues() throws Exception { // test for the two formats - single-block and frame. final int[] frameSizeToTest = {0, getDefaultFrameSize()}; // iterate over frame size to test for (int i = 0; i < frameSizeToTest.length; i++) { final int frameSize = frameSizeToTest[i]; invalidWriteLen(frameSize); invalidWriteOffset(frameSize); noOpStream(frameSize); } } private void invalidWriteLen(final int frameSize) throws BadCiphertextException, IOException { AwsCrypto awsCrypto = AwsCrypto.standard(); awsCrypto.setEncryptionFrameSize(frameSize); final OutputStream outStream = new ByteArrayOutputStream(); final OutputStream encryptionOutStream = awsCrypto.createEncryptingStream(customerMasterKey, outStream); final byte[] writeBytes = new byte[2048]; assertThrows( IndexOutOfBoundsException.class, () -> encryptionOutStream.write(writeBytes, 0, 2 * writeBytes.length)); } private void invalidWriteOffset(final int frameSize) throws BadCiphertextException, IOException { AwsCrypto awsCrypto = AwsCrypto.standard(); awsCrypto.setEncryptionFrameSize(frameSize); final OutputStream outStream = new ByteArrayOutputStream(); final OutputStream encryptionOutStream = awsCrypto.createEncryptingStream(customerMasterKey, outStream); final byte[] writeBytes = new byte[2048]; assertThrows( IndexOutOfBoundsException.class, () -> encryptionOutStream.write(writeBytes, writeBytes.length + 1, writeBytes.length)); } private void noOpStream(final int frameSize) throws Exception { final Map<String, String> encryptionContext = new HashMap<String, String>(1); encryptionContext.put("ENC", "noOpStream size " + frameSize); final ByteArrayOutputStream outStream = new ByteArrayOutputStream(); final OutputStream encryptionOutStream = encryptionClient_.createEncryptingStream(customerMasterKey, outStream, encryptionContext); encryptionOutStream.close(); testRoundTrip( 0, crypto -> crypto.setEncryptionFrameSize(frameSize), encryptWithContext(encryptionContext), basicDecrypt(), CommitmentPolicy.RequireEncryptRequireDecrypt); } @Test public void decryptEmptyFile() throws IOException { final InputStream inStream = new ByteArrayInputStream(new byte[0]); final ByteArrayOutputStream outStream = new ByteArrayOutputStream(); final OutputStream decryptionOutStream = encryptionClient_.createDecryptingStream(customerMasterKey, outStream); TestIOUtils.copyInStreamToOutStream(inStream, decryptionOutStream); inStream.close(); decryptionOutStream.close(); assertEquals(0, outStream.size()); } @Test public void checkEncContext() throws Exception { Map<String, String> context = new HashMap<String, String>(1); context.put("ENC", "Streaming Test " + UUID.randomUUID()); testRoundTrip( 1, awsCrypto -> {}, encryptWithContext(context), (crypto, inStream, outStream) -> { final CryptoOutputStream<JceMasterKey> decryptionOutStream = encryptionClient_.createDecryptingStream(customerMasterKey, outStream); TestIOUtils.copyInStreamToOutStream(inStream, decryptionOutStream); Map<String, String> getEncryptionContext = decryptionOutStream.getCryptoResult().getEncryptionContext(); // Since more values may have been added, we need to check to ensure that all // of setEncryptionContext is present, not that there is nothing else for (final Map.Entry<String, String> e : context.entrySet()) { assertEquals(e.getValue(), getEncryptionContext.get(e.getKey())); } }, CommitmentPolicy.RequireEncryptRequireDecrypt); } @Test public void checkKeyId() throws Exception { Map<String, String> context = new HashMap<String, String>(1); context.put("ENC", "Streaming Test " + UUID.randomUUID()); testRoundTrip( 1, awsCrypto -> {}, encryptWithContext(context), (crypto, inStream, outStream) -> { final CryptoOutputStream<JceMasterKey> decryptionOutStream = encryptionClient_.createDecryptingStream(customerMasterKey, outStream); TestIOUtils.copyInStreamToOutStream(inStream, decryptionOutStream); final String returnedKeyId = decryptionOutStream.getCryptoResult().getMasterKeys().get(0).getKeyId(); assertEquals("mockKey", returnedKeyId); }, CommitmentPolicy.RequireEncryptRequireDecrypt); } @Test public void whenGetResultCalledTooEarly_exceptionThrown() throws Exception { testRoundTrip( 1024, awsCrypto -> {}, (awsCrypto2, inStream, outStream) -> { final CryptoOutputStream<?> encryptionOutStream = awsCrypto2.createEncryptingStream(customerMasterKey, outStream); // we should be able to get the cryptoResult on the encrypt path immediately encryptionOutStream.getCryptoResult(); TestIOUtils.copyInStreamToOutStream(inStream, encryptionOutStream); }, (awsCrypto1, inStream, outStream) -> { final CryptoOutputStream<?> decryptionOutStream = awsCrypto1.createDecryptingStream(customerMasterKey, outStream); // Can't get headers until we write them to the outstream assertThrows(IllegalStateException.class, decryptionOutStream::getCryptoResult); TestIOUtils.copyInStreamToOutStream(inStream, decryptionOutStream); // Now we can get headers decryptionOutStream.getCryptoResult(); }, CommitmentPolicy.RequireEncryptRequireDecrypt); } @Test public void encryptUsingCryptoMaterialsManager() throws Exception { RecordingMaterialsManager cmm = new RecordingMaterialsManager(customerMasterKey); testRoundTrip( 1024, awsCrypto -> {}, (crypto, inStream, outStream) -> { final CryptoOutputStream<?> cryptoStream = crypto.createEncryptingStream(cmm, outStream); TestIOUtils.copyInStreamToOutStream(inStream, cryptoStream); assertEquals("bar", cryptoStream.getCryptoResult().getEncryptionContext().get("foo")); }, basicDecrypt(), commitmentPolicy); } @Test public void decryptUsingCryptoMaterialsManager() throws Exception { RecordingMaterialsManager cmm = new RecordingMaterialsManager(customerMasterKey); testRoundTrip( 1024, awsCrypto -> {}, encryptWithoutContext(), (crypto, inStream, outStream) -> { final CryptoOutputStream<?> cryptoStream = crypto.createDecryptingStream(cmm, outStream); assertFalse(cmm.didDecrypt); TestIOUtils.copyInStreamToOutStream(inStream, cryptoStream); assertTrue(cmm.didDecrypt); }, commitmentPolicy); } @Test public void whenStreamSizeSetEarly_streamSizePassedToCMM() throws Exception { CryptoMaterialsManager cmm = spy(new DefaultCryptoMaterialsManager(customerMasterKey)); CryptoOutputStream<?> os = AwsCrypto.standard().createEncryptingStream(cmm, new ByteArrayOutputStream()); os.setMaxInputLength(1); os.write(0); ArgumentCaptor<EncryptionMaterialsRequest> captor = ArgumentCaptor.forClass(EncryptionMaterialsRequest.class); verify(cmm).getMaterialsForEncrypt(captor.capture()); assertEquals(1L, captor.getValue().getPlaintextSize()); } @Test public void whenStreamSizeSetEarly_andExceeded_exceptionThrown() throws Exception { CryptoMaterialsManager cmm = spy(new DefaultCryptoMaterialsManager(customerMasterKey)); CryptoOutputStream<?> os = AwsCrypto.standard().createEncryptingStream(cmm, new ByteArrayOutputStream()); os.setMaxInputLength(1); os.write(0); assertThrows(() -> os.write(0)); } @Test public void whenStreamSizeSetLate_andExceeded_exceptionThrown() throws Exception { CryptoMaterialsManager cmm = spy(new DefaultCryptoMaterialsManager(customerMasterKey)); CryptoOutputStream<?> os = AwsCrypto.standard().createEncryptingStream(cmm, new ByteArrayOutputStream()); os.write(0); os.setMaxInputLength(1); assertThrows(() -> os.write(0)); } @Test public void whenStreamSizeSet_afterBeingExceeded_exceptionThrown() throws Exception { CryptoMaterialsManager cmm = spy(new DefaultCryptoMaterialsManager(customerMasterKey)); CryptoOutputStream<?> os = AwsCrypto.standard().createEncryptingStream(cmm, new ByteArrayOutputStream()); os.write(0); os.write(0); assertThrows(() -> os.setMaxInputLength(1)); } @Test public void whenStreamSizeNegative_setSizeThrows() throws Exception { CryptoOutputStream<?> is = AwsCrypto.standard() .createEncryptingStream(customerMasterKey, new ByteArrayOutputStream()); assertThrows(() -> is.setMaxInputLength(-1)); } @Test public void whenStreamSizeSet_roundTripSucceeds() throws Exception { testRoundTrip( 1024, ignored -> {}, (awsCrypto, inStream, outStream) -> { final CryptoOutputStream<?> encryptionOutStream = awsCrypto.createEncryptingStream(customerMasterKey, outStream); encryptionOutStream.setMaxInputLength(1024); TestIOUtils.copyInStreamToOutStream(inStream, encryptionOutStream); }, (awsCrypto, inStream, outStream) -> { final CryptoOutputStream<?> decryptionOutStream = awsCrypto.createDecryptingStream(customerMasterKey, outStream); // we happen to know inStream is a ByteArrayInputStream which will give an accurate // number // of bytes remaining on .available() decryptionOutStream.setMaxInputLength(inStream.available()); TestIOUtils.copyInStreamToOutStream(inStream, decryptionOutStream); }, CommitmentPolicy.RequireEncryptRequireDecrypt); } } }
714
0
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk/RecordingMaterialsManager.java
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package com.amazonaws.encryptionsdk; import com.amazonaws.encryptionsdk.model.DecryptionMaterials; import com.amazonaws.encryptionsdk.model.DecryptionMaterialsRequest; import com.amazonaws.encryptionsdk.model.EncryptionMaterials; import com.amazonaws.encryptionsdk.model.EncryptionMaterialsRequest; import java.util.Collections; public class RecordingMaterialsManager implements CryptoMaterialsManager { private final CryptoMaterialsManager delegate; private final CommitmentPolicy commitmentPolicy = TestUtils.DEFAULT_TEST_COMMITMENT_POLICY; public boolean didDecrypt = false; public RecordingMaterialsManager(CryptoMaterialsManager delegate) { this.delegate = delegate; } public RecordingMaterialsManager(MasterKeyProvider<?> delegate) { this.delegate = new DefaultCryptoMaterialsManager(delegate); } @Override public EncryptionMaterials getMaterialsForEncrypt(EncryptionMaterialsRequest request) { request = request.toBuilder().setContext(Collections.singletonMap("foo", "bar")).build(); EncryptionMaterials result = delegate.getMaterialsForEncrypt(request); return result; } @Override public DecryptionMaterials decryptMaterials(DecryptionMaterialsRequest request) { didDecrypt = true; return delegate.decryptMaterials(request); } }
715
0
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk/DecryptionMethod.java
package com.amazonaws.encryptionsdk; import com.amazonaws.encryptionsdk.internal.SignaturePolicy; import com.amazonaws.encryptionsdk.internal.TestIOUtils; import java.io.*; enum DecryptionMethod { OneShot { @Override public byte[] decryptMessage( AwsCrypto crypto, MasterKeyProvider<?> masterKeyProvider, byte[] ciphertext) throws IOException { return crypto.decryptData(masterKeyProvider, ciphertext).getResult(); } }, // Note for the record that changing the readLen parameter of copyInStreamToOutStream has minimal // effect on the actual data flow when copying from a CryptoInputStream: it will always read from // the // underlying input stream with a fixed chunk size (4096 bytes at the time of writing this), // independently // of how many bytes its asked to read of the decryption result. It's still useful to vary the // length to // ensure the buffering in the CryptoInputStream works correctly though. InputStreamSingleByteChunks { @Override public byte[] decryptMessage( AwsCrypto crypto, MasterKeyProvider<?> masterKeyProvider, byte[] ciphertext) throws IOException { InputStream in = crypto.createDecryptingStream(masterKeyProvider, new ByteArrayInputStream(ciphertext)); ByteArrayOutputStream out = new ByteArrayOutputStream(); TestIOUtils.copyInStreamToOutStream(in, out, 1); return out.toByteArray(); } }, InputStreamSmallByteChunks { @Override public byte[] decryptMessage( AwsCrypto crypto, MasterKeyProvider<?> masterKeyProvider, byte[] ciphertext) throws IOException { InputStream in = crypto.createDecryptingStream(masterKeyProvider, new ByteArrayInputStream(ciphertext)); ByteArrayOutputStream out = new ByteArrayOutputStream(); TestIOUtils.copyInStreamToOutStream(in, out, SMALL_CHUNK_SIZE); return out.toByteArray(); } }, InputStreamWholeMessageChunks { @Override public byte[] decryptMessage( AwsCrypto crypto, MasterKeyProvider<?> masterKeyProvider, byte[] ciphertext) throws IOException { InputStream in = crypto.createDecryptingStream(masterKeyProvider, new ByteArrayInputStream(ciphertext)); ByteArrayOutputStream out = new ByteArrayOutputStream(); TestIOUtils.copyInStreamToOutStream(in, out, ciphertext.length); return out.toByteArray(); } }, UnsignedMessageInputStreamSingleByteChunks { @Override public byte[] decryptMessage( AwsCrypto crypto, MasterKeyProvider<?> masterKeyProvider, byte[] ciphertext) throws IOException { InputStream in = crypto.createUnsignedMessageDecryptingStream( masterKeyProvider, new ByteArrayInputStream(ciphertext)); ByteArrayOutputStream out = new ByteArrayOutputStream(); TestIOUtils.copyInStreamToOutStream(in, out, 1); return out.toByteArray(); } @Override public SignaturePolicy signaturePolicy() { return SignaturePolicy.AllowEncryptForbidDecrypt; } }, UnsignedMessageInputStreamSmallByteChunks { @Override public byte[] decryptMessage( AwsCrypto crypto, MasterKeyProvider<?> masterKeyProvider, byte[] ciphertext) throws IOException { InputStream in = crypto.createUnsignedMessageDecryptingStream( masterKeyProvider, new ByteArrayInputStream(ciphertext)); ByteArrayOutputStream out = new ByteArrayOutputStream(); TestIOUtils.copyInStreamToOutStream(in, out, SMALL_CHUNK_SIZE); return out.toByteArray(); } @Override public SignaturePolicy signaturePolicy() { return SignaturePolicy.AllowEncryptForbidDecrypt; } }, UnsignedMessageInputStreamWholeMessageChunks { @Override public byte[] decryptMessage( AwsCrypto crypto, MasterKeyProvider<?> masterKeyProvider, byte[] ciphertext) throws IOException { InputStream in = crypto.createUnsignedMessageDecryptingStream( masterKeyProvider, new ByteArrayInputStream(ciphertext)); ByteArrayOutputStream out = new ByteArrayOutputStream(); TestIOUtils.copyInStreamToOutStream(in, out, ciphertext.length); return out.toByteArray(); } @Override public SignaturePolicy signaturePolicy() { return SignaturePolicy.AllowEncryptForbidDecrypt; } }, OutputStreamSingleByteChunks { @Override public byte[] decryptMessage( AwsCrypto crypto, MasterKeyProvider<?> masterKeyProvider, byte[] ciphertext) throws IOException { InputStream in = new ByteArrayInputStream(ciphertext); ByteArrayOutputStream out = new ByteArrayOutputStream(); OutputStream decryptingOut = crypto.createDecryptingStream(masterKeyProvider, out); TestIOUtils.copyInStreamToOutStream(in, decryptingOut, 1); return out.toByteArray(); } }, OutputStreamSmallByteChunks { @Override public byte[] decryptMessage( AwsCrypto crypto, MasterKeyProvider<?> masterKeyProvider, byte[] ciphertext) throws IOException { InputStream in = new ByteArrayInputStream(ciphertext); ByteArrayOutputStream out = new ByteArrayOutputStream(); OutputStream decryptingOut = crypto.createDecryptingStream(masterKeyProvider, out); TestIOUtils.copyInStreamToOutStream(in, decryptingOut, SMALL_CHUNK_SIZE); return out.toByteArray(); } }, OutputStreamWholeMessageChunks { @Override public byte[] decryptMessage( AwsCrypto crypto, MasterKeyProvider<?> masterKeyProvider, byte[] ciphertext) throws IOException { InputStream in = new ByteArrayInputStream(ciphertext); ByteArrayOutputStream out = new ByteArrayOutputStream(); OutputStream decryptingOut = crypto.createDecryptingStream(masterKeyProvider, out); TestIOUtils.copyInStreamToOutStream(in, decryptingOut, ciphertext.length); return out.toByteArray(); } }, UnsignedMessageOutputStreamSingleByteChunks { @Override public byte[] decryptMessage( AwsCrypto crypto, MasterKeyProvider masterKeyProvider, byte[] ciphertext) throws IOException { InputStream in = new ByteArrayInputStream(ciphertext); ByteArrayOutputStream out = new ByteArrayOutputStream(); OutputStream decryptingOut = crypto.createUnsignedMessageDecryptingStream(masterKeyProvider, out); TestIOUtils.copyInStreamToOutStream(in, decryptingOut, 1); return out.toByteArray(); } @Override public SignaturePolicy signaturePolicy() { return SignaturePolicy.AllowEncryptForbidDecrypt; } }, UnsignedMessageOutputStreamSmallByteChunks { @Override public byte[] decryptMessage( AwsCrypto crypto, MasterKeyProvider masterKeyProvider, byte[] ciphertext) throws IOException { InputStream in = new ByteArrayInputStream(ciphertext); ByteArrayOutputStream out = new ByteArrayOutputStream(); OutputStream decryptingOut = crypto.createUnsignedMessageDecryptingStream(masterKeyProvider, out); TestIOUtils.copyInStreamToOutStream(in, decryptingOut, SMALL_CHUNK_SIZE); return out.toByteArray(); } @Override public SignaturePolicy signaturePolicy() { return SignaturePolicy.AllowEncryptForbidDecrypt; } }, UnsignedMessageOutputStreamWholeMessageChunks { @Override public byte[] decryptMessage( AwsCrypto crypto, MasterKeyProvider masterKeyProvider, byte[] ciphertext) throws IOException { InputStream in = new ByteArrayInputStream(ciphertext); ByteArrayOutputStream out = new ByteArrayOutputStream(); OutputStream decryptingOut = crypto.createUnsignedMessageDecryptingStream(masterKeyProvider, out); TestIOUtils.copyInStreamToOutStream(in, decryptingOut, ciphertext.length); return out.toByteArray(); } @Override public SignaturePolicy signaturePolicy() { return SignaturePolicy.AllowEncryptForbidDecrypt; } }; // A semi-arbitrary chunk size just to have at least one non-boundary input, and something // that will span at least some message segments. private static final int SMALL_CHUNK_SIZE = 100; public abstract byte[] decryptMessage( AwsCrypto crypto, MasterKeyProvider<?> masterKeyProvider, byte[] ciphertext) throws IOException; public SignaturePolicy signaturePolicy() { return SignaturePolicy.AllowEncryptAllowDecrypt; } }
716
0
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk/TestVectorRunner.java
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package com.amazonaws.encryptionsdk; import static java.lang.String.format; import com.amazonaws.auth.DefaultAWSCredentialsProviderChain; import com.amazonaws.encryptionsdk.internal.SignaturePolicy; import com.amazonaws.encryptionsdk.jce.JceMasterKey; import com.amazonaws.encryptionsdk.kms.AwsKmsMrkAwareMasterKeyProvider; import com.amazonaws.encryptionsdk.kms.DiscoveryFilter; import com.amazonaws.encryptionsdk.kms.KmsMasterKeyProvider; import com.amazonaws.encryptionsdk.multi.MultipleProviderFactory; import com.amazonaws.util.IOUtils; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import java.io.IOException; import java.io.InputStream; import java.net.JarURLConnection; import java.net.URL; import java.security.*; import java.security.spec.PKCS8EncodedKeySpec; import java.security.spec.X509EncodedKeySpec; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.Callable; import java.util.function.Supplier; import java.util.jar.JarFile; import java.util.zip.ZipEntry; import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec; import org.bouncycastle.util.encoders.Base64; import org.junit.AfterClass; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import software.amazon.awssdk.regions.Region; @RunWith(Parameterized.class) public class TestVectorRunner { private static final int MANIFEST_VERSION = 2; // We save the files in memory to avoid repeatedly retrieving them. This won't work if the // plaintexts are too // large or numerous private static final Map<String, byte[]> cachedData = new HashMap<>(); private final String testName; private final TestCase testCase; private final DecryptionMethod decryptionMethod; public TestVectorRunner( final String testName, TestCase testCase, DecryptionMethod decryptionMethod) { this.testName = testName; this.testCase = testCase; this.decryptionMethod = decryptionMethod; } @Test public void decrypt() throws Exception { AwsCrypto crypto = AwsCrypto.builder() .withCommitmentPolicy(CommitmentPolicy.ForbidEncryptAllowDecrypt) .build(); Callable<byte[]> decryptor = () -> decryptionMethod.decryptMessage( crypto, testCase.mkpSupplier.get(), cachedData.get(testCase.ciphertextPath)); testCase.matcher.Match(decryptor); } @Parameterized.Parameters(name = "Compatibility Test: {0} - {2}") @SuppressWarnings("unchecked") public static Collection<Object[]> data() throws Exception { final String zipPath = System.getProperty("testVectorZip"); if (zipPath == null) { return Collections.emptyList(); } final JarURLConnection jarConnection = (JarURLConnection) new URL("jar:" + zipPath + "!/").openConnection(); try (JarFile jar = jarConnection.getJarFile()) { final Map<String, Object> manifest = readJsonMapFromJar(jar, "manifest.json"); final Map<String, Object> metaData = (Map<String, Object>) manifest.get("manifest"); // We only support "awses-decrypt" type manifests right now if (!"awses-decrypt".equals(metaData.get("type"))) { throw new IllegalArgumentException("Unsupported manifest type: " + metaData.get("type")); } if (!Integer.valueOf(MANIFEST_VERSION).equals(metaData.get("version"))) { throw new IllegalArgumentException( "Unsupported manifest version: " + metaData.get("version")); } final Map<String, KeyEntry> keys = parseKeyManifest(readJsonMapFromJar(jar, (String) manifest.get("keys"))); final KmsMasterKeyProvider kmsProvV1 = KmsMasterKeyProvider.builder() .withCredentials(new DefaultAWSCredentialsProviderChain()) .buildDiscovery(); final com.amazonaws.encryptionsdk.kmssdkv2.KmsMasterKeyProvider kmsProvV2 = com.amazonaws.encryptionsdk.kmssdkv2.KmsMasterKeyProvider.builder().buildDiscovery(); List<Object[]> testCases = new ArrayList<>(); for (Map.Entry<String, Map<String, Object>> testEntry : ((Map<String, Map<String, Object>>) manifest.get("tests")).entrySet()) { String testName = testEntry.getKey(); TestCase testCaseV1 = parseTest(testEntry.getKey(), testEntry.getValue(), keys, jar, kmsProvV1); TestCase testCaseV2 = parseTest(testEntry.getKey(), testEntry.getValue(), keys, jar, kmsProvV2); for (DecryptionMethod decryptionMethod : DecryptionMethod.values()) { if (testCaseV1.signaturePolicy.equals(decryptionMethod.signaturePolicy())) { testCases.add(new Object[] {testName, testCaseV1, decryptionMethod}); testCases.add(new Object[] {testName + "-V2", testCaseV2, decryptionMethod}); } } } return testCases; } } @AfterClass public static void teardown() { cachedData.clear(); } private static byte[] readBytesFromJar(JarFile jar, String fileName) throws IOException { try (InputStream is = readFromJar(jar, fileName)) { return IOUtils.toByteArray(is); } } private static Map<String, Object> readJsonMapFromJar(JarFile jar, String fileName) throws IOException { try (InputStream is = readFromJar(jar, fileName)) { final ObjectMapper mapper = new ObjectMapper(); return mapper.readValue(is, new TypeReference<Map<String, Object>>() {}); } } private static InputStream readFromJar(JarFile jar, String name) throws IOException { // Our manifest URIs incorrectly start with file:// rather than just file: so we need to strip // this ZipEntry entry = jar.getEntry(name.replaceFirst("^file://(?!/)", "")); return jar.getInputStream(entry); } private static void cacheData(JarFile jar, String url) throws IOException { if (!cachedData.containsKey(url)) { cachedData.put(url, readBytesFromJar(jar, url)); } } @SuppressWarnings("unchecked") private static <T> TestCase parseTest( String testName, Map<String, Object> data, Map<String, KeyEntry> keys, JarFile jar, KmsMasterKeyProvider kmsProv) throws IOException { final String ciphertextURL = (String) data.get("ciphertext"); cacheData(jar, ciphertextURL); Supplier<MasterKeyProvider<?>> mkpSupplier = () -> { @SuppressWarnings("generic") final List<MasterKey<?>> mks = new ArrayList<>(); for (Map<String, Object> mkEntry : (List<Map<String, Object>>) data.get("master-keys")) { final String type = (String) mkEntry.get("type"); final String keyName = (String) mkEntry.get("key"); final KeyEntry key = keys.get(keyName); if ("aws-kms".equals(type)) { mks.add(kmsProv.getMasterKey(key.keyId)); } else if ("aws-kms-mrk-aware".equals(type)) { AwsKmsMrkAwareMasterKeyProvider provider = AwsKmsMrkAwareMasterKeyProvider.builder().buildStrict(key.keyId); mks.add(provider.getMasterKey(key.keyId)); } else if ("aws-kms-mrk-aware-discovery".equals(type)) { final String defaultMrkRegion = (String) mkEntry.get("default-mrk-region"); final Map<String, Object> discoveryFilterSpec = (Map<String, Object>) mkEntry.get("aws-kms-discovery-filter"); final DiscoveryFilter discoveryFilter; if (discoveryFilterSpec != null) { discoveryFilter = new DiscoveryFilter( (String) discoveryFilterSpec.get("partition"), (List<String>) discoveryFilterSpec.get("account-ids")); } else { discoveryFilter = null; } return AwsKmsMrkAwareMasterKeyProvider.builder() .withDiscoveryMrkRegion(defaultMrkRegion) .buildDiscovery(discoveryFilter); } else if ("raw".equals(type)) { final String provId = (String) mkEntry.get("provider-id"); final String algorithm = (String) mkEntry.get("encryption-algorithm"); if ("aes".equals(algorithm)) { mks.add( JceMasterKey.getInstance( (SecretKey) key.key, provId, key.keyId, "AES/GCM/NoPadding")); } else if ("rsa".equals(algorithm)) { String transformation = "RSA/ECB/"; final String padding = (String) mkEntry.get("padding-algorithm"); if ("pkcs1".equals(padding)) { transformation += "PKCS1Padding"; } else if ("oaep-mgf1".equals(padding)) { final String hashName = ((String) mkEntry.get("padding-hash")).replace("sha", "sha-").toUpperCase(); transformation += "OAEPWith" + hashName + "AndMGF1Padding"; } else { throw new IllegalArgumentException("Unsupported padding:" + padding); } final PublicKey wrappingKey; final PrivateKey unwrappingKey; if (key.key instanceof PublicKey) { wrappingKey = (PublicKey) key.key; unwrappingKey = null; } else { wrappingKey = null; unwrappingKey = (PrivateKey) key.key; } mks.add( JceMasterKey.getInstance( wrappingKey, unwrappingKey, provId, key.keyId, transformation)); } else { throw new IllegalArgumentException("Unsupported algorithm: " + algorithm); } } else { throw new IllegalArgumentException("Unsupported Key Type: " + type); } } return MultipleProviderFactory.buildMultiProvider(mks); }; @SuppressWarnings("unchecked") final Map<String, Object> resultSpec = (Map<String, Object>) data.get("result"); final ResultMatcher matcher = parseResultMatcher(jar, resultSpec); String decryptionMethodSpec = (String) data.get("decryption-method"); SignaturePolicy signaturePolicy = SignaturePolicy.AllowEncryptAllowDecrypt; if (decryptionMethodSpec != null) { if ("streaming-unsigned-only".equals(decryptionMethodSpec)) { signaturePolicy = SignaturePolicy.AllowEncryptForbidDecrypt; } else { throw new IllegalArgumentException( "Unsupported Decryption Method: " + decryptionMethodSpec); } } return new TestCase(testName, ciphertextURL, mkpSupplier, matcher, signaturePolicy); } @SuppressWarnings("unchecked") private static TestCase parseTest( String testName, Map<String, Object> data, Map<String, KeyEntry> keys, JarFile jar, com.amazonaws.encryptionsdk.kmssdkv2.KmsMasterKeyProvider kmsProv) throws IOException { final String ciphertextURL = (String) data.get("ciphertext"); cacheData(jar, ciphertextURL); Supplier<MasterKeyProvider<?>> mkpSupplier = () -> { @SuppressWarnings("generic") final List<MasterKey<?>> mks = new ArrayList<>(); for (Map<String, Object> mkEntry : (List<Map<String, Object>>) data.get("master-keys")) { final String type = (String) mkEntry.get("type"); final String keyName = (String) mkEntry.get("key"); final KeyEntry key = keys.get(keyName); if ("aws-kms".equals(type)) { mks.add(kmsProv.getMasterKey(key.keyId)); } else if ("aws-kms-mrk-aware".equals(type)) { com.amazonaws.encryptionsdk.kmssdkv2.AwsKmsMrkAwareMasterKeyProvider provider = com.amazonaws.encryptionsdk.kmssdkv2.AwsKmsMrkAwareMasterKeyProvider.builder() .buildStrict(key.keyId); mks.add(provider.getMasterKey(key.keyId)); } else if ("aws-kms-mrk-aware-discovery".equals(type)) { final String defaultMrkRegion = (String) mkEntry.get("default-mrk-region"); final Map<String, Object> discoveryFilterSpec = (Map<String, Object>) mkEntry.get("aws-kms-discovery-filter"); final DiscoveryFilter discoveryFilter; if (discoveryFilterSpec != null) { discoveryFilter = new DiscoveryFilter( (String) discoveryFilterSpec.get("partition"), (List<String>) discoveryFilterSpec.get("account-ids")); } else { discoveryFilter = null; } return com.amazonaws.encryptionsdk.kmssdkv2.AwsKmsMrkAwareMasterKeyProvider.builder() .discoveryMrkRegion(Region.of(defaultMrkRegion)) .buildDiscovery(discoveryFilter); } else if ("raw".equals(type)) { final String provId = (String) mkEntry.get("provider-id"); final String algorithm = (String) mkEntry.get("encryption-algorithm"); if ("aes".equals(algorithm)) { mks.add( JceMasterKey.getInstance( (SecretKey) key.key, provId, key.keyId, "AES/GCM/NoPadding")); } else if ("rsa".equals(algorithm)) { String transformation = "RSA/ECB/"; final String padding = (String) mkEntry.get("padding-algorithm"); if ("pkcs1".equals(padding)) { transformation += "PKCS1Padding"; } else if ("oaep-mgf1".equals(padding)) { final String hashName = ((String) mkEntry.get("padding-hash")).replace("sha", "sha-").toUpperCase(); transformation += "OAEPWith" + hashName + "AndMGF1Padding"; } else { throw new IllegalArgumentException("Unsupported padding:" + padding); } final PublicKey wrappingKey; final PrivateKey unwrappingKey; if (key.key instanceof PublicKey) { wrappingKey = (PublicKey) key.key; unwrappingKey = null; } else { wrappingKey = null; unwrappingKey = (PrivateKey) key.key; } mks.add( JceMasterKey.getInstance( wrappingKey, unwrappingKey, provId, key.keyId, transformation)); } else { throw new IllegalArgumentException("Unsupported algorithm: " + algorithm); } } else { throw new IllegalArgumentException("Unsupported Key Type: " + type); } } return MultipleProviderFactory.buildMultiProvider(mks); }; @SuppressWarnings("unchecked") final Map<String, Object> resultSpec = (Map<String, Object>) data.get("result"); final ResultMatcher matcher = parseResultMatcher(jar, resultSpec); String decryptionMethodSpec = (String) data.get("decryption-method"); SignaturePolicy signaturePolicy = SignaturePolicy.AllowEncryptAllowDecrypt; if (decryptionMethodSpec != null) { if ("streaming-unsigned-only".equals(decryptionMethodSpec)) { signaturePolicy = SignaturePolicy.AllowEncryptForbidDecrypt; } else { throw new IllegalArgumentException( "Unsupported Decryption Method: " + decryptionMethodSpec); } } return new TestCase(testName, ciphertextURL, mkpSupplier, matcher, signaturePolicy); } private static ResultMatcher parseResultMatcher( final JarFile jar, final Map<String, Object> result) throws IOException { if (result.size() != 1) { throw new IllegalArgumentException("Unsupported result specification: " + result); } Map.Entry<String, Object> pair = result.entrySet().iterator().next(); if (pair.getKey().equals("output")) { Map<String, String> outputSpec = (Map<String, String>) pair.getValue(); String plaintextUrl = outputSpec.get("plaintext"); cacheData(jar, plaintextUrl); return new OutputResultMatcher(plaintextUrl); } else if (pair.getKey().equals("error")) { Map<String, String> errorSpec = (Map<String, String>) pair.getValue(); String errorDescription = errorSpec.get("error-description"); return new ErrorResultMatcher(errorDescription); } else { throw new IllegalArgumentException("Unsupported result specification: " + result); } } @SuppressWarnings("unchecked") private static Map<String, KeyEntry> parseKeyManifest(final Map<String, Object> keysManifest) throws GeneralSecurityException { // check our type final Map<String, Object> metaData = (Map<String, Object>) keysManifest.get("manifest"); if (!"keys".equals(metaData.get("type"))) { throw new IllegalArgumentException("Invalid manifest type: " + metaData.get("type")); } if (!Integer.valueOf(3).equals(metaData.get("version"))) { throw new IllegalArgumentException("Invalid manifest version: " + metaData.get("version")); } final Map<String, KeyEntry> result = new HashMap<>(); Map<String, Object> keys = (Map<String, Object>) keysManifest.get("keys"); for (Map.Entry<String, Object> entry : keys.entrySet()) { final String name = entry.getKey(); final Map<String, Object> data = (Map<String, Object>) entry.getValue(); final String keyType = (String) data.get("type"); final String encoding = (String) data.get("encoding"); final String keyId = (String) data.get("key-id"); final String material = (String) data.get("material"); // May be null final String algorithm = (String) data.get("algorithm"); // May be null final KeyEntry keyEntry; final KeyFactory kf; switch (keyType) { case "symmetric": if (!"base64".equals(encoding)) { throw new IllegalArgumentException( format("Key %s is symmetric but has encoding %s", keyId, encoding)); } keyEntry = new KeyEntry( name, keyId, keyType, new SecretKeySpec(Base64.decode(material), algorithm.toUpperCase())); break; case "private": kf = KeyFactory.getInstance(algorithm); if (!"pem".equals(encoding)) { throw new IllegalArgumentException( format("Key %s is private but has encoding %s", keyId, encoding)); } byte[] pkcs8Key = parsePem(material); keyEntry = new KeyEntry( name, keyId, keyType, kf.generatePrivate(new PKCS8EncodedKeySpec(pkcs8Key))); break; case "public": kf = KeyFactory.getInstance(algorithm); if (!"pem".equals(encoding)) { throw new IllegalArgumentException( format("Key %s is private but has encoding %s", keyId, encoding)); } byte[] x509Key = parsePem(material); keyEntry = new KeyEntry( name, keyId, keyType, kf.generatePublic(new X509EncodedKeySpec(x509Key))); break; case "aws-kms": keyEntry = new KeyEntry(name, keyId, keyType, null); break; default: throw new IllegalArgumentException("Unsupported key type: " + keyType); } result.put(name, keyEntry); } return result; } private static byte[] parsePem(String pem) { final String stripped = pem.replaceAll("-+[A-Z ]+-+", ""); return Base64.decode(stripped); } private static class KeyEntry { final String name; final String keyId; final String type; final Key key; private KeyEntry(String name, String keyId, String type, Key key) { this.name = name; this.keyId = keyId; this.type = type; this.key = key; } } private static class TestCase { private final String name; private final String ciphertextPath; private final ResultMatcher matcher; private final Supplier<MasterKeyProvider<?>> mkpSupplier; private final SignaturePolicy signaturePolicy; private TestCase( String name, String ciphertextPath, Supplier<MasterKeyProvider<?>> mkpSupplier, ResultMatcher matcher, SignaturePolicy signaturePolicy) { this.name = name; this.ciphertextPath = ciphertextPath; this.matcher = matcher; this.mkpSupplier = mkpSupplier; this.signaturePolicy = signaturePolicy; } } private interface ResultMatcher { void Match(Callable<byte[]> decryptor) throws Exception; } private static class OutputResultMatcher implements ResultMatcher { private final String plaintextPath; private OutputResultMatcher(String plaintextPath) { this.plaintextPath = plaintextPath; } @Override public void Match(Callable<byte[]> decryptor) throws Exception { final byte[] plaintext = decryptor.call(); final byte[] expectedPlaintext = cachedData.get(plaintextPath); Assert.assertArrayEquals(expectedPlaintext, plaintext); } } private static class ErrorResultMatcher implements ResultMatcher { private final String errorDescription; private ErrorResultMatcher(String errorDescription) { this.errorDescription = errorDescription; } @Override public void Match(Callable<byte[]> decryptor) { Assert.assertThrows( "Decryption expected to fail (" + errorDescription + ") but succeeded", Exception.class, decryptor::call); } } }
717
0
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk/CommitmentKATRunner.java
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package com.amazonaws.encryptionsdk; import static com.amazonaws.encryptionsdk.TestUtils.assertThrows; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import com.amazonaws.encryptionsdk.exception.BadCiphertextException; import com.amazonaws.encryptionsdk.internal.Utils; import com.amazonaws.encryptionsdk.kms.KmsMasterKeyProvider; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import java.io.File; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Map; import javax.crypto.spec.SecretKeySpec; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; @RunWith(Parameterized.class) public class CommitmentKATRunner { private String comment; private String keyringType; private byte[] ciphertext; private byte[] commitment; private byte[] plaintext; private byte[] decryptedDEK; private byte[] messageId; private byte[] header; private Map<String, String> encryptionContext; private boolean status; private static final String TEST_VECTOR_RESOURCE_PATH = "/commitment-test-vectors.json"; public CommitmentKATRunner( String comment, String keyringType, byte[] ciphertext, byte[] commitment, byte[] plaintext, byte[] decryptedDEK, byte[] messageId, byte[] header, Map<String, String> encryptionContext, boolean status) throws Exception { this.comment = comment; this.keyringType = keyringType; this.ciphertext = ciphertext; this.commitment = commitment; this.plaintext = plaintext; this.decryptedDEK = decryptedDEK; this.messageId = messageId; this.header = header; this.encryptionContext = encryptionContext; this.status = status; } @Parameters( name = "{index}: testDecryptCommitment({0}, {1}, {2}, {3}, {4}, {5}, {6}, {7}, {8}, {9})") public static Collection<Object[]> data() throws Exception { final String testVectorsName = CommitmentKATRunner.class.getResource(TEST_VECTOR_RESOURCE_PATH).getPath(); final File ciphertextManifestFile = new File(testVectorsName); final List<Object[]> testCases_ = new ArrayList<Object[]>(); if (!ciphertextManifestFile.exists()) { throw new IllegalStateException( "Missing commitment test vectors file from src/test/resources."); } final ObjectMapper ciphertextManifestMapper = new ObjectMapper(); final Map<String, Object> ciphertextManifest = ciphertextManifestMapper.readValue( ciphertextManifestFile, new TypeReference<Map<String, Object>>() {}); final List<Map<String, Object>> testCases = (List<Map<String, Object>>) ciphertextManifest.get("tests"); for (Map<String, Object> test : testCases) { final String keyringType = (String) test.get("keyring-type"); final byte[] decryptedDEK = Utils.decodeBase64String((String) test.get("decrypted-dek")); final byte[] ciphertext = Utils.decodeBase64String((String) test.get("ciphertext")); final byte[] commitment = Utils.decodeBase64String((String) test.get("commitment")); final byte[] messageId = Utils.decodeBase64String((String) test.get("message-id")); final byte[] header = Utils.decodeBase64String((String) test.get("header")); final boolean status = (boolean) test.get("status"); final String comment = (String) test.get("comment"); final Map<String, String> encryptionContext = (Map<String, String>) test.get("encryption-context"); // plaintext is available for cases which succeed decryption byte[] plaintext = null; if (status) { final List<String> plaintextFrames = (List<String>) test.get("plaintext-frames"); plaintext = String.join("", plaintextFrames).getBytes(StandardCharsets.UTF_8); } testCases_.add( new Object[] { comment, keyringType, ciphertext, commitment, plaintext, decryptedDEK, messageId, header, encryptionContext, status }); } return testCases_; } @Test public void testDecryptCommitment() throws Exception { final AwsCrypto crypto = AwsCrypto.builder() .withCommitmentPolicy(CommitmentPolicy.ForbidEncryptAllowDecrypt) .build(); // Determine what MKP to test with based on whether the test case was create using kms or not. // If it was, we can test decryption of the message completely end to end by using a // Discovery KMS MKP. // Otherwise, we must mock out a provider that just returns the data encryption key associated // with the test case. final MasterKeyProvider mkp; switch (keyringType) { case "aws-kms": mkp = KmsMasterKeyProvider.builder().buildDiscovery(); break; case "static": default: mkp = mock(MasterKeyProvider.class); DataKey dataKey = new DataKey( // All committing algorithms use HkdfSHA512 for // the kdf. If this changes, the test vectors // will need to indicate what algorithm suite // was used in order for this test to // appropriately set the secret key spec's algorithm new SecretKeySpec(decryptedDEK, "HkdfSHA512"), new byte[0], new byte[0], null); when(mkp.decryptDataKey(any(), any(), any())).thenReturn(dataKey); break; } // Ensure tests that are expected to fail do so with the right exception and error message if (!status) { assertThrows( BadCiphertextException.class, "Key commitment validation failed. Key identity does not " + "match the identity asserted in the message. Halting processing of this message.", () -> crypto.decryptData(mkp, ciphertext)); return; } // Otherwise ensure our result matches the expected commitment data final CryptoResult decryptResult = crypto.decryptData(mkp, ciphertext); assertArrayEquals(decryptResult.getHeaders().getSuiteData(), commitment); assertArrayEquals(decryptResult.getHeaders().getMessageId(), messageId); assertArrayEquals(decryptResult.getHeaders().toByteArray(), header); assertTrue(decryptResult.getEncryptionContext().equals(encryptionContext)); assertArrayEquals((byte[]) decryptResult.getResult(), plaintext); } }
718
0
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk/ParsedCiphertextTest.java
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package com.amazonaws.encryptionsdk; import static com.amazonaws.encryptionsdk.TestUtils.assertThrows; import static org.junit.Assert.*; import static org.mockito.Mockito.spy; import com.amazonaws.encryptionsdk.exception.AwsCryptoException; import com.amazonaws.encryptionsdk.exception.BadCiphertextException; import com.amazonaws.encryptionsdk.internal.StaticMasterKey; import com.amazonaws.encryptionsdk.model.CiphertextHeaders; import com.amazonaws.encryptionsdk.multi.MultipleProviderFactory; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import org.junit.Before; import org.junit.Test; public class ParsedCiphertextTest extends CiphertextHeaders { private static final int MESSAGE_FORMAT_MAX_EDKS = (1 << 16) - 1; private StaticMasterKey masterKeyProvider; private AwsCrypto encryptionClient_; @Before public void init() { masterKeyProvider = spy(new StaticMasterKey("testmaterial")); encryptionClient_ = AwsCrypto.builder() .withCommitmentPolicy(CommitmentPolicy.ForbidEncryptAllowDecrypt) .build(); encryptionClient_.setEncryptionAlgorithm( CryptoAlgorithm.ALG_AES_128_GCM_IV12_TAG16_HKDF_SHA256); } @Test() public void goodParsedCiphertext() { final int byteSize = 0; final int frameSize = 0; final byte[] plaintextBytes = new byte[byteSize]; final Map<String, String> encryptionContext = new HashMap<String, String>(1); encryptionContext.put("ENC1", "ParsedCiphertext test with %d" + byteSize); encryptionClient_.setEncryptionFrameSize(frameSize); final byte[] cipherText = encryptionClient_ .encryptData(masterKeyProvider, plaintextBytes, encryptionContext) .getResult(); final ParsedCiphertext pCt = new ParsedCiphertext(cipherText); assertNotNull(pCt.getCiphertext()); assertTrue(pCt.getOffset() > 0); } @Test(expected = BadCiphertextException.class) public void incompleteZeroByteCiphertext() { final byte[] cipherText = {}; ParsedCiphertext pCt = new ParsedCiphertext(cipherText); } @Test(expected = BadCiphertextException.class) public void incompleteSingleByteCiphertext() { final byte[] cipherText = {1 /* Original ciphertext version number */}; ParsedCiphertext pCt = new ParsedCiphertext(cipherText); } @Test(expected = BadCiphertextException.class) public void incompleteCiphertext() { final int byteSize = 0; final int frameSize = 0; final byte[] plaintextBytes = new byte[byteSize]; final Map<String, String> encryptionContext = new HashMap<String, String>(1); encryptionContext.put("ENC1", "ParsedCiphertext test with %d" + byteSize); encryptionClient_.setEncryptionFrameSize(frameSize); final byte[] cipherText = encryptionClient_ .encryptData(masterKeyProvider, plaintextBytes, encryptionContext) .getResult(); ParsedCiphertext pCt = new ParsedCiphertext(cipherText); byte[] incompleteCiphertext = Arrays.copyOf(pCt.getCiphertext(), pCt.getOffset() - 1); ParsedCiphertext badPCt = new ParsedCiphertext(incompleteCiphertext); } private MasterKeyProvider<?> providerWithEdks(int numEdks) { List<MasterKeyProvider<?>> providers = new ArrayList<>(); for (int i = 0; i < numEdks; i++) { providers.add(masterKeyProvider); } return MultipleProviderFactory.buildMultiProvider(providers); } @Test public void lessThanMaxEdks() { MasterKeyProvider<?> provider = providerWithEdks(2); CryptoResult<byte[], ?> result = encryptionClient_.encryptData(provider, new byte[] {1}); ParsedCiphertext ciphertext = new ParsedCiphertext(result.getResult(), 3); assertEquals(ciphertext.getEncryptedKeyBlobCount(), 2); } @Test public void equalToMaxEdks() { MasterKeyProvider<?> provider = providerWithEdks(3); CryptoResult<byte[], ?> result = encryptionClient_.encryptData(provider, new byte[] {1}); ParsedCiphertext ciphertext = new ParsedCiphertext(result.getResult(), 3); assertEquals(ciphertext.getEncryptedKeyBlobCount(), 3); } @Test public void failMoreThanMaxEdks() { MasterKeyProvider<?> provider = providerWithEdks(4); CryptoResult<byte[], ?> result = encryptionClient_.encryptData(provider, new byte[] {1}); assertThrows( AwsCryptoException.class, "Ciphertext encrypted data keys exceed maxEncryptedDataKeys", () -> new ParsedCiphertext(result.getResult(), 3)); } @Test public void noMaxEdks() { MasterKeyProvider<?> provider = providerWithEdks(MESSAGE_FORMAT_MAX_EDKS); CryptoResult<byte[], ?> result = encryptionClient_.encryptData(provider, new byte[] {1}); // explicit no-max ParsedCiphertext ciphertext = new ParsedCiphertext(result.getResult(), CiphertextHeaders.NO_MAX_ENCRYPTED_DATA_KEYS); assertEquals(ciphertext.getEncryptedKeyBlobCount(), MESSAGE_FORMAT_MAX_EDKS); // implicit no-max ciphertext = new ParsedCiphertext(result.getResult()); assertEquals(ciphertext.getEncryptedKeyBlobCount(), MESSAGE_FORMAT_MAX_EDKS); } }
719
0
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk/kms/MockKMSClient.java
/* * Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except * in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.amazonaws.encryptionsdk.kms; import com.amazonaws.AmazonClientException; import com.amazonaws.AmazonServiceException; import com.amazonaws.AmazonWebServiceRequest; import com.amazonaws.ResponseMetadata; import com.amazonaws.regions.Region; import com.amazonaws.regions.Regions; import com.amazonaws.services.kms.AWSKMSClient; import com.amazonaws.services.kms.model.CreateAliasRequest; import com.amazonaws.services.kms.model.CreateAliasResult; import com.amazonaws.services.kms.model.CreateGrantRequest; import com.amazonaws.services.kms.model.CreateGrantResult; import com.amazonaws.services.kms.model.CreateKeyRequest; import com.amazonaws.services.kms.model.CreateKeyResult; import com.amazonaws.services.kms.model.DecryptRequest; import com.amazonaws.services.kms.model.DecryptResult; import com.amazonaws.services.kms.model.DeleteAliasRequest; import com.amazonaws.services.kms.model.DeleteAliasResult; import com.amazonaws.services.kms.model.DescribeKeyRequest; import com.amazonaws.services.kms.model.DescribeKeyResult; import com.amazonaws.services.kms.model.DisableKeyRequest; import com.amazonaws.services.kms.model.DisableKeyResult; import com.amazonaws.services.kms.model.DisableKeyRotationRequest; import com.amazonaws.services.kms.model.DisableKeyRotationResult; import com.amazonaws.services.kms.model.EnableKeyRequest; import com.amazonaws.services.kms.model.EnableKeyResult; import com.amazonaws.services.kms.model.EnableKeyRotationRequest; import com.amazonaws.services.kms.model.EnableKeyRotationResult; import com.amazonaws.services.kms.model.EncryptRequest; import com.amazonaws.services.kms.model.EncryptResult; import com.amazonaws.services.kms.model.GenerateDataKeyRequest; import com.amazonaws.services.kms.model.GenerateDataKeyResult; import com.amazonaws.services.kms.model.GenerateDataKeyWithoutPlaintextRequest; import com.amazonaws.services.kms.model.GenerateDataKeyWithoutPlaintextResult; import com.amazonaws.services.kms.model.GenerateRandomRequest; import com.amazonaws.services.kms.model.GenerateRandomResult; import com.amazonaws.services.kms.model.GetKeyPolicyRequest; import com.amazonaws.services.kms.model.GetKeyPolicyResult; import com.amazonaws.services.kms.model.GetKeyRotationStatusRequest; import com.amazonaws.services.kms.model.GetKeyRotationStatusResult; import com.amazonaws.services.kms.model.InvalidCiphertextException; import com.amazonaws.services.kms.model.KeyMetadata; import com.amazonaws.services.kms.model.KeyUsageType; import com.amazonaws.services.kms.model.ListAliasesRequest; import com.amazonaws.services.kms.model.ListAliasesResult; import com.amazonaws.services.kms.model.ListGrantsRequest; import com.amazonaws.services.kms.model.ListGrantsResult; import com.amazonaws.services.kms.model.ListKeyPoliciesRequest; import com.amazonaws.services.kms.model.ListKeyPoliciesResult; import com.amazonaws.services.kms.model.ListKeysRequest; import com.amazonaws.services.kms.model.ListKeysResult; import com.amazonaws.services.kms.model.NotFoundException; import com.amazonaws.services.kms.model.PutKeyPolicyRequest; import com.amazonaws.services.kms.model.PutKeyPolicyResult; import com.amazonaws.services.kms.model.ReEncryptRequest; import com.amazonaws.services.kms.model.ReEncryptResult; import com.amazonaws.services.kms.model.RetireGrantRequest; import com.amazonaws.services.kms.model.RetireGrantResult; import com.amazonaws.services.kms.model.RevokeGrantRequest; import com.amazonaws.services.kms.model.RevokeGrantResult; import com.amazonaws.services.kms.model.UpdateKeyDescriptionRequest; import com.amazonaws.services.kms.model.UpdateKeyDescriptionResult; import java.nio.ByteBuffer; import java.security.SecureRandom; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.UUID; public class MockKMSClient extends AWSKMSClient { private static final SecureRandom rnd = new SecureRandom(); private static final String ACCOUNT_ID = "01234567890"; private final Map<DecryptMapKey, DecryptResult> results_ = new HashMap<>(); private final Set<String> activeKeys = new HashSet<>(); private final Map<String, String> keyAliases = new HashMap<>(); private Region region_ = Region.getRegion(Regions.DEFAULT_REGION); @Override public CreateAliasResult createAlias(CreateAliasRequest arg0) throws AmazonServiceException, AmazonClientException { assertExists(arg0.getTargetKeyId()); keyAliases.put("alias/" + arg0.getAliasName(), keyAliases.get(arg0.getTargetKeyId())); return new CreateAliasResult(); } @Override public CreateGrantResult createGrant(CreateGrantRequest arg0) throws AmazonServiceException, AmazonClientException { throw new java.lang.UnsupportedOperationException(); } @Override public CreateKeyResult createKey() throws AmazonServiceException, AmazonClientException { return createKey(new CreateKeyRequest()); } @Override public CreateKeyResult createKey(CreateKeyRequest req) throws AmazonServiceException, AmazonClientException { String keyId = UUID.randomUUID().toString(); String arn = "arn:aws:kms:" + region_.getName() + ":" + ACCOUNT_ID + ":key/" + keyId; activeKeys.add(arn); keyAliases.put(keyId, arn); keyAliases.put(arn, arn); CreateKeyResult result = new CreateKeyResult(); result.setKeyMetadata( new KeyMetadata() .withAWSAccountId(ACCOUNT_ID) .withCreationDate(new Date()) .withDescription(req.getDescription()) .withEnabled(true) .withKeyId(keyId) .withKeyUsage(KeyUsageType.ENCRYPT_DECRYPT) .withArn(arn)); return result; } @Override public DecryptResult decrypt(DecryptRequest req) throws AmazonServiceException, AmazonClientException { DecryptResult result = results_.get(new DecryptMapKey(req)); if (result != null) { // Copy it to avoid external modification DecryptResult copy = new DecryptResult(); copy.setKeyId(retrieveArn(result.getKeyId())); byte[] pt = new byte[result.getPlaintext().limit()]; result.getPlaintext().get(pt); result.getPlaintext().rewind(); copy.setPlaintext(ByteBuffer.wrap(pt)); return copy; } else { throw new InvalidCiphertextException("Invalid Ciphertext"); } } @Override public DeleteAliasResult deleteAlias(DeleteAliasRequest arg0) throws AmazonServiceException, AmazonClientException { throw new java.lang.UnsupportedOperationException(); } @Override public DescribeKeyResult describeKey(DescribeKeyRequest arg0) throws AmazonServiceException, AmazonClientException { final String arn = retrieveArn(arg0.getKeyId()); final KeyMetadata keyMetadata = new KeyMetadata().withArn(arn).withKeyId(arn); final DescribeKeyResult describeKeyResult = new DescribeKeyResult().withKeyMetadata(keyMetadata); return describeKeyResult; } @Override public DisableKeyResult disableKey(DisableKeyRequest arg0) throws AmazonServiceException, AmazonClientException { throw new java.lang.UnsupportedOperationException(); } @Override public DisableKeyRotationResult disableKeyRotation(DisableKeyRotationRequest arg0) throws AmazonServiceException, AmazonClientException { throw new java.lang.UnsupportedOperationException(); } @Override public EnableKeyResult enableKey(EnableKeyRequest arg0) throws AmazonServiceException, AmazonClientException { throw new java.lang.UnsupportedOperationException(); } @Override public EnableKeyRotationResult enableKeyRotation(EnableKeyRotationRequest arg0) throws AmazonServiceException, AmazonClientException { throw new java.lang.UnsupportedOperationException(); } @Override public EncryptResult encrypt(EncryptRequest req) throws AmazonServiceException, AmazonClientException { // We internally delegate to encrypt, so as to avoid mockito detecting extra calls to encrypt // when spying on the // MockKMSClient, we put the real logic into a separate function. return encrypt0(req); } private EncryptResult encrypt0(EncryptRequest req) throws AmazonServiceException, AmazonClientException { final byte[] cipherText = new byte[512]; rnd.nextBytes(cipherText); DecryptResult dec = new DecryptResult(); dec.withKeyId(retrieveArn(req.getKeyId())).withPlaintext(req.getPlaintext().asReadOnlyBuffer()); ByteBuffer ctBuff = ByteBuffer.wrap(cipherText); results_.put(new DecryptMapKey(ctBuff, req.getEncryptionContext()), dec); String arn = retrieveArn(req.getKeyId()); return new EncryptResult().withCiphertextBlob(ctBuff).withKeyId(arn); } @Override public GenerateDataKeyResult generateDataKey(GenerateDataKeyRequest req) throws AmazonServiceException, AmazonClientException { byte[] pt; if (req.getKeySpec() != null) { if (req.getKeySpec().contains("256")) { pt = new byte[32]; } else if (req.getKeySpec().contains("128")) { pt = new byte[16]; } else { throw new java.lang.UnsupportedOperationException(); } } else { pt = new byte[req.getNumberOfBytes()]; } rnd.nextBytes(pt); ByteBuffer ptBuff = ByteBuffer.wrap(pt); EncryptResult encryptResult = encrypt0( new EncryptRequest() .withKeyId(req.getKeyId()) .withPlaintext(ptBuff) .withEncryptionContext(req.getEncryptionContext())); String arn = retrieveArn(req.getKeyId()); return new GenerateDataKeyResult() .withKeyId(arn) .withCiphertextBlob(encryptResult.getCiphertextBlob()) .withPlaintext(ptBuff); } @Override public GenerateDataKeyWithoutPlaintextResult generateDataKeyWithoutPlaintext( GenerateDataKeyWithoutPlaintextRequest req) throws AmazonServiceException, AmazonClientException { GenerateDataKeyRequest generateDataKeyRequest = new GenerateDataKeyRequest() .withEncryptionContext(req.getEncryptionContext()) .withGrantTokens(req.getGrantTokens()) .withKeyId(req.getKeyId()) .withKeySpec(req.getKeySpec()) .withNumberOfBytes(req.getNumberOfBytes()); GenerateDataKeyResult generateDataKey = generateDataKey(generateDataKeyRequest); String arn = retrieveArn(req.getKeyId()); return new GenerateDataKeyWithoutPlaintextResult() .withCiphertextBlob(generateDataKey.getCiphertextBlob()) .withKeyId(arn); } @Override public GenerateRandomResult generateRandom() throws AmazonServiceException, AmazonClientException { throw new java.lang.UnsupportedOperationException(); } @Override public GenerateRandomResult generateRandom(GenerateRandomRequest arg0) throws AmazonServiceException, AmazonClientException { throw new java.lang.UnsupportedOperationException(); } @Override public ResponseMetadata getCachedResponseMetadata(AmazonWebServiceRequest arg0) { throw new java.lang.UnsupportedOperationException(); } @Override public GetKeyPolicyResult getKeyPolicy(GetKeyPolicyRequest arg0) throws AmazonServiceException, AmazonClientException { throw new java.lang.UnsupportedOperationException(); } @Override public GetKeyRotationStatusResult getKeyRotationStatus(GetKeyRotationStatusRequest arg0) throws AmazonServiceException, AmazonClientException { throw new java.lang.UnsupportedOperationException(); } @Override public ListAliasesResult listAliases() throws AmazonServiceException, AmazonClientException { throw new java.lang.UnsupportedOperationException(); } @Override public ListAliasesResult listAliases(ListAliasesRequest arg0) throws AmazonServiceException, AmazonClientException { throw new java.lang.UnsupportedOperationException(); } @Override public ListGrantsResult listGrants(ListGrantsRequest arg0) throws AmazonServiceException, AmazonClientException { throw new java.lang.UnsupportedOperationException(); } @Override public ListKeyPoliciesResult listKeyPolicies(ListKeyPoliciesRequest arg0) throws AmazonServiceException, AmazonClientException { throw new java.lang.UnsupportedOperationException(); } @Override public ListKeysResult listKeys() throws AmazonServiceException, AmazonClientException { throw new java.lang.UnsupportedOperationException(); } @Override public ListKeysResult listKeys(ListKeysRequest arg0) throws AmazonServiceException, AmazonClientException { throw new java.lang.UnsupportedOperationException(); } @Override public PutKeyPolicyResult putKeyPolicy(PutKeyPolicyRequest arg0) throws AmazonServiceException, AmazonClientException { throw new java.lang.UnsupportedOperationException(); } @Override public ReEncryptResult reEncrypt(ReEncryptRequest arg0) throws AmazonServiceException, AmazonClientException { throw new java.lang.UnsupportedOperationException(); } @Override public RetireGrantResult retireGrant(RetireGrantRequest arg0) throws AmazonServiceException, AmazonClientException { throw new java.lang.UnsupportedOperationException(); } @Override public RevokeGrantResult revokeGrant(RevokeGrantRequest arg0) throws AmazonServiceException, AmazonClientException { throw new java.lang.UnsupportedOperationException(); } @Override public void setEndpoint(String arg0) { // Do nothing } @Override public void setRegion(Region arg0) { region_ = arg0; } @Override public void shutdown() { // Do nothing } @Override public UpdateKeyDescriptionResult updateKeyDescription(UpdateKeyDescriptionRequest arg0) throws AmazonServiceException, AmazonClientException { throw new java.lang.UnsupportedOperationException(); } public void deleteKey(final String keyId) { final String arn = retrieveArn(keyId); activeKeys.remove(arn); } private String retrieveArn(final String keyId) { String arn = keyAliases.get(keyId); assertExists(arn); return arn; } private void assertExists(String keyId) { if (keyAliases.containsKey(keyId)) { keyId = keyAliases.get(keyId); } if (keyId == null || !activeKeys.contains(keyId)) { throw new NotFoundException("Key doesn't exist: " + keyId); } } private static class DecryptMapKey { private final ByteBuffer cipherText; private final Map<String, String> ec; public DecryptMapKey(DecryptRequest req) { cipherText = req.getCiphertextBlob().asReadOnlyBuffer(); if (req.getEncryptionContext() != null) { ec = Collections.unmodifiableMap(new HashMap<String, String>(req.getEncryptionContext())); } else { ec = Collections.emptyMap(); } } public DecryptMapKey(ByteBuffer ctBuff, Map<String, String> ec) { cipherText = ctBuff.asReadOnlyBuffer(); if (ec != null) { this.ec = Collections.unmodifiableMap(new HashMap<String, String>(ec)); } else { this.ec = Collections.emptyMap(); } } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((cipherText == null) ? 0 : cipherText.hashCode()); result = prime * result + ((ec == null) ? 0 : ec.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; DecryptMapKey other = (DecryptMapKey) obj; if (cipherText == null) { if (other.cipherText != null) return false; } else if (!cipherText.equals(other.cipherText)) return false; if (ec == null) { if (other.ec != null) return false; } else if (!ec.equals(other.ec)) return false; return true; } @Override public String toString() { return "DecryptMapKey [cipherText=" + cipherText + ", ec=" + ec + "]"; } } }
720
0
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk/kms/KMSProviderBuilderMockTests.java
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package com.amazonaws.encryptionsdk.kms; import static com.amazonaws.encryptionsdk.multi.MultipleProviderFactory.buildMultiProvider; import static java.util.Collections.singletonList; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.notNull; import static org.mockito.Mockito.atLeastOnce; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; import com.amazonaws.AmazonWebServiceRequest; import com.amazonaws.RequestClientOptions; import com.amazonaws.encryptionsdk.AwsCrypto; import com.amazonaws.encryptionsdk.MasterKeyProvider; import com.amazonaws.encryptionsdk.internal.VersionInfo; import com.amazonaws.encryptionsdk.kms.KmsMasterKeyProvider.RegionalClientSupplier; import com.amazonaws.services.kms.model.CreateAliasRequest; import com.amazonaws.services.kms.model.DecryptRequest; import com.amazonaws.services.kms.model.EncryptRequest; import com.amazonaws.services.kms.model.GenerateDataKeyRequest; import java.util.Arrays; import org.junit.Test; import org.mockito.ArgumentCaptor; public class KMSProviderBuilderMockTests { @Test public void testBareAliasMapping() { MockKMSClient client = spy(new MockKMSClient()); RegionalClientSupplier supplier = mock(RegionalClientSupplier.class); when(supplier.getClient(notNull())).thenReturn(client); String key1 = client.createKey().getKeyMetadata().getKeyId(); client.createAlias(new CreateAliasRequest().withAliasName("foo").withTargetKeyId(key1)); KmsMasterKeyProvider mkp0 = KmsMasterKeyProvider.builder() .withCustomClientFactory(supplier) .withDefaultRegion("us-west-2") .buildStrict("alias/foo"); AwsCrypto.standard().encryptData(mkp0, new byte[0]); } @Test public void testGrantTokenPassthrough_usingMKsetCall() throws Exception { MockKMSClient client = spy(new MockKMSClient()); RegionalClientSupplier supplier = mock(RegionalClientSupplier.class); when(supplier.getClient(any())).thenReturn(client); String key1 = client.createKey().getKeyMetadata().getArn(); String key2 = client.createKey().getKeyMetadata().getArn(); KmsMasterKeyProvider mkp0 = KmsMasterKeyProvider.builder() .withDefaultRegion("us-west-2") .withCustomClientFactory(supplier) .buildStrict(key1, key2); KmsMasterKey mk1 = mkp0.getMasterKey(key1); KmsMasterKey mk2 = mkp0.getMasterKey(key2); mk1.setGrantTokens(singletonList("foo")); mk2.setGrantTokens(singletonList("foo")); MasterKeyProvider<?> mkp = buildMultiProvider(mk1, mk2); byte[] ciphertext = AwsCrypto.standard().encryptData(mkp, new byte[0]).getResult(); ArgumentCaptor<GenerateDataKeyRequest> gdkr = ArgumentCaptor.forClass(GenerateDataKeyRequest.class); verify(client, times(1)).generateDataKey(gdkr.capture()); assertEquals(key1, gdkr.getValue().getKeyId()); assertEquals(1, gdkr.getValue().getGrantTokens().size()); assertEquals("foo", gdkr.getValue().getGrantTokens().get(0)); ArgumentCaptor<EncryptRequest> er = ArgumentCaptor.forClass(EncryptRequest.class); verify(client, times(1)).encrypt(er.capture()); assertEquals(key2, er.getValue().getKeyId()); assertEquals(1, er.getValue().getGrantTokens().size()); assertEquals("foo", er.getValue().getGrantTokens().get(0)); AwsCrypto.standard().decryptData(mkp, ciphertext); ArgumentCaptor<DecryptRequest> decrypt = ArgumentCaptor.forClass(DecryptRequest.class); verify(client, times(1)).decrypt(decrypt.capture()); assertEquals(1, decrypt.getValue().getGrantTokens().size()); assertEquals("foo", decrypt.getValue().getGrantTokens().get(0)); verify(supplier, atLeastOnce()).getClient("us-west-2"); verifyNoMoreInteractions(supplier); } @Test public void testGrantTokenPassthrough_usingMKPWithers() throws Exception { MockKMSClient client = spy(new MockKMSClient()); RegionalClientSupplier supplier = mock(RegionalClientSupplier.class); when(supplier.getClient(any())).thenReturn(client); String key1 = client.createKey().getKeyMetadata().getArn(); String key2 = client.createKey().getKeyMetadata().getArn(); KmsMasterKeyProvider mkp0 = KmsMasterKeyProvider.builder() .withDefaultRegion("us-west-2") .withCustomClientFactory(supplier) .buildStrict(key1, key2); MasterKeyProvider<?> mkp = mkp0.withGrantTokens("foo"); byte[] ciphertext = AwsCrypto.standard().encryptData(mkp, new byte[0]).getResult(); ArgumentCaptor<GenerateDataKeyRequest> gdkr = ArgumentCaptor.forClass(GenerateDataKeyRequest.class); verify(client, times(1)).generateDataKey(gdkr.capture()); assertEquals(key1, gdkr.getValue().getKeyId()); assertEquals(1, gdkr.getValue().getGrantTokens().size()); assertEquals("foo", gdkr.getValue().getGrantTokens().get(0)); ArgumentCaptor<EncryptRequest> er = ArgumentCaptor.forClass(EncryptRequest.class); verify(client, times(1)).encrypt(er.capture()); assertEquals(key2, er.getValue().getKeyId()); assertEquals(1, er.getValue().getGrantTokens().size()); assertEquals("foo", er.getValue().getGrantTokens().get(0)); mkp = mkp0.withGrantTokens(Arrays.asList("bar")); AwsCrypto.standard().decryptData(mkp, ciphertext); ArgumentCaptor<DecryptRequest> decrypt = ArgumentCaptor.forClass(DecryptRequest.class); verify(client, times(1)).decrypt(decrypt.capture()); assertEquals(1, decrypt.getValue().getGrantTokens().size()); assertEquals("bar", decrypt.getValue().getGrantTokens().get(0)); verify(supplier, atLeastOnce()).getClient("us-west-2"); verifyNoMoreInteractions(supplier); } @Test public void testUserAgentPassthrough() throws Exception { MockKMSClient client = spy(new MockKMSClient()); String key1 = client.createKey().getKeyMetadata().getArn(); String key2 = client.createKey().getKeyMetadata().getArn(); KmsMasterKeyProvider mkp = KmsMasterKeyProvider.builder() .withCustomClientFactory(ignored -> client) .buildStrict(key1, key2); AwsCrypto.standard() .decryptData(mkp, AwsCrypto.standard().encryptData(mkp, new byte[0]).getResult()); ArgumentCaptor<GenerateDataKeyRequest> gdkr = ArgumentCaptor.forClass(GenerateDataKeyRequest.class); verify(client, times(1)).generateDataKey(gdkr.capture()); assertTrue(getUA(gdkr.getValue()).contains(VersionInfo.loadUserAgent())); ArgumentCaptor<EncryptRequest> encr = ArgumentCaptor.forClass(EncryptRequest.class); verify(client, times(1)).encrypt(encr.capture()); assertTrue(getUA(encr.getValue()).contains(VersionInfo.loadUserAgent())); ArgumentCaptor<DecryptRequest> decr = ArgumentCaptor.forClass(DecryptRequest.class); verify(client, times(1)).decrypt(decr.capture()); assertTrue(getUA(decr.getValue()).contains(VersionInfo.loadUserAgent())); } private String getUA(AmazonWebServiceRequest request) { // Note: This test may break in future versions of the AWS SDK, as Marker is documented as being // for internal // use only. return request .getRequestClientOptions() .getClientMarker(RequestClientOptions.Marker.USER_AGENT); } }
721
0
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk/kms/KMSTestFixtures.java
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package com.amazonaws.encryptionsdk.kms; public final class KMSTestFixtures { private KMSTestFixtures() { throw new UnsupportedOperationException( "This class exists to hold static constants and cannot be instantiated."); } /** * These special test keys have been configured to allow Encrypt, Decrypt, and GenerateDataKey * operations from any AWS principal and should be used when adding new KMS tests. * * <p>This should go without saying, but never use these keys for production purposes (as anyone * in the world can decrypt data encrypted using them). */ public static final String US_WEST_2_KEY_ID = "arn:aws:kms:us-west-2:658956600833:key/b3537ef1-d8dc-4780-9f5a-55776cbb2f7f"; public static final String EU_CENTRAL_1_KEY_ID = "arn:aws:kms:eu-central-1:658956600833:key/75414c93-5285-4b57-99c9-30c1cf0a22c2"; public static final String US_EAST_1_MULTI_REGION_KEY_ID = "arn:aws:kms:us-east-1:658956600833:key/mrk-80bd8ecdcd4342aebd84b7dc9da498a7"; public static final String US_WEST_2_MULTI_REGION_KEY_ID = "arn:aws:kms:us-west-2:658956600833:key/mrk-80bd8ecdcd4342aebd84b7dc9da498a7"; public static final String ACCOUNT_ID = "658956600833"; public static final String PARTITION = "aws"; public static final String US_WEST_2 = "us-west-2"; public static final String[] TEST_KEY_IDS = new String[] {US_WEST_2_KEY_ID, EU_CENTRAL_1_KEY_ID}; }
722
0
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk/kms/DiscoveryFilterTest.java
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package com.amazonaws.encryptionsdk.kms; import static com.amazonaws.encryptionsdk.TestUtils.assertThrows; import static org.junit.Assert.assertNotNull; import java.util.Arrays; import java.util.Collections; import java.util.List; import org.junit.Test; public class DiscoveryFilterTest { @Test public void testValidConstruct() throws Exception { DiscoveryFilter filter = new DiscoveryFilter("partition", Arrays.asList("accountId")); assertNotNull(filter); DiscoveryFilter filter2 = new DiscoveryFilter("partition", "accountId1", "accountId2"); assertNotNull(filter2); } @Test public void testConstructWithEmptyPartition() throws Exception { assertThrows( IllegalArgumentException.class, () -> new DiscoveryFilter("", Arrays.asList("accountId"))); assertThrows(IllegalArgumentException.class, () -> new DiscoveryFilter("", "accountId")); } @Test public void testConstructWithNullPartition() throws Exception { assertThrows( IllegalArgumentException.class, () -> new DiscoveryFilter(null, Arrays.asList("accountId"))); assertThrows(IllegalArgumentException.class, () -> new DiscoveryFilter(null, "accountId")); } @Test public void testConstructWithEmptyIds() throws Exception { assertThrows( IllegalArgumentException.class, () -> new DiscoveryFilter("aws", Collections.emptyList())); } @Test public void testConstructWithNullIds() throws Exception { assertThrows( IllegalArgumentException.class, () -> new DiscoveryFilter("aws", (List<String>) null)); } @Test public void testConstructWithIdsContainingEmptyId() throws Exception { assertThrows( IllegalArgumentException.class, () -> new DiscoveryFilter("aws", Arrays.asList("accountId", ""))); assertThrows(IllegalArgumentException.class, () -> new DiscoveryFilter("aws", "accountId", "")); } @Test public void testConstructWithIdsContainingNullId() throws Exception { assertThrows( IllegalArgumentException.class, () -> new DiscoveryFilter("aws", Arrays.asList("accountId", null))); assertThrows( IllegalArgumentException.class, () -> new DiscoveryFilter("aws", "accountId", null)); } }
723
0
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk/kms/MaxEncryptedDataKeysIntegrationTest.java
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package com.amazonaws.encryptionsdk.kms; import static org.junit.Assert.*; import static org.mockito.Mockito.*; import com.amazonaws.encryptionsdk.AwsCrypto; import com.amazonaws.encryptionsdk.TestUtils; import com.amazonaws.encryptionsdk.exception.AwsCryptoException; import com.amazonaws.services.kms.AWSKMS; import com.amazonaws.services.kms.AWSKMSClientBuilder; import java.util.ArrayList; import java.util.List; import org.junit.Before; import org.junit.Test; public class MaxEncryptedDataKeysIntegrationTest { private static final byte[] PLAINTEXT = {1, 2, 3, 4}; private static final int MAX_EDKS = 3; private AWSKMS testClient_; private KmsMasterKeyProvider.RegionalClientSupplier testClientSupplier_; private AwsCrypto testCryptoClient_; @Before public void setup() { testClient_ = spy(AWSKMSClientBuilder.standard().withRegion("us-west-2").build()); testClientSupplier_ = regionName -> { if (regionName.equals("us-west-2")) { return testClient_; } throw new AwsCryptoException( "test supplier only configured for us-west-2 and eu-central-1"); }; testCryptoClient_ = AwsCrypto.standard().toBuilder().withMaxEncryptedDataKeys(MAX_EDKS).build(); } private KmsMasterKeyProvider providerWithEdks(int numKeys) { List<String> keyIds = new ArrayList<>(numKeys); for (int i = 0; i < numKeys; i++) { keyIds.add(KMSTestFixtures.US_WEST_2_KEY_ID); } return KmsMasterKeyProvider.builder() .withCustomClientFactory(testClientSupplier_) .buildStrict(keyIds); } @Test public void encryptDecryptWithLessThanMaxEdks() { KmsMasterKeyProvider provider = providerWithEdks(MAX_EDKS - 1); byte[] ciphertext = testCryptoClient_.encryptData(provider, PLAINTEXT).getResult(); byte[] decrypted = testCryptoClient_.decryptData(provider, ciphertext).getResult(); assertArrayEquals(decrypted, PLAINTEXT); } @Test public void encryptDecryptWithMaxEdks() { KmsMasterKeyProvider provider = providerWithEdks(MAX_EDKS); byte[] ciphertext = testCryptoClient_.encryptData(provider, PLAINTEXT).getResult(); byte[] decrypted = testCryptoClient_.decryptData(provider, ciphertext).getResult(); assertArrayEquals(decrypted, PLAINTEXT); } @Test public void noEncryptWithMoreThanMaxEdks() { KmsMasterKeyProvider provider = providerWithEdks(MAX_EDKS + 1); TestUtils.assertThrows( AwsCryptoException.class, "Encrypted data keys exceed maxEncryptedDataKeys", () -> testCryptoClient_.encryptData(provider, PLAINTEXT)); } @Test public void noDecryptWithMoreThanMaxEdks() { KmsMasterKeyProvider provider = providerWithEdks(MAX_EDKS + 1); byte[] ciphertext = AwsCrypto.standard().encryptData(provider, PLAINTEXT).getResult(); TestUtils.assertThrows( AwsCryptoException.class, "Ciphertext encrypted data keys exceed maxEncryptedDataKeys", () -> testCryptoClient_.decryptData(provider, ciphertext)); verify(testClient_, never()).decrypt(any()); } }
724
0
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk/kms/AwsKmsMrkAwareMasterKeyTest.java
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package com.amazonaws.encryptionsdk.kms; import static com.amazonaws.encryptionsdk.internal.RandomBytesGenerator.generate; import static org.junit.Assert.*; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.*; import static org.mockito.Mockito.mock; import com.amazonaws.AmazonServiceException; import com.amazonaws.RequestClientOptions; import com.amazonaws.encryptionsdk.*; import com.amazonaws.encryptionsdk.exception.CannotUnwrapDataKeyException; import com.amazonaws.encryptionsdk.internal.VersionInfo; import com.amazonaws.encryptionsdk.model.KeyBlob; import com.amazonaws.services.kms.AWSKMS; import com.amazonaws.services.kms.model.*; import java.lang.reflect.Method; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Map; import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec; import org.junit.Test; import org.junit.experimental.runners.Enclosed; import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; @RunWith(Enclosed.class) public class AwsKmsMrkAwareMasterKeyTest { public static class getInstance { @Test public void basic_use() { AWSKMS client = spy(new MockKMSClient()); MasterKeyProvider mkp = mock(MasterKeyProvider.class); // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.6 // = type=test // # On initialization, the caller MUST provide: final AwsKmsMrkAwareMasterKey test = AwsKmsMrkAwareMasterKey.getInstance( client, "arn:aws:kms:us-west-2:658956600833:key/b3537ef1-d8dc-4780-9f5a-55776cbb2f7f", mkp); // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.5 // = type=test // # MUST implement the Master Key Interface (../master-key- // # interface.md#interface) assertTrue(MasterKey.class.isInstance(test)); } @Test // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.6 // = type=test // # The AWS KMS key identifier MUST NOT be null or empty. public void requires_valid_identifiers() { AWSKMS client = spy(new MockKMSClient()); MasterKeyProvider mkp = mock(MasterKeyProvider.class); assertThrows( IllegalArgumentException.class, () -> AwsKmsMrkAwareMasterKey.getInstance(client, "", mkp)); assertThrows( IllegalArgumentException.class, () -> AwsKmsMrkAwareMasterKey.getInstance(client, null, mkp)); // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.6 // = type=test // # The AWS KMS // # key identifier MUST be a valid identifier (aws-kms-key-arn.md#a- // # valid-aws-kms-identifier). assertThrows( IllegalArgumentException.class, () -> AwsKmsMrkAwareMasterKey.getInstance( client, "arn:aws:dynamodb:us-east-2:123456789012:table/myDynamoDBTable", mkp)); } @Test // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.6 // = type=test // # The AWS KMS SDK client MUST not be null. public void requires_valid_client() { MasterKeyProvider mkp = mock(MasterKeyProvider.class); assertThrows( IllegalArgumentException.class, () -> AwsKmsMrkAwareMasterKey.getInstance( null, "arn:aws:kms:us-west-2:658956600833:key/b3537ef1-d8dc-4780-9f5a-55776cbb2f7f", mkp)); } @Test public void requires_valid_provider() { AWSKMS client = spy(new MockKMSClient()); assertThrows( IllegalArgumentException.class, () -> AwsKmsMrkAwareMasterKey.getInstance( client, "arn:aws:kms:us-west-2:658956600833:key/b3537ef1-d8dc-4780-9f5a-55776cbb2f7f", null)); } } public static class generateDataKey { @Test public void basic_use() { final CryptoAlgorithm ALGORITHM_SUITE = CryptoAlgorithm.ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA256; final List<String> GRANT_TOKENS = Collections.singletonList("testGrantToken"); final Map<String, String> ENCRYPTION_CONTEXT = Collections.singletonMap("myKey", "myValue"); final String keyIdentifier = "arn:aws:kms:us-west-2:658956600833:key/b3537ef1-d8dc-4780-9f5a-55776cbb2f7f"; final ByteBuffer udk = ByteBuffer.allocate(ALGORITHM_SUITE.getDataKeyLength()); final ByteBuffer ciphertext = ByteBuffer.allocate(10); final AWSKMS client = mock(AWSKMS.class); when(client.generateDataKey(any())) .thenReturn( new GenerateDataKeyResult() .withPlaintext(udk) .withKeyId(keyIdentifier) .withCiphertextBlob(ciphertext)); final MasterKeyProvider mkp = mock(MasterKeyProvider.class); when(mkp.getDefaultProviderId()).thenReturn("aws-kms"); AwsKmsMrkAwareMasterKey masterKey = AwsKmsMrkAwareMasterKey.getInstance(client, keyIdentifier, mkp); // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.6 // = type=test // # The master key MUST be able to be configured with an optional list of // # Grant Tokens. masterKey.setGrantTokens(GRANT_TOKENS); // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.10 // = type=test // # The inputs MUST be the same as the Master Key Generate Data Key // # (../master-key-interface.md#generate-data-key) interface. DataKey<AwsKmsMrkAwareMasterKey> test = masterKey.generateDataKey(ALGORITHM_SUITE, ENCRYPTION_CONTEXT); ArgumentCaptor<GenerateDataKeyRequest> gr = ArgumentCaptor.forClass(GenerateDataKeyRequest.class); // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.10 // = type=test // # This // # master key MUST use the configured AWS KMS client to make an AWS KMS // # GenerateDatakey (https://docs.aws.amazon.com/kms/latest/APIReference/ // # API_GenerateDataKey.html) request constructed as follows: verify(client, times(1)).generateDataKey(gr.capture()); // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.10 // = type=test // # The output MUST be the same as the Master Key Generate Data Key // # (../master-key-interface.md#generate-data-key) interface. assertTrue(DataKey.class.isInstance(test)); GenerateDataKeyRequest actualRequest = gr.getValue(); assertEquals(keyIdentifier, actualRequest.getKeyId()); assertEquals(GRANT_TOKENS, actualRequest.getGrantTokens()); assertEquals(ENCRYPTION_CONTEXT, actualRequest.getEncryptionContext()); assertEquals( ALGORITHM_SUITE.getDataKeyLength(), actualRequest.getNumberOfBytes().longValue()); assertTrue( actualRequest .getRequestClientOptions() .getClientMarker(RequestClientOptions.Marker.USER_AGENT) .contains(VersionInfo.loadUserAgent())); assertNotNull(test.getKey()); // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.10 // = type=test // # The response's "Plaintext" MUST be the plaintext in // # the output. assertEquals(ALGORITHM_SUITE.getDataKeyLength(), test.getKey().getEncoded().length); assertEquals(ALGORITHM_SUITE.getDataKeyAlgo(), test.getKey().getAlgorithm()); assertNotNull(test.getEncryptedDataKey()); // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.10 // = type=test // # The response's cipher text blob MUST be used as the // # returned as the ciphertext for the encrypted data key in the output. assertEquals(10, test.getEncryptedDataKey().length); } @Test // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.10 // = type=test // # If the call succeeds the AWS KMS Generate Data Key response's // # "Plaintext" MUST match the key derivation input length specified by // # the algorithm suite included in the input. public void length_must_match() { final CryptoAlgorithm ALGORITHM_SUITE = CryptoAlgorithm.ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA256; final Map<String, String> ENCRYPTION_CONTEXT = Collections.singletonMap("myKey", "myValue"); final String keyIdentifier = "arn:aws:kms:us-west-2:658956600833:key/b3537ef1-d8dc-4780-9f5a-55776cbb2f7f"; // I use more, because less _should_ trigger an underflow... but the condition should _always_ // fail final int wrongLength = ALGORITHM_SUITE.getDataKeyLength() + 1; final AWSKMS client = mock(AWSKMS.class); when(client.generateDataKey(any())) .thenReturn( new GenerateDataKeyResult() .withPlaintext(ByteBuffer.allocate(wrongLength)) .withKeyId(keyIdentifier) .withCiphertextBlob(ByteBuffer.allocate(10))); final MasterKeyProvider mkp = mock(MasterKeyProvider.class); when(mkp.getDefaultProviderId()).thenReturn("aws-kms"); AwsKmsMrkAwareMasterKey masterKey = AwsKmsMrkAwareMasterKey.getInstance(client, keyIdentifier, mkp); assertThrows( IllegalStateException.class, () -> masterKey.generateDataKey(ALGORITHM_SUITE, ENCRYPTION_CONTEXT)); } @Test public void need_an_arn() { final CryptoAlgorithm ALGORITHM_SUITE = CryptoAlgorithm.ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA256; final Map<String, String> ENCRYPTION_CONTEXT = Collections.singletonMap("myKey", "myValue"); final String keyIdentifier = "arn:aws:kms:us-west-2:658956600833:key/b3537ef1-d8dc-4780-9f5a-55776cbb2f7f"; final AWSKMS client = mock(AWSKMS.class); when(client.generateDataKey(any())) .thenReturn( new GenerateDataKeyResult() .withPlaintext(ByteBuffer.allocate(ALGORITHM_SUITE.getDataKeyLength())) // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.10 // = type=test // # The response's "KeyId" // # MUST be valid. .withKeyId("b3537ef1-d8dc-4780-9f5a-55776cbb2f7f") .withCiphertextBlob(ByteBuffer.allocate(10))); final MasterKeyProvider mkp = mock(MasterKeyProvider.class); when(mkp.getDefaultProviderId()).thenReturn("aws-kms"); AwsKmsMrkAwareMasterKey masterKey = AwsKmsMrkAwareMasterKey.getInstance(client, keyIdentifier, mkp); assertThrows( IllegalStateException.class, () -> masterKey.generateDataKey(ALGORITHM_SUITE, ENCRYPTION_CONTEXT)); } } public static class encryptDataKey { @Test public void basic_use() { final CryptoAlgorithm ALGORITHM_SUITE = CryptoAlgorithm.ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA256; final List<String> GRANT_TOKENS = Collections.singletonList("testGrantToken"); final Map<String, String> ENCRYPTION_CONTEXT = Collections.singletonMap("myKey", "myValue"); final String keyIdentifier = "arn:aws:kms:us-west-2:658956600833:key/b3537ef1-d8dc-4780-9f5a-55776cbb2f7f"; final SecretKey SECRET_KEY = new SecretKeySpec( generate(ALGORITHM_SUITE.getDataKeyLength()), ALGORITHM_SUITE.getDataKeyAlgo()); final MasterKeyProvider<AwsKmsMrkAwareMasterKey> mkp = mock(MasterKeyProvider.class); when(mkp.getDefaultProviderId()).thenReturn("aws-kms"); final DataKey dataKey = new DataKey( SECRET_KEY, new byte[0], "aws-kms".getBytes(StandardCharsets.UTF_8), mock(MasterKey.class)); final AWSKMS client = mock(AWSKMS.class); when(client.encrypt(any())) .thenReturn( new EncryptResult() .withKeyId(keyIdentifier) .withCiphertextBlob(ByteBuffer.allocate(10))); AwsKmsMrkAwareMasterKey masterKey = AwsKmsMrkAwareMasterKey.getInstance(client, keyIdentifier, mkp); masterKey.setGrantTokens(GRANT_TOKENS); // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.11 // = type=test // # The inputs MUST be the same as the Master Key Encrypt Data Key // # (../master-key-interface.md#encrypt-data-key) interface. DataKey<AwsKmsMrkAwareMasterKey> test = masterKey.encryptDataKey(ALGORITHM_SUITE, ENCRYPTION_CONTEXT, dataKey); // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.11 // = type=test // # The output MUST be the same as the Master Key Encrypt Data Key // # (../master-key-interface.md#encrypt-data-key) interface. assertTrue(DataKey.class.isInstance(test)); // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.11 // = type=test // # The master // # key MUST use the configured AWS KMS client to make an AWS KMS Encrypt // # (https://docs.aws.amazon.com/kms/latest/APIReference/ // # API_Encrypt.html) request constructed as follows: verify(client, times(1)).encrypt(any()); ArgumentCaptor<EncryptRequest> gr = ArgumentCaptor.forClass(EncryptRequest.class); verify(client, times(1)).encrypt(gr.capture()); final EncryptRequest actualRequest = gr.getValue(); assertEquals(keyIdentifier, actualRequest.getKeyId()); assertEquals(GRANT_TOKENS, actualRequest.getGrantTokens()); assertEquals(ENCRYPTION_CONTEXT, actualRequest.getEncryptionContext()); assertTrue( actualRequest .getRequestClientOptions() .getClientMarker(RequestClientOptions.Marker.USER_AGENT) .contains(VersionInfo.loadUserAgent())); assertNotNull(test.getKey()); assertEquals(ALGORITHM_SUITE.getDataKeyLength(), test.getKey().getEncoded().length); assertEquals(ALGORITHM_SUITE.getDataKeyAlgo(), test.getKey().getAlgorithm()); assertNotNull(test.getEncryptedDataKey()); // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.11 // = type=test // # The // # response's cipher text blob MUST be used as the "ciphertext" for the // # encrypted data key. assertEquals(10, test.getEncryptedDataKey().length); } @Test public void secret_key_must_be_raw() { final CryptoAlgorithm ALGORITHM_SUITE = CryptoAlgorithm.ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA256; final List<String> GRANT_TOKENS = Collections.singletonList("testGrantToken"); final Map<String, String> ENCRYPTION_CONTEXT = Collections.singletonMap("myKey", "myValue"); final String keyIdentifier = "arn:aws:kms:us-west-2:658956600833:key/b3537ef1-d8dc-4780-9f5a-55776cbb2f7f"; final MasterKeyProvider<AwsKmsMrkAwareMasterKey> mkp = mock(MasterKeyProvider.class); when(mkp.getDefaultProviderId()).thenReturn("aws-kms"); // Test "stuff" here final SecretKey SECRET_KEY = mock(SecretKeySpec.class); when(SECRET_KEY.getFormat()).thenReturn("NOT-RAW"); final DataKey dataKey = new DataKey( SECRET_KEY, new byte[0], "aws-kms".getBytes(StandardCharsets.UTF_8), mock(MasterKey.class)); final AWSKMS client = mock(AWSKMS.class); when(client.encrypt(any())) .thenReturn( new EncryptResult() .withKeyId(keyIdentifier) .withCiphertextBlob(ByteBuffer.allocate(10))); AwsKmsMrkAwareMasterKey masterKey = AwsKmsMrkAwareMasterKey.getInstance(client, keyIdentifier, mkp); masterKey.setGrantTokens(GRANT_TOKENS); assertThrows( "Only RAW encoded keys are supported", IllegalArgumentException.class, () -> masterKey.encryptDataKey(ALGORITHM_SUITE, ENCRYPTION_CONTEXT, dataKey)); } @Test public void need_an_arn() { final CryptoAlgorithm ALGORITHM_SUITE = CryptoAlgorithm.ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA256; final List<String> GRANT_TOKENS = Collections.singletonList("testGrantToken"); final Map<String, String> ENCRYPTION_CONTEXT = Collections.singletonMap("myKey", "myValue"); final String keyIdentifier = "arn:aws:kms:us-west-2:658956600833:key/b3537ef1-d8dc-4780-9f5a-55776cbb2f7f"; final SecretKey SECRET_KEY = new SecretKeySpec( generate(ALGORITHM_SUITE.getDataKeyLength()), ALGORITHM_SUITE.getDataKeyAlgo()); final MasterKeyProvider<AwsKmsMrkAwareMasterKey> mkp = mock(MasterKeyProvider.class); when(mkp.getDefaultProviderId()).thenReturn("aws-kms"); final DataKey dataKey = new DataKey( SECRET_KEY, new byte[0], "aws-kms".getBytes(StandardCharsets.UTF_8), mock(MasterKey.class)); final AWSKMS client = mock(AWSKMS.class); when(client.encrypt(any())) .thenReturn( new EncryptResult() // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.11 // = type=test // # The AWS KMS Encrypt response MUST contain a valid "KeyId". .withKeyId("b3537ef1-d8dc-4780-9f5a-55776cbb2f7f") .withCiphertextBlob(ByteBuffer.allocate(10))); AwsKmsMrkAwareMasterKey masterKey = AwsKmsMrkAwareMasterKey.getInstance(client, keyIdentifier, mkp); masterKey.setGrantTokens(GRANT_TOKENS); assertThrows( IllegalStateException.class, () -> masterKey.encryptDataKey(ALGORITHM_SUITE, ENCRYPTION_CONTEXT, dataKey)); } } public static class filterEncryptedDataKeys { @Test public void basic_use() { final String keyIdentifier = "arn:aws:kms:us-west-2:658956600833:key/b3537ef1-d8dc-4780-9f5a-55776cbb2f7f"; final String providerId = "aws-kms"; final EncryptedDataKey edk = new KeyBlob(providerId, keyIdentifier.getBytes(StandardCharsets.UTF_8), new byte[10]); assertTrue(AwsKmsMrkAwareMasterKey.filterEncryptedDataKeys(providerId, keyIdentifier, edk)); } @Test public void mrk_specific() { /* This may be overkill, * but the whole point * of multi-region optimization * is this fuzzy match. */ final String configuredIdentifier = "arn:aws:kms:us-west-2:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574"; final String ekdIdentifier = "arn:aws:kms:us-east-2:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574"; final String providerId = "aws-kms"; final EncryptedDataKey edk = new KeyBlob(providerId, ekdIdentifier.getBytes(StandardCharsets.UTF_8), new byte[10]); assertTrue( AwsKmsMrkAwareMasterKey.filterEncryptedDataKeys(providerId, configuredIdentifier, edk)); } @Test public void provider_info_must_be_arn() { final String configuredIdentifier = "arn:aws:kms:us-west-2:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574"; final String rawKeyId = "mrk-edb7fe6942894d32ac46dbb1c922d574"; final String alias = "arn:aws:kms:us-west-2:111122223333:alias/mrk-edb7fe6942894d32ac46dbb1c922d574"; final String providerId = "aws-kms"; final EncryptedDataKey edkNotArn = new KeyBlob(providerId, rawKeyId.getBytes(StandardCharsets.UTF_8), new byte[10]); final EncryptedDataKey edkAliasArn = new KeyBlob(providerId, rawKeyId.getBytes(StandardCharsets.UTF_8), new byte[10]); // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.9 // = type=test // # Additionally each provider info MUST be a valid AWS KMS ARN // # (aws-kms-key-arn.md#a-valid-aws-kms-arn) with a resource type of // # "key". assertThrows( IllegalStateException.class, () -> AwsKmsMrkAwareMasterKey.filterEncryptedDataKeys( providerId, configuredIdentifier, edkNotArn)); assertThrows( IllegalStateException.class, () -> AwsKmsMrkAwareMasterKey.filterEncryptedDataKeys( providerId, configuredIdentifier, edkAliasArn)); } @Test // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.9 // = type=test // # To match the encrypted data key's // # provider ID MUST exactly match the value "aws-kms" and the the // # function AWS KMS MRK Match for Decrypt (aws-kms-mrk-match-for- // # decrypt.md#implementation) called with the configured AWS KMS key // # identifier and the encrypted data key's provider info MUST return // # "true". public void may_not_match() { final String keyIdentifier = "arn:aws:kms:us-west-2:658956600833:key/b3537ef1-d8dc-4780-9f5a-55776cbb2f7f"; final String providerId = "aws-kms"; final EncryptedDataKey edk = new KeyBlob(providerId, keyIdentifier.getBytes(StandardCharsets.UTF_8), new byte[10]); assertFalse( AwsKmsMrkAwareMasterKey.filterEncryptedDataKeys("not-aws-kms", keyIdentifier, edk)); assertFalse( AwsKmsMrkAwareMasterKey.filterEncryptedDataKeys( providerId, "arn:aws:kms:us-west-2:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574", edk)); } } public static class decryptSingleEncryptedDataKey { @Test public void basic_use() { final CryptoAlgorithm ALGORITHM_SUITE = CryptoAlgorithm.ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA256; final List<String> GRANT_TOKENS = Collections.singletonList("testGrantToken"); final Map<String, String> ENCRYPTION_CONTEXT = Collections.singletonMap("myKey", "myValue"); final String keyIdentifier = "arn:aws:kms:us-west-2:658956600833:key/b3537ef1-d8dc-4780-9f5a-55776cbb2f7f"; final String providerId = "aws-kms"; final EncryptedDataKey edk = new KeyBlob(providerId, keyIdentifier.getBytes(StandardCharsets.UTF_8), new byte[10]); final MasterKeyProvider mkp = mock(MasterKeyProvider.class); when(mkp.getDefaultProviderId()).thenReturn(providerId); final AWSKMS client = mock(AWSKMS.class); when(client.decrypt(any())) .thenReturn( new DecryptResult() .withKeyId(keyIdentifier) .withPlaintext(ByteBuffer.allocate(ALGORITHM_SUITE.getDataKeyLength()))); AwsKmsMrkAwareMasterKey masterKey = AwsKmsMrkAwareMasterKey.getInstance(client, keyIdentifier, mkp); masterKey.setGrantTokens(GRANT_TOKENS); DataKey<AwsKmsMrkAwareMasterKey> test = AwsKmsMrkAwareMasterKey.decryptSingleEncryptedDataKey( any(), client, keyIdentifier, GRANT_TOKENS, ALGORITHM_SUITE, edk, ENCRYPTION_CONTEXT); verify(client, times(1)).decrypt(any()); ArgumentCaptor<DecryptRequest> gr = ArgumentCaptor.forClass(DecryptRequest.class); verify(client, times(1)).decrypt(gr.capture()); final DecryptRequest actualRequest = gr.getValue(); // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.9 // = type=test // # To decrypt the encrypted data key this master key MUST use the // # configured AWS KMS client to make an AWS KMS Decrypt // # (https://docs.aws.amazon.com/kms/latest/APIReference/ // # API_Decrypt.html) request constructed as follows: assertEquals(keyIdentifier, actualRequest.getKeyId()); assertEquals(GRANT_TOKENS, actualRequest.getGrantTokens()); assertEquals(ENCRYPTION_CONTEXT, actualRequest.getEncryptionContext()); assertTrue( actualRequest .getRequestClientOptions() .getClientMarker(RequestClientOptions.Marker.USER_AGENT) .contains(VersionInfo.loadUserAgent())); assertNotNull(test.getKey()); assertEquals(ALGORITHM_SUITE.getDataKeyLength(), test.getKey().getEncoded().length); assertEquals(ALGORITHM_SUITE.getDataKeyAlgo(), test.getKey().getAlgorithm()); } @Test public void expect_key_arn() { final CryptoAlgorithm ALGORITHM_SUITE = CryptoAlgorithm.ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA256; final List<String> GRANT_TOKENS = Collections.singletonList("testGrantToken"); final Map<String, String> ENCRYPTION_CONTEXT = Collections.singletonMap("myKey", "myValue"); final String keyIdentifier = "arn:aws:kms:us-west-2:658956600833:key/b3537ef1-d8dc-4780-9f5a-55776cbb2f7f"; final String providerId = "aws-kms"; final EncryptedDataKey edk = new KeyBlob(providerId, keyIdentifier.getBytes(StandardCharsets.UTF_8), new byte[10]); final MasterKeyProvider mkp = mock(MasterKeyProvider.class); when(mkp.getDefaultProviderId()).thenReturn(providerId); final AWSKMS client = mock(AWSKMS.class); when(client.decrypt(any())) .thenReturn( new DecryptResult() .withKeyId(null) .withPlaintext(ByteBuffer.allocate(ALGORITHM_SUITE.getDataKeyLength()))); AwsKmsMrkAwareMasterKey masterKey = AwsKmsMrkAwareMasterKey.getInstance(client, keyIdentifier, mkp); masterKey.setGrantTokens(GRANT_TOKENS); assertThrows( IllegalStateException.class, () -> AwsKmsMrkAwareMasterKey.decryptSingleEncryptedDataKey( any(), client, keyIdentifier, GRANT_TOKENS, ALGORITHM_SUITE, edk, ENCRYPTION_CONTEXT)); } @Test // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.9 // = type=test // # If the call succeeds then the response's "KeyId" MUST be equal to the // # configured AWS KMS key identifier otherwise the function MUST collect // # an error. public void returned_arn_must_match() { final CryptoAlgorithm ALGORITHM_SUITE = CryptoAlgorithm.ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA256; final List<String> GRANT_TOKENS = Collections.singletonList("testGrantToken"); final Map<String, String> ENCRYPTION_CONTEXT = Collections.singletonMap("myKey", "myValue"); final String keyIdentifier = "arn:aws:kms:us-west-2:658956600833:key/b3537ef1-d8dc-4780-9f5a-55776cbb2f7f"; final String providerId = "aws-kms"; final EncryptedDataKey edk = new KeyBlob(providerId, keyIdentifier.getBytes(StandardCharsets.UTF_8), new byte[10]); final MasterKeyProvider mkp = mock(MasterKeyProvider.class); when(mkp.getDefaultProviderId()).thenReturn(providerId); final AWSKMS client = mock(AWSKMS.class); when(client.decrypt(any())) .thenReturn( new DecryptResult() .withKeyId("arn:aws:kms:us-west-2:658956600833:key/something-else") .withPlaintext(ByteBuffer.allocate(ALGORITHM_SUITE.getDataKeyLength()))); AwsKmsMrkAwareMasterKey masterKey = AwsKmsMrkAwareMasterKey.getInstance(client, keyIdentifier, mkp); masterKey.setGrantTokens(GRANT_TOKENS); assertThrows( IllegalStateException.class, () -> AwsKmsMrkAwareMasterKey.decryptSingleEncryptedDataKey( any(), client, keyIdentifier, GRANT_TOKENS, ALGORITHM_SUITE, edk, ENCRYPTION_CONTEXT)); } @Test // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.9 // = type=test // # The response's "Plaintext"'s length MUST equal the length // # required by the requested algorithm suite otherwise the function MUST // # collect an error. public void key_length_must_match() { final CryptoAlgorithm ALGORITHM_SUITE = CryptoAlgorithm.ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA256; final List<String> GRANT_TOKENS = Collections.singletonList("testGrantToken"); final Map<String, String> ENCRYPTION_CONTEXT = Collections.singletonMap("myKey", "myValue"); final String keyIdentifier = "arn:aws:kms:us-west-2:658956600833:key/b3537ef1-d8dc-4780-9f5a-55776cbb2f7f"; final String providerId = "aws-kms"; // I use more, because less _should_ trigger an underflow... but the condition should _always_ // fail final int wrongLength = ALGORITHM_SUITE.getDataKeyLength() + 1; final EncryptedDataKey edk = new KeyBlob(providerId, keyIdentifier.getBytes(StandardCharsets.UTF_8), new byte[10]); final MasterKeyProvider mkp = mock(MasterKeyProvider.class); when(mkp.getDefaultProviderId()).thenReturn(providerId); final AWSKMS client = mock(AWSKMS.class); when(client.decrypt(any())) .thenReturn( new DecryptResult() .withKeyId(keyIdentifier) .withPlaintext(ByteBuffer.allocate(wrongLength))); AwsKmsMrkAwareMasterKey masterKey = AwsKmsMrkAwareMasterKey.getInstance(client, keyIdentifier, mkp); masterKey.setGrantTokens(GRANT_TOKENS); assertThrows( IllegalStateException.class, () -> AwsKmsMrkAwareMasterKey.decryptSingleEncryptedDataKey( any(), client, keyIdentifier, GRANT_TOKENS, ALGORITHM_SUITE, edk, ENCRYPTION_CONTEXT)); } } public static class decryptDataKey { @Test public void basic_use() { final String keyIdentifier = "arn:aws:kms:us-west-2:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574"; final CryptoAlgorithm ALGORITHM_SUITE = CryptoAlgorithm.ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA256; final List<String> GRANT_TOKENS = Collections.singletonList("testGrantToken"); final Map<String, String> ENCRYPTION_CONTEXT = Collections.singletonMap("myKey", "myValue"); final byte[] cipherText = new byte[10]; final String providerId = "aws-kms"; final MasterKeyProvider mkp = mock(MasterKeyProvider.class); when(mkp.getDefaultProviderId()).thenReturn(providerId); final EncryptedDataKey edk1 = new KeyBlob("aws-kms", keyIdentifier.getBytes(StandardCharsets.UTF_8), cipherText); final EncryptedDataKey edk2 = new KeyBlob("aws-kms", keyIdentifier.getBytes(StandardCharsets.UTF_8), cipherText); final AWSKMS client = mock(AWSKMS.class); when(client.decrypt(any())) .thenReturn( new DecryptResult() .withKeyId(keyIdentifier) .withPlaintext(ByteBuffer.allocate(ALGORITHM_SUITE.getDataKeyLength()))); final AwsKmsMrkAwareMasterKey mk = AwsKmsMrkAwareMasterKey.getInstance(client, keyIdentifier, mkp); mk.setGrantTokens(GRANT_TOKENS); // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.9 // = type=test // # The inputs MUST be the same as the Master Key Decrypt Data Key // # (../master-key-interface.md#decrypt-data-key) interface. final DataKey<AwsKmsMrkAwareMasterKey> test = mk.decryptDataKey(ALGORITHM_SUITE, Arrays.asList(edk1, edk2), ENCRYPTION_CONTEXT); // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.9 // = type=test // # For each encrypted data key in the filtered set, one at a time, the // # master key MUST attempt to decrypt the data key. // // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.9 // = type=test // # If the AWS KMS response satisfies the requirements then it MUST be // # use and this function MUST return and not attempt to decrypt any more // # encrypted data keys. verify(client, times((1))) .decrypt( new DecryptRequest() .withGrantTokens(GRANT_TOKENS) .withEncryptionContext(ENCRYPTION_CONTEXT) .withKeyId(keyIdentifier) .withCiphertextBlob(ByteBuffer.wrap(cipherText))); // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.9 // = type=test // # The output MUST be the same as the Master Key Decrypt Data Key // # (../master-key-interface.md#decrypt-data-key) interface. assertTrue(DataKey.class.isInstance(test)); } @Test // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.9 // = type=test // # The set of encrypted data keys MUST first be filtered to match this // # master key's configuration. public void edk_match() { final CryptoAlgorithm ALGORITHM_SUITE = CryptoAlgorithm.ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA256; final List<String> GRANT_TOKENS = Collections.singletonList("testGrantToken"); final Map<String, String> ENCRYPTION_CONTEXT = Collections.singletonMap("myKey", "myValue"); final String keyIdentifier = "arn:aws:kms:us-west-2:658956600833:key/b3537ef1-d8dc-4780-9f5a-55776cbb2f7f"; final String providerId = "aws-kms"; final String clientErrMsg = "asdf"; final EncryptedDataKey edk1 = new KeyBlob("not-aws-kms", keyIdentifier.getBytes(StandardCharsets.UTF_8), new byte[10]); final EncryptedDataKey edk2 = new KeyBlob( providerId, "not-key-identifier".getBytes(StandardCharsets.UTF_8), new byte[10]); final MasterKeyProvider mkp = mock(MasterKeyProvider.class); when(mkp.getDefaultProviderId()).thenReturn(providerId); final AWSKMS client = mock(AWSKMS.class); when(client.decrypt(any())).thenThrow(new AmazonServiceException(clientErrMsg)); final KmsMasterKeyProvider.RegionalClientSupplier supplier = mock(KmsMasterKeyProvider.RegionalClientSupplier.class); when(supplier.getClient(any())).thenReturn(client); final AwsKmsMrkAwareMasterKey masterKey = AwsKmsMrkAwareMasterKey.getInstance(client, keyIdentifier, mkp); masterKey.setGrantTokens(GRANT_TOKENS); final CannotUnwrapDataKeyException testProviderNotMatch = assertThrows( "Unable to decrypt any data keys", CannotUnwrapDataKeyException.class, () -> masterKey.decryptDataKey( ALGORITHM_SUITE, Arrays.asList(edk1), ENCRYPTION_CONTEXT)); assertEquals(0, testProviderNotMatch.getSuppressed().length); final IllegalStateException testArnNotMatch = assertThrows( "Unable to decrypt any data keys", IllegalStateException.class, () -> masterKey.decryptDataKey( ALGORITHM_SUITE, Arrays.asList(edk2), ENCRYPTION_CONTEXT)); assertEquals(0, testArnNotMatch.getSuppressed().length); } @Test // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.9 // = type=test // # If this attempt // # results in an error, then these errors MUST be collected. // // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.9 // = type=test // # If all the input encrypted data keys have been processed then this // # function MUST yield an error that includes all the collected errors. public void exception_wrapped() { final CryptoAlgorithm ALGORITHM_SUITE = CryptoAlgorithm.ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA256; final List<String> GRANT_TOKENS = Collections.singletonList("testGrantToken"); final Map<String, String> ENCRYPTION_CONTEXT = Collections.singletonMap("myKey", "myValue"); final String keyIdentifier = "arn:aws:kms:us-west-2:658956600833:key/b3537ef1-d8dc-4780-9f5a-55776cbb2f7f"; final String providerId = "aws-kms"; final String clientErrMsg = "asdf"; final EncryptedDataKey edk = new KeyBlob(providerId, keyIdentifier.getBytes(StandardCharsets.UTF_8), new byte[10]); final MasterKeyProvider mkp = mock(MasterKeyProvider.class); when(mkp.getDefaultProviderId()).thenReturn(providerId); final AWSKMS client = mock(AWSKMS.class); when(client.decrypt(any())).thenThrow(new AmazonServiceException(clientErrMsg)); KmsMasterKeyProvider.RegionalClientSupplier supplier = mock(KmsMasterKeyProvider.RegionalClientSupplier.class); when(supplier.getClient(any())).thenReturn(client); AwsKmsMrkAwareMasterKey masterKey = AwsKmsMrkAwareMasterKey.getInstance(client, keyIdentifier, mkp); masterKey.setGrantTokens(GRANT_TOKENS); final CannotUnwrapDataKeyException test = assertThrows( "Unable to decrypt any data keys", CannotUnwrapDataKeyException.class, () -> masterKey.decryptDataKey( ALGORITHM_SUITE, Arrays.asList(edk), ENCRYPTION_CONTEXT)); assertEquals(1, test.getSuppressed().length); Throwable fromClient = Arrays.stream(test.getSuppressed()).findFirst().get(); assertTrue(fromClient instanceof AmazonServiceException); assertTrue(fromClient.getMessage().startsWith(clientErrMsg)); } } public static class getMasterKey { @Test // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.7 // = type=test // # MUST be unchanged from the Master Key interface. public void test_get_master_key() throws NoSuchMethodException { String methodName = "getMasterKey"; Class<?>[] parameterTypes = new Class<?>[] {String.class, String.class}; // Make sure the signature is correct by fetching the base method Method baseMethod = MasterKey.class.getDeclaredMethod(methodName, parameterTypes); assertNotNull(baseMethod); // Assert AwsKmsMrkAwareMasterKey does not declare the same method directly assertThrows( NoSuchMethodException.class, () -> AwsKmsMrkAwareMasterKey.class.getDeclaredMethod(methodName, parameterTypes)); } } public static class getMasterKeysForEncryption { @Test // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.8 // = type=test // # MUST be unchanged from the Master Key interface. public void test_getMasterKeysForEncryption() throws NoSuchMethodException { String methodName = "getMasterKeysForEncryption"; Class<?>[] parameterTypes = new Class<?>[] {MasterKeyRequest.class}; // Make sure the signature is correct by fetching the base method Method baseMethod = MasterKey.class.getDeclaredMethod(methodName, parameterTypes); assertNotNull(baseMethod); // Assert AwsKmsMrkAwareMasterKey does no declare the same method directly assertThrows( NoSuchMethodException.class, () -> AwsKmsMrkAwareMasterKey.class.getDeclaredMethod(methodName, parameterTypes)); } } }
725
0
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk/kms/XCompatKmsDecryptTest.java
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package com.amazonaws.encryptionsdk.kms; import static org.junit.Assert.assertArrayEquals; import com.amazonaws.encryptionsdk.AwsCrypto; import com.amazonaws.encryptionsdk.CryptoResult; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import java.io.File; import java.nio.file.Files; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Map; import org.apache.commons.lang3.StringUtils; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; @RunWith(Parameterized.class) public class XCompatKmsDecryptTest { private String plaintextFileName; private String ciphertextFileName; private String kmsKeyId; public XCompatKmsDecryptTest( String plaintextFileName, String ciphertextFileName, String kmsKeyId) { this.plaintextFileName = plaintextFileName; this.ciphertextFileName = ciphertextFileName; this.kmsKeyId = kmsKeyId; } @Parameters(name = "{index}: testDecryptFromFile({0}, {1}, {2})") public static Collection<Object[]> data() throws Exception { String baseDirName; baseDirName = System.getProperty("staticCompatibilityResourcesDir"); if (baseDirName == null) { baseDirName = XCompatKmsDecryptTest.class.getProtectionDomain().getCodeSource().getLocation().getPath() + "aws_encryption_sdk_resources"; } List<Object[]> testCases_ = new ArrayList<Object[]>(); String ciphertextManifestName = StringUtils.join( new String[] {baseDirName, "manifests", "ciphertext.manifest"}, File.separator); File ciphertextManifestFile = new File(ciphertextManifestName); if (!ciphertextManifestFile.exists()) { return Collections.emptyList(); } ObjectMapper ciphertextManifestMapper = new ObjectMapper(); Map<String, Object> ciphertextManifest = ciphertextManifestMapper.readValue( ciphertextManifestFile, new TypeReference<Map<String, Object>>() {}); List<Map<String, Object>> testCases = (List<Map<String, Object>>) ciphertextManifest.get("test_cases"); for (Map<String, Object> testCase : testCases) { Map<String, String> plaintext = (Map<String, String>) testCase.get("plaintext"); Map<String, String> ciphertext = (Map<String, String>) testCase.get("ciphertext"); List<Map<String, Object>> masterKeys = (List<Map<String, Object>>) testCase.get("master_keys"); for (Map<String, Object> masterKey : masterKeys) { String providerId = (String) masterKey.get("provider_id"); if (providerId.equals("aws-kms") && (boolean) masterKey.get("decryptable")) { testCases_.add( new Object[] { baseDirName + File.separator + plaintext.get("filename"), baseDirName + File.separator + ciphertext.get("filename"), (String) masterKey.get("key_id") }); break; } } } return testCases_; } @Test public void testDecryptFromFile() throws Exception { AwsCrypto crypto = AwsCrypto.standard(); final KmsMasterKeyProvider masterKeyProvider = KmsMasterKeyProvider.builder().buildStrict(kmsKeyId); byte ciphertextBytes[] = Files.readAllBytes(Paths.get(ciphertextFileName)); byte plaintextBytes[] = Files.readAllBytes(Paths.get(plaintextFileName)); final CryptoResult decryptResult = crypto.decryptData(masterKeyProvider, ciphertextBytes); assertArrayEquals(plaintextBytes, (byte[]) decryptResult.getResult()); } }
726
0
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk/kms/KMSProviderBuilderIntegrationTests.java
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package com.amazonaws.encryptionsdk.kms; import static com.amazonaws.encryptionsdk.TestUtils.assertThrows; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.atLeastOnce; import static org.mockito.Mockito.never; import static org.mockito.Mockito.reset; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import com.amazonaws.AbortedException; import com.amazonaws.ClientConfiguration; import com.amazonaws.Request; import com.amazonaws.auth.AWSCredentials; import com.amazonaws.auth.AWSCredentialsProvider; import com.amazonaws.auth.DefaultAWSCredentialsProviderChain; import com.amazonaws.client.builder.AwsClientBuilder; import com.amazonaws.encryptionsdk.AwsCrypto; import com.amazonaws.encryptionsdk.CryptoAlgorithm; import com.amazonaws.encryptionsdk.CryptoResult; import com.amazonaws.encryptionsdk.EncryptedDataKey; import com.amazonaws.encryptionsdk.MasterKeyProvider; import com.amazonaws.encryptionsdk.exception.AwsCryptoException; import com.amazonaws.encryptionsdk.exception.CannotUnwrapDataKeyException; import com.amazonaws.encryptionsdk.internal.VersionInfo; import com.amazonaws.encryptionsdk.kms.KmsMasterKeyProvider.RegionalClientSupplier; import com.amazonaws.encryptionsdk.model.KeyBlob; import com.amazonaws.handlers.RequestHandler2; import com.amazonaws.http.exception.HttpRequestTimeoutException; import com.amazonaws.services.kms.AWSKMS; import com.amazonaws.services.kms.AWSKMSClientBuilder; import java.nio.charset.StandardCharsets; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicReference; import org.junit.Before; import org.junit.Test; import org.mockito.ArgumentCaptor; public class KMSProviderBuilderIntegrationTests { private static final String AWS_KMS_PROVIDER_ID = "aws-kms"; private AWSKMS testUSWestClient__; private AWSKMS testEUCentralClient__; private RegionalClientSupplier testClientSupplier__; @Before public void setup() { testUSWestClient__ = spy(AWSKMSClientBuilder.standard().withRegion("us-west-2").build()); testEUCentralClient__ = spy(AWSKMSClientBuilder.standard().withRegion("eu-central-1").build()); testClientSupplier__ = regionName -> { if (regionName.equals("us-west-2")) { return testUSWestClient__; } else if (regionName.equals("eu-central-1")) { return testEUCentralClient__; } else { throw new AwsCryptoException( "test supplier only configured for us-west-2 and eu-central-1"); } }; } @Test public void whenBogusRegionsDecrypted_doesNotLeakClients() throws Exception { AtomicReference<ConcurrentHashMap<String, AWSKMS>> kmsCache = new AtomicReference<>(); KmsMasterKeyProvider mkp = (new KmsMasterKeyProvider.Builder() { @Override protected void snoopClientCache(final ConcurrentHashMap<String, AWSKMS> map) { kmsCache.set(map); } }) .buildDiscovery(); try { mkp.decryptDataKey( CryptoAlgorithm.ALG_AES_128_GCM_IV12_TAG16_HKDF_SHA256, Collections.singleton( new KeyBlob( "aws-kms", "arn:aws:kms:us-bogus-1:123456789010:key/b3537ef1-d8dc-4780-9f5a-55776cbb2f7f" .getBytes(StandardCharsets.UTF_8), new byte[40])), new HashMap<>()); fail("Expected CannotUnwrapDataKeyException"); } catch (CannotUnwrapDataKeyException e) { // ok } assertTrue(kmsCache.get().isEmpty()); } @Test public void whenOperationSuccessful_clientIsCached() { AtomicReference<ConcurrentHashMap<String, AWSKMS>> kmsCache = new AtomicReference<>(); KmsMasterKeyProvider mkp = (new KmsMasterKeyProvider.Builder() { @Override protected void snoopClientCache(final ConcurrentHashMap<String, AWSKMS> map) { kmsCache.set(map); } }) .buildStrict(KMSTestFixtures.TEST_KEY_IDS[0]); AwsCrypto.standard().encryptData(mkp, new byte[1]); AWSKMS kms = kmsCache.get().get("us-west-2"); assertNotNull(kms); AwsCrypto.standard().encryptData(mkp, new byte[1]); // Cache entry should stay the same assertEquals(kms, kmsCache.get().get("us-west-2")); } @Test public void whenConstructedWithoutArguments_canUseMultipleRegions() throws Exception { KmsMasterKeyProvider mkp = KmsMasterKeyProvider.builder().buildDiscovery(); for (String key : KMSTestFixtures.TEST_KEY_IDS) { byte[] ciphertext = AwsCrypto.standard() .encryptData(KmsMasterKeyProvider.builder().buildStrict(key), new byte[1]) .getResult(); AwsCrypto.standard().decryptData(mkp, ciphertext); } } @Test public void whenConstructedInStrictMode_encryptDecrypt() throws Exception { KmsMasterKeyProvider mkp = KmsMasterKeyProvider.builder() .withCustomClientFactory(testClientSupplier__) .buildStrict(KMSTestFixtures.TEST_KEY_IDS[0]); byte[] ciphertext = AwsCrypto.standard().encryptData(mkp, new byte[1]).getResult(); verify(testUSWestClient__, times(1)).generateDataKey(any()); AwsCrypto.standard().decryptData(mkp, ciphertext); verify(testUSWestClient__, times(1)).decrypt(any()); } @Test public void whenConstructedInStrictMode_encryptDecryptMultipleCmks() throws Exception { KmsMasterKeyProvider mkp = KmsMasterKeyProvider.builder() .withCustomClientFactory(testClientSupplier__) .buildStrict(KMSTestFixtures.US_WEST_2_KEY_ID, KMSTestFixtures.EU_CENTRAL_1_KEY_ID); byte[] ciphertext = AwsCrypto.standard().encryptData(mkp, new byte[1]).getResult(); verify(testUSWestClient__, times(1)).generateDataKey(any()); verify(testEUCentralClient__, times(1)).encrypt(any()); AwsCrypto.standard().decryptData(mkp, ciphertext); verify(testUSWestClient__, times(1)).decrypt(any()); } @Test public void whenConstructedInStrictMode_encryptSingleBadKeyIdFails() throws Exception { KmsMasterKeyProvider mkp = KmsMasterKeyProvider.builder() .withCustomClientFactory(testClientSupplier__) .withDefaultRegion("us-west-2") .buildStrict(KMSTestFixtures.US_WEST_2_KEY_ID, "badKeyId"); assertThrows( AwsCryptoException.class, () -> AwsCrypto.standard().encryptData(mkp, new byte[1]).getResult()); verify(testUSWestClient__, times(1)).generateDataKey(any()); verify(testUSWestClient__, times(1)).encrypt(any()); } @Test public void whenConstructedInStrictMode_decryptBadEDKFails() throws Exception { KmsMasterKeyProvider mkp = KmsMasterKeyProvider.builder() .withCustomClientFactory(testClientSupplier__) .withDefaultRegion("us-west-2") .buildStrict("badKeyId"); final CryptoAlgorithm algSuite = CryptoAlgorithm.ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA256; final Map<String, String> encCtx = Collections.singletonMap("myKey", "myValue"); final EncryptedDataKey badEDK = new KeyBlob( AWS_KMS_PROVIDER_ID, "badKeyId".getBytes(StandardCharsets.UTF_8), new byte[algSuite.getDataKeyLength()]); assertThrows( CannotUnwrapDataKeyException.class, () -> mkp.decryptDataKey(algSuite, Collections.singletonList(badEDK), encCtx)); verify(testUSWestClient__, times(1)).decrypt(any()); } @Test public void whenConstructedInDiscoveryMode_decrypt() throws Exception { KmsMasterKeyProvider singleCmkMkp = KmsMasterKeyProvider.builder() .withCustomClientFactory(testClientSupplier__) .buildStrict(KMSTestFixtures.TEST_KEY_IDS[0]); byte[] singleCmkCiphertext = AwsCrypto.standard().encryptData(singleCmkMkp, new byte[1]).getResult(); KmsMasterKeyProvider mkpToTest = KmsMasterKeyProvider.builder() .withCustomClientFactory(testClientSupplier__) .buildDiscovery(); AwsCrypto.standard().decryptData(mkpToTest, singleCmkCiphertext); verify(testUSWestClient__, times(1)).decrypt(any()); } @Test public void whenConstructedInDiscoveryMode_decryptBadEDKFails() throws Exception { KmsMasterKeyProvider mkp = KmsMasterKeyProvider.builder() .withCustomClientFactory(testClientSupplier__) .withDefaultRegion("us-west-2") .buildDiscovery(); final CryptoAlgorithm algSuite = CryptoAlgorithm.ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA256; final Map<String, String> encCtx = Collections.singletonMap("myKey", "myValue"); final EncryptedDataKey badEDK = new KeyBlob( AWS_KMS_PROVIDER_ID, "badKeyId".getBytes(StandardCharsets.UTF_8), new byte[algSuite.getDataKeyLength()]); assertThrows( CannotUnwrapDataKeyException.class, () -> mkp.decryptDataKey(algSuite, Collections.singletonList(badEDK), encCtx)); verify(testUSWestClient__, times(1)).decrypt(any()); } @Test public void whenConstructedWithDiscoveryFilter_decrypt() throws Exception { KmsMasterKeyProvider singleCmkMkp = KmsMasterKeyProvider.builder() .withCustomClientFactory(testClientSupplier__) .buildStrict(KMSTestFixtures.TEST_KEY_IDS[0]); byte[] singleCmkCiphertext = AwsCrypto.standard().encryptData(singleCmkMkp, new byte[1]).getResult(); KmsMasterKeyProvider mkpToTest = KmsMasterKeyProvider.builder() .withCustomClientFactory(testClientSupplier__) .buildDiscovery( new DiscoveryFilter( KMSTestFixtures.PARTITION, Arrays.asList(KMSTestFixtures.ACCOUNT_ID))); AwsCrypto.standard().decryptData(mkpToTest, singleCmkCiphertext); verify(testUSWestClient__, times(1)).decrypt(any()); } @Test public void whenConstructedWithDiscoveryFilter_decryptBadEDKFails() throws Exception { KmsMasterKeyProvider mkp = KmsMasterKeyProvider.builder() .withCustomClientFactory(testClientSupplier__) .withDefaultRegion("us-west-2") .buildDiscovery( new DiscoveryFilter( KMSTestFixtures.PARTITION, Arrays.asList(KMSTestFixtures.ACCOUNT_ID))); final CryptoAlgorithm algSuite = CryptoAlgorithm.ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA256; final Map<String, String> encCtx = Collections.singletonMap("myKey", "myValue"); final String badARN = "arn:aws:kms:us-west-2:658956600833:key/badID"; final EncryptedDataKey badEDK = new KeyBlob( AWS_KMS_PROVIDER_ID, badARN.getBytes(StandardCharsets.UTF_8), new byte[algSuite.getDataKeyLength()]); assertThrows( CannotUnwrapDataKeyException.class, () -> mkp.decryptDataKey(algSuite, Collections.singletonList(badEDK), encCtx)); verify(testUSWestClient__, times(1)).decrypt(any()); } @Test public void whenHandlerConfigured_handlerIsInvoked() throws Exception { RequestHandler2 handler = spy(new RequestHandler2() {}); KmsMasterKeyProvider mkp = KmsMasterKeyProvider.builder() .withClientBuilder(AWSKMSClientBuilder.standard().withRequestHandlers(handler)) .buildStrict(KMSTestFixtures.TEST_KEY_IDS[0]); AwsCrypto.standard().encryptData(mkp, new byte[1]); verify(handler).beforeRequest(any()); } @Test public void whenShortTimeoutSet_timesOut() throws Exception { // By setting a timeout of 1ms, it's not physically possible to complete both the us-west-2 and // eu-central-1 // requests due to speed of light limits. KmsMasterKeyProvider mkp = KmsMasterKeyProvider.builder() .withClientBuilder( AWSKMSClientBuilder.standard() .withClientConfiguration(new ClientConfiguration().withRequestTimeout(1))) .buildStrict(Arrays.asList(KMSTestFixtures.TEST_KEY_IDS)); try { AwsCrypto.standard().encryptData(mkp, new byte[1]); fail("Expected exception"); } catch (Exception e) { if (e instanceof AbortedException) { // ok - one manifestation of a timeout } else if (e.getCause() instanceof HttpRequestTimeoutException) { // ok - another kind of timeout } else { throw e; } } } @Test public void whenCustomCredentialsSet_theyAreUsed() throws Exception { AWSCredentialsProvider customProvider = spy(new DefaultAWSCredentialsProviderChain()); KmsMasterKeyProvider mkp = KmsMasterKeyProvider.builder() .withCredentials(customProvider) .buildStrict(KMSTestFixtures.TEST_KEY_IDS[0]); AwsCrypto.standard().encryptData(mkp, new byte[1]); verify(customProvider, atLeastOnce()).getCredentials(); AWSCredentials customCredentials = spy(customProvider.getCredentials()); mkp = KmsMasterKeyProvider.builder() .withCredentials(customCredentials) .buildStrict(KMSTestFixtures.TEST_KEY_IDS[0]); AwsCrypto.standard().encryptData(mkp, new byte[1]); verify(customCredentials, atLeastOnce()).getAWSSecretKey(); } @Test public void whenBuilderCloned_configurationIsRetained() throws Exception { AWSCredentialsProvider customProvider1 = spy(new DefaultAWSCredentialsProviderChain()); AWSCredentialsProvider customProvider2 = spy(new DefaultAWSCredentialsProviderChain()); KmsMasterKeyProvider.Builder builder = KmsMasterKeyProvider.builder().withCredentials(customProvider1); KmsMasterKeyProvider.Builder builder2 = builder.clone(); // This will mutate the first builder to change the creds, but leave the clone unchanged. MasterKeyProvider<?> mkp2 = builder.withCredentials(customProvider2).buildStrict(KMSTestFixtures.TEST_KEY_IDS[0]); MasterKeyProvider<?> mkp1 = builder2.buildStrict(KMSTestFixtures.TEST_KEY_IDS[0]); CryptoResult<byte[], ?> result = AwsCrypto.standard().encryptData(mkp1, new byte[0]); verify(customProvider1, atLeastOnce()).getCredentials(); verify(customProvider2, never()).getCredentials(); reset(customProvider1, customProvider2); result = AwsCrypto.standard().encryptData(mkp2, new byte[0]); verify(customProvider1, never()).getCredentials(); verify(customProvider2, atLeastOnce()).getCredentials(); } @Test public void whenBuilderCloned_clientBuilderCustomizationIsRetained() throws Exception { RequestHandler2 handler = spy(new RequestHandler2() {}); KmsMasterKeyProvider mkp = KmsMasterKeyProvider.builder() .withClientBuilder(AWSKMSClientBuilder.standard().withRequestHandlers(handler)) .clone() .buildStrict(KMSTestFixtures.TEST_KEY_IDS[0]); AwsCrypto.standard().encryptData(mkp, new byte[0]); verify(handler, atLeastOnce()).beforeRequest(any()); } @Test(expected = IllegalArgumentException.class) public void whenBogusEndpointIsSet_constructionFails() throws Exception { KmsMasterKeyProvider.builder() .withClientBuilder( AWSKMSClientBuilder.standard() .withEndpointConfiguration( new AwsClientBuilder.EndpointConfiguration( "https://this.does.not.exist.example.com", "bad-region"))); } @Test public void whenUserAgentsOverridden_originalUAsPreserved() throws Exception { RequestHandler2 handler = spy(new RequestHandler2() {}); KmsMasterKeyProvider mkp = KmsMasterKeyProvider.builder() .withClientBuilder( AWSKMSClientBuilder.standard() .withRequestHandlers(handler) .withClientConfiguration( new ClientConfiguration() .withUserAgentPrefix("TEST-UA-PREFIX") .withUserAgentSuffix("TEST-UA-SUFFIX"))) .clone() .buildStrict(KMSTestFixtures.TEST_KEY_IDS[0]); AwsCrypto.standard().encryptData(mkp, new byte[0]); ArgumentCaptor<Request> captor = ArgumentCaptor.forClass(Request.class); verify(handler, atLeastOnce()).beforeRequest(captor.capture()); String ua = (String) captor.getValue().getHeaders().get("User-Agent"); assertTrue(ua.contains("TEST-UA-PREFIX")); assertTrue(ua.contains("TEST-UA-SUFFIX")); assertTrue(ua.contains(VersionInfo.loadUserAgent())); } @Test public void whenDefaultRegionSet_itIsUsedForBareKeyIds() throws Exception { // TODO: Need to set up a role to assume as bare key IDs are relative to the caller account } }
727
0
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk/kms/AwsKmsMrkAwareMasterKeyProviderTest.java
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package com.amazonaws.encryptionsdk.kms; import static com.amazonaws.encryptionsdk.internal.AwsKmsCmkArnInfo.parseInfoFromKeyArn; import static org.junit.Assert.*; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.*; import static org.mockito.Mockito.spy; import com.amazonaws.AmazonServiceException; import com.amazonaws.auth.BasicAWSCredentials; import com.amazonaws.encryptionsdk.*; import com.amazonaws.encryptionsdk.exception.AwsCryptoException; import com.amazonaws.encryptionsdk.exception.CannotUnwrapDataKeyException; import com.amazonaws.encryptionsdk.exception.NoSuchMasterKeyException; import com.amazonaws.encryptionsdk.exception.UnsupportedProviderException; import com.amazonaws.encryptionsdk.kms.KmsMasterKeyProvider.RegionalClientSupplier; import com.amazonaws.encryptionsdk.model.KeyBlob; import com.amazonaws.services.kms.AWSKMS; import com.amazonaws.services.kms.AWSKMSClientBuilder; import com.amazonaws.services.kms.model.DecryptRequest; import com.amazonaws.services.kms.model.DecryptResult; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import org.junit.Test; import org.junit.experimental.runners.Enclosed; import org.junit.runner.RunWith; @RunWith(Enclosed.class) public class AwsKmsMrkAwareMasterKeyProviderTest { public static class getResourceForResourceTypeKey { @Test public void basic_use() { assertEquals( "mrk-edb7fe6942894d32ac46dbb1c922d574", AwsKmsMrkAwareMasterKeyProvider.getResourceForResourceTypeKey( "arn:aws:kms:us-west-2:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574")); } @Test public void not_an_arn() { assertEquals( "mrk-edb7fe6942894d32ac46dbb1c922d574", AwsKmsMrkAwareMasterKeyProvider.getResourceForResourceTypeKey( "mrk-edb7fe6942894d32ac46dbb1c922d574")); final String malformed = "aws:kms:us-west-2::key/garbage"; assertEquals( malformed, AwsKmsMrkAwareMasterKeyProvider.getResourceForResourceTypeKey(malformed)); } @Test public void not_a_key() { final String alias = "arn:aws:kms:us-west-2:658956600833:alias/EncryptDecrypt"; assertEquals(alias, AwsKmsMrkAwareMasterKeyProvider.getResourceForResourceTypeKey(alias)); } } public static class assertMrksAreUnique { @Test // = compliance/framework/aws-kms/aws-kms-mrk-are-unique.txt#2.5 // = type=test // # The caller MUST provide: public void basic_use() { AwsKmsMrkAwareMasterKeyProvider.assertMrksAreUnique( Arrays.asList( "arn:aws:kms:us-west-2:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574")); } @Test public void no_duplicates() { // = compliance/framework/aws-kms/aws-kms-mrk-are-unique.txt#2.5 // = type=test // # If there are zero duplicate resource ids between the multi-region // # keys, this function MUST exit successfully AwsKmsMrkAwareMasterKeyProvider.assertMrksAreUnique( Arrays.asList( "arn:aws:kms:us-west-2:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574", "arn:aws:kms:us-west-2:658956600833:key/b3537ef1-d8dc-4780-9f5a-55776cbb2f7f")); } @Test // = compliance/framework/aws-kms/aws-kms-mrk-are-unique.txt#2.5 // = type=test // # If the list does not contain any multi-Region keys (aws-kms-key- // # arn.md#identifying-an-aws-kms-multi-region-key) this function MUST // # exit successfully. public void no_mrks_at_all() { AwsKmsMrkAwareMasterKeyProvider.assertMrksAreUnique( Arrays.asList( "arn:aws:kms:us-west-2:658956600833:key/b3537ef1-d8dc-4780-9f5a-55776cbb2f7f", "arn:aws:kms:us-west-2:658956600833:key/b3537ef1-d8dc-4780-9f5a-55776cbb2f7f")); } @Test public void non_mrk_duplicates_ok() { AwsKmsMrkAwareMasterKeyProvider.assertMrksAreUnique( Arrays.asList( "arn:aws:kms:us-west-2:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574", "arn:aws:kms:us-west-2:658956600833:key/b3537ef1-d8dc-4780-9f5a-55776cbb2f7f", "arn:aws:kms:us-west-2:658956600833:key/b3537ef1-d8dc-4780-9f5a-55776cbb2f7f", "arn:aws:kms:us-west-2:658956600833:alias/EncryptDecrypt", "arn:aws:kms:us-west-2:658956600833:alias/EncryptDecrypt")); } @Test // = compliance/framework/aws-kms/aws-kms-mrk-are-unique.txt#2.5 // = type=test // # If any duplicate multi-region resource ids exist, this function MUST // # yield an error that includes all identifiers with duplicate resource // # ids not only the first duplicate found. public void no_duplicate_mrks() { assertThrows( IllegalArgumentException.class, () -> AwsKmsMrkAwareMasterKeyProvider.assertMrksAreUnique( Arrays.asList( "arn:aws:kms:us-west-2:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574", "arn:aws:kms:us-east-1:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574"))); } } // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.6 // = type=test // # On initialization the caller MUST provide: public static class AwsKmsMrkAwareMasterKeyProviderBuilderTests { @Test public void basic_use() { final AwsKmsMrkAwareMasterKeyProvider strict = AwsKmsMrkAwareMasterKeyProvider.builder() .buildStrict( "arn:aws:kms:us-west-2:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574"); final AwsKmsMrkAwareMasterKeyProvider discovery = AwsKmsMrkAwareMasterKeyProvider.builder().buildDiscovery(); // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.5 // = type=test // # MUST implement the Master Key Provider Interface (../master-key- // # provider-interface.md#interface) assertTrue(MasterKeyProvider.class.isInstance(strict)); assertTrue(MasterKeyProvider.class.isInstance(discovery)); // These are not testable because of how the builder is structured. // // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.6 // = type=test // # A discovery filter MUST NOT be configured in strict mode. // // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.6 // = type=test // # A default MRK Region MUST NOT be configured in strict mode. // // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.6 // = type=test // # In // # discovery mode if a default MRK Region is not configured the AWS SDK // # Default Region MUST be used. // // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.6 // = type=test // # The key id list MUST be empty in discovery mode. // // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.6 // = type=test // # The regional client // # supplier MUST be defined in discovery mode. } @Test // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.6 // = type=test // # The key id list MUST NOT be empty or null in strict mode. public void no_noop() { assertThrows( IllegalArgumentException.class, () -> AwsKmsMrkAwareMasterKeyProvider.builder().buildStrict()); assertThrows( IllegalArgumentException.class, () -> AwsKmsMrkAwareMasterKeyProvider.builder().buildStrict(new ArrayList<String>())); } @Test // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.6 // = type=test // # The key id // # list MUST NOT contain any null or empty string values. public void no_null_identifiers() { assertThrows( IllegalArgumentException.class, () -> AwsKmsMrkAwareMasterKeyProvider.builder() .buildStrict( "arn:aws:kms:us-west-2:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574", "")); assertThrows( IllegalArgumentException.class, () -> AwsKmsMrkAwareMasterKeyProvider.builder() .buildStrict( "arn:aws:kms:us-west-2:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574", null)); } @Test // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.6 // = type=test // # All AWS KMS // # key identifiers are be passed to Assert AWS KMS MRK are unique (aws- // # kms-mrk-are-unique.md#Implementation) and the function MUST return // # success. public void no_duplicate_mrks() { assertThrows( IllegalArgumentException.class, () -> AwsKmsMrkAwareMasterKeyProvider.builder() .buildStrict( "arn:aws:kms:us-west-2:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574", "arn:aws:kms:us-east-1:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574")); } @Test public void always_need_a_region() { assertThrows( AwsCryptoException.class, () -> AwsKmsMrkAwareMasterKeyProvider.builder() .withDefaultRegion(null) .buildStrict("mrk-edb7fe6942894d32ac46dbb1c922d574")); AwsKmsMrkAwareMasterKeyProvider.builder() .withDefaultRegion("us-east-1") .buildStrict("mrk-edb7fe6942894d32ac46dbb1c922d574"); } @Test // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.6 // = type=test // # If an AWS SDK Default Region can not be // # obtained initialization MUST fail. public void discovery_region_can_not_be_null() { assertThrows( IllegalArgumentException.class, () -> AwsKmsMrkAwareMasterKeyProvider.builder() // need to force the default region to `null` // otherwise it may pick one up from the environment. .withDefaultRegion(null) .withDiscoveryMrkRegion(null) .buildDiscovery()); } @Test public void basic_credentials_and_builder() { BasicAWSCredentials creds = new BasicAWSCredentials("asdf", "qwer"); AwsKmsMrkAwareMasterKeyProvider.builder() .withClientBuilder(AWSKMSClientBuilder.standard()) .withCredentials(creds) .buildDiscovery(); } } public static class extractRegion { @Test public void basic_use() { final String test = AwsKmsMrkAwareMasterKeyProvider.extractRegion( "us-east-1", "us-east-2", Optional.of( "arn:aws:kms:us-west-2:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574"), parseInfoFromKeyArn( "arn:aws:kms:us-west-2:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574"), false); assertEquals("us-west-2", test); } @Test // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.7 // = type=test // # If the requested AWS KMS key identifier is not a well formed ARN the // # AWS Region MUST be the configured default region this SHOULD be // # obtained from the AWS SDK. public void not_an_arn() { final String test = AwsKmsMrkAwareMasterKeyProvider.extractRegion( "us-east-1", "us-east-2", Optional.empty(), parseInfoFromKeyArn("mrk-edb7fe6942894d32ac46dbb1c922d574"), false); assertEquals("us-east-1", test); } @Test // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.7 // = type=test // # Otherwise if the requested AWS KMS key // # identifier is identified as a multi-Region key (aws-kms-key- // # arn.md#identifying-an-aws-kms-multi-region-key), then AWS Region MUST // # be the region from the AWS KMS key ARN stored in the provider info // # from the encrypted data key. public void not_an_mrk() { final String test = AwsKmsMrkAwareMasterKeyProvider.extractRegion( "us-east-1", "us-east-2", Optional.of( "arn:aws:kms:us-west-2:658956600833:key/b3537ef1-d8dc-4780-9f5a-55776cbb2f7f"), parseInfoFromKeyArn( "arn:aws:kms:us-west-2:658956600833:key/b3537ef1-d8dc-4780-9f5a-55776cbb2f7f"), false); assertEquals("us-west-2", test); final String test2 = AwsKmsMrkAwareMasterKeyProvider.extractRegion( "us-east-1", "us-east-2", Optional.of("arn:aws:kms:us-west-2:658956600833:alias/mrk-nasty"), parseInfoFromKeyArn("arn:aws:kms:us-west-2:658956600833:alias/mrk-nasty"), false); assertEquals("us-west-2", test2); } @Test // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.7 // = type=test // # Otherwise if the mode is discovery then // # the AWS Region MUST be the discovery MRK region. public void mrk_in_discovery() { final String test = AwsKmsMrkAwareMasterKeyProvider.extractRegion( "us-east-1", "us-east-2", Optional.empty(), parseInfoFromKeyArn( "arn:aws:kms:us-west-2:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574"), true); assertEquals("us-east-2", test); } @Test // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.7 // = type=test // # Finally if the // # provider info is identified as a multi-Region key (aws-kms-key- // # arn.md#identifying-an-aws-kms-multi-region-key) the AWS Region MUST // # be the region from the AWS KMS key in the configured key ids matched // # to the requested AWS KMS key by using AWS KMS MRK Match for Decrypt // # (aws-kms-mrk-match-for-decrypt.md#implementation). public void fuzzy_match_mrk() { final String test = AwsKmsMrkAwareMasterKeyProvider.extractRegion( "us-east-1", "us-east-2", Optional.of( "arn:aws:kms:us-west-2:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574"), parseInfoFromKeyArn( "arn:aws:kms:us-west-1:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574"), false); assertEquals("us-west-2", test); } } public static class getMasterKey { @Test public void basic_use() { final String identifier = "arn:aws:kms:us-west-2:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574"; final AWSKMS client = spy(new MockKMSClient()); final RegionalClientSupplier supplier = mock(RegionalClientSupplier.class); when(supplier.getClient(any())).thenReturn(client); AwsKmsMrkAwareMasterKeyProvider mkp = AwsKmsMrkAwareMasterKeyProvider.builder() .withCustomClientFactory(supplier) .buildStrict(identifier); // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.7 // = type=test // # The input MUST be the same as the Master Key Provider Get Master Key // # (../master-key-provider-interface.md#get-master-key) interface. AwsKmsMrkAwareMasterKey test = mkp.getMasterKey("aws-kms", identifier); // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.7 // = type=test // # The output MUST be the same as the Master Key Provider Get Master Key // # (../master-key-provider-interface.md#get-master-key) interface. assertTrue(AwsKmsMrkAwareMasterKey.class.isInstance((test))); assertEquals(identifier, test.getKeyId()); verify(supplier, times(1)).getClient("us-west-2"); } @Test public void basic_mrk_use() { final String configuredIdentifier = "arn:aws:kms:us-west-2:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574"; final String requestedIdentifier = "arn:aws:kms:us-east-1:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574"; final AWSKMS client = spy(new MockKMSClient()); final RegionalClientSupplier supplier = mock(RegionalClientSupplier.class); when(supplier.getClient(any())).thenReturn(client); AwsKmsMrkAwareMasterKeyProvider mkp = AwsKmsMrkAwareMasterKeyProvider.builder() .withCustomClientFactory(supplier) .buildStrict(configuredIdentifier); AwsKmsMrkAwareMasterKey test = mkp.getMasterKey("aws-kms", requestedIdentifier); assertEquals(configuredIdentifier, test.getKeyId()); verify(supplier, times(1)).getClient("us-west-2"); } @Test public void other_basic_uses() { final AWSKMS client = spy(new MockKMSClient()); final RegionalClientSupplier supplier = mock(RegionalClientSupplier.class); when(supplier.getClient(any())).thenReturn(client); // A raw alias is a valid configuration for encryption final String rawAliasIdentifier = "alias/my-alias"; AwsKmsMrkAwareMasterKeyProvider.builder() .withCustomClientFactory(supplier) .buildStrict(rawAliasIdentifier) .getMasterKey("aws-kms", rawAliasIdentifier); // A raw alias is a valid configuration for encryption final String rawKeyIdentifier = "mrk-edb7fe6942894d32ac46dbb1c922d574"; AwsKmsMrkAwareMasterKeyProvider.builder() .withCustomClientFactory(supplier) .buildStrict(rawKeyIdentifier) .getMasterKey("aws-kms", rawKeyIdentifier); } @Test // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.7 // = type=test // # The function MUST only provide master keys if the input provider id // # equals "aws-kms". public void only_this_provider() { final String identifier = "arn:aws:kms:us-west-2:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574"; final AWSKMS client = spy(new MockKMSClient()); final RegionalClientSupplier supplier = mock(RegionalClientSupplier.class); when(supplier.getClient(any())).thenReturn(client); AwsKmsMrkAwareMasterKeyProvider mkp = AwsKmsMrkAwareMasterKeyProvider.builder() .withCustomClientFactory(supplier) .buildStrict(identifier); assertThrows( UnsupportedProviderException.class, () -> mkp.getMasterKey("not-aws-kms", identifier)); } @Test // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.7 // = type=test // # In strict mode, the requested AWS KMS key ARN MUST // # match a member of the configured key ids by using AWS KMS MRK Match // # for Decrypt (aws-kms-mrk-match-for-decrypt.md#implementation) // # otherwise this function MUST error. public void no_key_id_match() { final String identifier = "arn:aws:kms:us-west-2:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574"; final AWSKMS client = spy(new MockKMSClient()); final RegionalClientSupplier supplier = mock(RegionalClientSupplier.class); when(supplier.getClient(any())).thenReturn(client); final AwsKmsMrkAwareMasterKeyProvider mkp = AwsKmsMrkAwareMasterKeyProvider.builder() .withCustomClientFactory(supplier) .buildStrict(identifier); assertThrows( NoSuchMasterKeyException.class, () -> mkp.getMasterKey("aws-kms", "does-not-match-configured")); } @Test // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.7 // = type=test // # In discovery mode, the requested // # AWS KMS key identifier MUST be a well formed AWS KMS ARN. public void discovery_request_must_be_arn() { AwsKmsMrkAwareMasterKeyProvider mkp = AwsKmsMrkAwareMasterKeyProvider.builder().buildDiscovery(); assertThrows( NoSuchMasterKeyException.class, () -> mkp.getMasterKey("aws-kms", "mrk-edb7fe6942894d32ac46dbb1c922d574")); } @Test // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.7 // = type=test // # In // # discovery mode if a discovery filter is configured the requested AWS // # KMS key ARN's "partition" MUST match the discovery filter's // # "partition" and the AWS KMS key ARN's "account" MUST exist in the // # discovery filter's account id set. public void discovery_filter_must_match() { final String identifier = "arn:aws:kms:us-west-2:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574"; final AWSKMS client = spy(new MockKMSClient()); final RegionalClientSupplier supplier = mock(RegionalClientSupplier.class); when(supplier.getClient(any())).thenReturn(client); assertThrows( NoSuchMasterKeyException.class, () -> AwsKmsMrkAwareMasterKeyProvider.builder() .buildDiscovery(new DiscoveryFilter("aws", Arrays.asList("not-111122223333"))) .getMasterKey("aws-kms", identifier)); assertThrows( NoSuchMasterKeyException.class, () -> AwsKmsMrkAwareMasterKeyProvider.builder() .buildDiscovery(new DiscoveryFilter("not-aws", Arrays.asList("111122223333"))) .getMasterKey("aws-kms", identifier)); } @Test // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.7 // = type=test // # In discovery mode a AWS KMS MRK Aware Master Key (aws-kms-mrk-aware- // # master-key.md) MUST be returned configured with public void discovery_magic_to_make_the_region_match() { final String identifier = "arn:aws:kms:us-west-2:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574"; final AWSKMS client = spy(new MockKMSClient()); final RegionalClientSupplier supplier = mock(RegionalClientSupplier.class); when(supplier.getClient(any())).thenReturn(client); AwsKmsMrkAwareMasterKeyProvider mkp = AwsKmsMrkAwareMasterKeyProvider.builder() .withCustomClientFactory(supplier) .withDiscoveryMrkRegion("my-region") .buildDiscovery(); AwsKmsMrkAwareMasterKey test = mkp.getMasterKey("aws-kms", identifier); // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.7 // = type=test // # An AWS KMS client // # MUST be obtained by calling the regional client supplier with this // # AWS Region. assertEquals( "arn:aws:kms:my-region:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574", test.getKeyId()); verify(supplier, times(1)).getClient("my-region"); } @Test // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.7 // = type=test // # In strict mode a AWS KMS MRK Aware Master Key (aws-kms-mrk-aware- // # master-key.md) MUST be returned configured with public void strict_mrk_region_match() { final String identifier = "arn:aws:kms:us-west-2:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574"; final String configIdentifier = "arn:aws:kms:us-east-1:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574"; final AWSKMS client = spy(new MockKMSClient()); final RegionalClientSupplier supplier = mock(RegionalClientSupplier.class); when(supplier.getClient(any())).thenReturn(client); AwsKmsMrkAwareMasterKeyProvider mkp = AwsKmsMrkAwareMasterKeyProvider.builder() .withCustomClientFactory(supplier) .buildStrict(configIdentifier); AwsKmsMrkAwareMasterKey test = mkp.getMasterKey("aws-kms", identifier); assertEquals(configIdentifier, test.getKeyId()); verify(supplier, times(1)).getClient("us-east-1"); } } public static class decryptDataKey { @Test public void basic_use() { final String identifier = "arn:aws:kms:us-west-2:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574"; final CryptoAlgorithm ALGORITHM_SUITE = CryptoAlgorithm.ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA256; final List<String> GRANT_TOKENS = Collections.singletonList("testGrantToken"); final Map<String, String> ENCRYPTION_CONTEXT = Collections.singletonMap("myKey", "myValue"); final byte[] cipherText = new byte[10]; final EncryptedDataKey edk1 = new KeyBlob("aws-kms", identifier.getBytes(StandardCharsets.UTF_8), cipherText); final EncryptedDataKey edk2 = new KeyBlob("aws-kms", identifier.getBytes(StandardCharsets.UTF_8), cipherText); final RegionalClientSupplier supplier = mock(RegionalClientSupplier.class); final AWSKMS client = mock(AWSKMS.class); when(client.decrypt(any())) .thenReturn( new DecryptResult() .withKeyId(identifier) .withPlaintext(ByteBuffer.allocate(ALGORITHM_SUITE.getDataKeyLength()))); when(supplier.getClient(any())).thenReturn(client); AwsKmsMrkAwareMasterKeyProvider mkp = AwsKmsMrkAwareMasterKeyProvider.builder() .withCustomClientFactory(supplier) .buildStrict(identifier) .withGrantTokens(GRANT_TOKENS); // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.9 // = type=test // # The input MUST be the same as the Master Key Provider Decrypt Data // # Key (../master-key-provider-interface.md#decrypt-data-key) interface. final DataKey<AwsKmsMrkAwareMasterKey> test = mkp.decryptDataKey(ALGORITHM_SUITE, Arrays.asList(edk1, edk2), ENCRYPTION_CONTEXT); // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.9 // = type=test // # For each encrypted data key in the filtered set, one at a time, the // # master key provider MUST call Get Master Key (aws-kms-mrk-aware- // # master-key-provider.md#get-master-key) with the encrypted data key's // # provider info as the AWS KMS key ARN. // // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.9 // = type=test // # It MUST call Decrypt Data Key // # (aws-kms-mrk-aware-master-key.md#decrypt-data-key) on this master key // # with the input algorithm, this single encrypted data key, and the // # input encryption context. // // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.9 // = type=test // # If the decrypt data key call is // # successful, then this function MUST return this result and not // # attempt to decrypt any more encrypted data keys. verify(client, times((1))) .decrypt( new DecryptRequest() .withGrantTokens(GRANT_TOKENS) .withEncryptionContext(ENCRYPTION_CONTEXT) .withKeyId(identifier) .withCiphertextBlob(ByteBuffer.wrap(cipherText))); // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.9 // = type=test // # The output MUST be the same as the Master Key Provider Decrypt Data // # Key (../master-key-provider-interface.md#decrypt-data-key) interface. assertTrue(DataKey.class.isInstance(test)); } @Test // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.9 // = type=test // # The set of encrypted data keys MUST first be filtered to match this // # master key's configuration. public void only_if_providers_match() { final String identifier = "arn:aws:kms:us-west-2:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574"; final CryptoAlgorithm ALGORITHM_SUITE = CryptoAlgorithm.ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA256; final Map<String, String> ENCRYPTION_CONTEXT = Collections.singletonMap("myKey", "myValue"); final EncryptedDataKey edk = new KeyBlob( "not-aws-kms", "not the identifier".getBytes(StandardCharsets.UTF_8), new byte[10]); AwsKmsMrkAwareMasterKeyProvider mkp = AwsKmsMrkAwareMasterKeyProvider.builder().buildStrict(identifier); // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.9 // = type=test // # To match the encrypted data key's // # provider ID MUST exactly match the value "aws-kms". final CannotUnwrapDataKeyException test = assertThrows( "Unable to decrypt any data keys", CannotUnwrapDataKeyException.class, () -> mkp.decryptDataKey(ALGORITHM_SUITE, Arrays.asList(edk), ENCRYPTION_CONTEXT)); assertEquals(0, test.getSuppressed().length); } @Test // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.9 // = type=test // # Additionally // # each provider info MUST be a valid AWS KMS ARN (aws-kms-key-arn.md#a- // # valid-aws-kms-arn) with a resource type of "key". public void provider_info_must_be_arn() { final String identifier = "arn:aws:kms:us-west-2:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574"; final String aliasArn = "arn:aws:kms:us-west-2:111122223333:alias/mrk-edb7fe6942894d32ac46dbb1c922d574"; final CryptoAlgorithm ALGORITHM_SUITE = CryptoAlgorithm.ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA256; final Map<String, String> ENCRYPTION_CONTEXT = Collections.singletonMap("myKey", "myValue"); final EncryptedDataKey edk = new KeyBlob("aws-kms", aliasArn.getBytes(StandardCharsets.UTF_8), new byte[10]); AwsKmsMrkAwareMasterKeyProvider mkp = AwsKmsMrkAwareMasterKeyProvider.builder().buildStrict(identifier); final IllegalStateException test = assertThrows( "Invalid provider info in message.", IllegalStateException.class, () -> mkp.decryptDataKey(ALGORITHM_SUITE, Arrays.asList(edk), ENCRYPTION_CONTEXT)); assertEquals(0, test.getSuppressed().length); } @Test // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.9 // = type=test // # If this attempt results in an error, then // # these errors MUST be collected. // // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.9 // = type=test // # If all the input encrypted data keys have been processed then this // # function MUST yield an error that includes all the collected errors. public void exception_wrapped() { final String identifier = "arn:aws:kms:us-west-2:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574"; final CryptoAlgorithm ALGORITHM_SUITE = CryptoAlgorithm.ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA256; final Map<String, String> ENCRYPTION_CONTEXT = Collections.singletonMap("myKey", "myValue"); final EncryptedDataKey edk = new KeyBlob("aws-kms", identifier.getBytes(StandardCharsets.UTF_8), new byte[10]); final RegionalClientSupplier supplier = mock(RegionalClientSupplier.class); final AWSKMS client = mock(AWSKMS.class); final String clientErrMsg = "asdf"; when(client.decrypt(any())).thenThrow(new AmazonServiceException(clientErrMsg)); when(supplier.getClient(any())).thenReturn(client); AwsKmsMrkAwareMasterKeyProvider mkp = AwsKmsMrkAwareMasterKeyProvider.builder() .withCustomClientFactory(supplier) .buildStrict(identifier); CannotUnwrapDataKeyException test = assertThrows( "Unable to decrypt any data keys", CannotUnwrapDataKeyException.class, () -> mkp.decryptDataKey(ALGORITHM_SUITE, Arrays.asList(edk), ENCRYPTION_CONTEXT)); assertEquals(1, test.getSuppressed().length); Throwable fromMasterKey = Arrays.stream(test.getSuppressed()).findFirst().get(); assertTrue(fromMasterKey instanceof CannotUnwrapDataKeyException); assertEquals(1, fromMasterKey.getSuppressed().length); Throwable fromClient = Arrays.stream(fromMasterKey.getSuppressed()).findFirst().get(); assertTrue(fromClient instanceof AmazonServiceException); assertTrue(fromClient.getMessage().startsWith(clientErrMsg)); } } public static class clientFactory { @Test public void basic_use() { final ConcurrentHashMap<String, AWSKMS> cache = spy(new ConcurrentHashMap<>()); final AWSKMS test = AwsKmsMrkAwareMasterKeyProvider.Builder.clientFactory(cache, null).getClient("asdf"); assertNotEquals(null, test); verify(cache, times(1)).containsKey("asdf"); } @Test public void use_clients_that_exist() { final String region = "asdf"; final ConcurrentHashMap<String, AWSKMS> cache = spy(new ConcurrentHashMap<>()); // Add something so we can verify that we get it final AWSKMS client = mock(AWSKMS.class); cache.put(region, client); final AWSKMS test = AwsKmsMrkAwareMasterKeyProvider.Builder.clientFactory(cache, null).getClient(region); assertEquals(client, test); } } public static class getMasterKeysForEncryption { @Test public void basic_use() { final String identifier = "arn:aws:kms:us-west-2:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574"; final AWSKMS client = spy(new MockKMSClient()); final RegionalClientSupplier supplier = mock(RegionalClientSupplier.class); when(supplier.getClient("us-west-2")).thenReturn(client); final MasterKeyRequest request = MasterKeyRequest.newBuilder().build(); final AwsKmsMrkAwareMasterKeyProvider mkp = AwsKmsMrkAwareMasterKeyProvider.builder() .withCustomClientFactory(supplier) .buildStrict(identifier); // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.8 // = type=test // # The input MUST be the same as the Master Key Provider Get Master Keys // # For Encryption (../master-key-provider-interface.md#get-master-keys- // # for-encryption) interface. // // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.8 // = type=test // # The output MUST be the same as the Master Key Provider Get Master // # Keys For Encryption (../master-key-provider-interface.md#get-master- // # keys-for-encryption) interface. final List<AwsKmsMrkAwareMasterKey> test = mkp.getMasterKeysForEncryption(request); // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.8 // = type=test // # If the configured mode is strict this function MUST return a // # list of master keys obtained by calling Get Master Key (aws-kms-mrk- // # aware-master-key-provider.md#get-master-key) for each AWS KMS key // # identifier in the configured key ids assertEquals(1, test.size()); assertEquals(identifier, test.get(0).getKeyId()); } @Test // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.8 // = type=test // # If the configured mode is discovery the function MUST return an empty // # list. public void no_keys_is_empty_list() { final AwsKmsMrkAwareMasterKeyProvider mkp = AwsKmsMrkAwareMasterKeyProvider.builder().buildDiscovery(); final List<AwsKmsMrkAwareMasterKey> test = mkp.getMasterKeysForEncryption(MasterKeyRequest.newBuilder().build()); assertEquals(0, test.size()); } } }
728
0
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk/kms/KmsMasterKeyTest.java
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package com.amazonaws.encryptionsdk.kms; import static com.amazonaws.encryptionsdk.TestUtils.assertThrows; import static com.amazonaws.encryptionsdk.internal.RandomBytesGenerator.generate; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.mockito.ArgumentMatchers.isA; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import com.amazonaws.AmazonWebServiceRequest; import com.amazonaws.RequestClientOptions; import com.amazonaws.encryptionsdk.CryptoAlgorithm; import com.amazonaws.encryptionsdk.DataKey; import com.amazonaws.encryptionsdk.EncryptedDataKey; import com.amazonaws.encryptionsdk.MasterKey; import com.amazonaws.encryptionsdk.MasterKeyProvider; import com.amazonaws.encryptionsdk.exception.CannotUnwrapDataKeyException; import com.amazonaws.encryptionsdk.internal.VersionInfo; import com.amazonaws.encryptionsdk.model.KeyBlob; import com.amazonaws.services.kms.AWSKMS; import com.amazonaws.services.kms.model.DecryptRequest; import com.amazonaws.services.kms.model.DecryptResult; import com.amazonaws.services.kms.model.EncryptRequest; import com.amazonaws.services.kms.model.GenerateDataKeyRequest; import com.amazonaws.services.kms.model.GenerateDataKeyResult; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.function.Supplier; import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec; import org.junit.Test; import org.mockito.ArgumentCaptor; public class KmsMasterKeyTest { private static final String AWS_KMS_PROVIDER_ID = "aws-kms"; private static final String OTHER_PROVIDER_ID = "not-aws-kms"; private static final CryptoAlgorithm ALGORITHM_SUITE = CryptoAlgorithm.ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA256; private static final SecretKey DATA_KEY = new SecretKeySpec( generate(ALGORITHM_SUITE.getDataKeyLength()), ALGORITHM_SUITE.getDataKeyAlgo()); private static final List<String> GRANT_TOKENS = Collections.singletonList("testGrantToken"); private static final Map<String, String> ENCRYPTION_CONTEXT = Collections.singletonMap("myKey", "myValue"); @Test public void testEncryptAndDecrypt() { AWSKMS client = spy(new MockKMSClient()); Supplier supplier = mock(Supplier.class); when(supplier.get()).thenReturn(client); MasterKey otherMasterKey = mock(MasterKey.class); when(otherMasterKey.getProviderId()).thenReturn(OTHER_PROVIDER_ID); when(otherMasterKey.getKeyId()).thenReturn("someOtherId"); DataKey dataKey = new DataKey( DATA_KEY, new byte[0], OTHER_PROVIDER_ID.getBytes(StandardCharsets.UTF_8), otherMasterKey); MasterKeyProvider mkp = mock(MasterKeyProvider.class); when(mkp.getDefaultProviderId()).thenReturn(AWS_KMS_PROVIDER_ID); String keyId = client.createKey().getKeyMetadata().getArn(); KmsMasterKey kmsMasterKey = KmsMasterKey.getInstance(supplier, keyId, mkp); kmsMasterKey.setGrantTokens(GRANT_TOKENS); DataKey<KmsMasterKey> encryptDataKeyResult = kmsMasterKey.encryptDataKey(ALGORITHM_SUITE, ENCRYPTION_CONTEXT, dataKey); ArgumentCaptor<EncryptRequest> er = ArgumentCaptor.forClass(EncryptRequest.class); verify(client, times(1)).encrypt(er.capture()); EncryptRequest actualRequest = er.getValue(); assertEquals(keyId, actualRequest.getKeyId()); assertEquals(GRANT_TOKENS, actualRequest.getGrantTokens()); assertEquals(ENCRYPTION_CONTEXT, actualRequest.getEncryptionContext()); assertArrayEquals(DATA_KEY.getEncoded(), actualRequest.getPlaintext().array()); assertUserAgent(actualRequest); assertEquals(encryptDataKeyResult.getMasterKey(), kmsMasterKey); assertEquals(AWS_KMS_PROVIDER_ID, encryptDataKeyResult.getProviderId()); assertArrayEquals( keyId.getBytes(StandardCharsets.UTF_8), encryptDataKeyResult.getProviderInformation()); assertNotNull(encryptDataKeyResult.getEncryptedDataKey()); DataKey<KmsMasterKey> decryptDataKeyResult = kmsMasterKey.decryptDataKey( ALGORITHM_SUITE, Collections.singletonList(encryptDataKeyResult), ENCRYPTION_CONTEXT); ArgumentCaptor<DecryptRequest> decrypt = ArgumentCaptor.forClass(DecryptRequest.class); verify(client, times(1)).decrypt(decrypt.capture()); DecryptRequest actualDecryptRequest = decrypt.getValue(); assertArrayEquals( encryptDataKeyResult.getProviderInformation(), actualDecryptRequest.getKeyId().getBytes(StandardCharsets.UTF_8)); assertEquals(GRANT_TOKENS, actualDecryptRequest.getGrantTokens()); assertEquals(ENCRYPTION_CONTEXT, actualDecryptRequest.getEncryptionContext()); assertArrayEquals( encryptDataKeyResult.getEncryptedDataKey(), actualDecryptRequest.getCiphertextBlob().array()); assertUserAgent(actualDecryptRequest); assertEquals(DATA_KEY, decryptDataKeyResult.getKey()); assertArrayEquals( keyId.getBytes(StandardCharsets.UTF_8), decryptDataKeyResult.getProviderInformation()); } @Test public void testGenerateAndDecrypt() { AWSKMS client = spy(new MockKMSClient()); Supplier supplier = mock(Supplier.class); when(supplier.get()).thenReturn(client); MasterKeyProvider mkp = mock(MasterKeyProvider.class); when(mkp.getDefaultProviderId()).thenReturn(AWS_KMS_PROVIDER_ID); String keyId = client.createKey().getKeyMetadata().getArn(); KmsMasterKey kmsMasterKey = KmsMasterKey.getInstance(supplier, keyId, mkp); kmsMasterKey.setGrantTokens(GRANT_TOKENS); DataKey<KmsMasterKey> generateDataKeyResult = kmsMasterKey.generateDataKey(ALGORITHM_SUITE, ENCRYPTION_CONTEXT); ArgumentCaptor<GenerateDataKeyRequest> gr = ArgumentCaptor.forClass(GenerateDataKeyRequest.class); verify(client, times(1)).generateDataKey(gr.capture()); GenerateDataKeyRequest actualRequest = gr.getValue(); assertEquals(keyId, actualRequest.getKeyId()); assertEquals(GRANT_TOKENS, actualRequest.getGrantTokens()); assertEquals(ENCRYPTION_CONTEXT, actualRequest.getEncryptionContext()); assertEquals(ALGORITHM_SUITE.getDataKeyLength(), actualRequest.getNumberOfBytes().longValue()); assertUserAgent(actualRequest); assertNotNull(generateDataKeyResult.getKey()); assertEquals( ALGORITHM_SUITE.getDataKeyLength(), generateDataKeyResult.getKey().getEncoded().length); assertEquals(ALGORITHM_SUITE.getDataKeyAlgo(), generateDataKeyResult.getKey().getAlgorithm()); assertNotNull(generateDataKeyResult.getEncryptedDataKey()); DataKey<KmsMasterKey> decryptDataKeyResult = kmsMasterKey.decryptDataKey( ALGORITHM_SUITE, Collections.singletonList(generateDataKeyResult), ENCRYPTION_CONTEXT); ArgumentCaptor<DecryptRequest> decrypt = ArgumentCaptor.forClass(DecryptRequest.class); verify(client, times(1)).decrypt(decrypt.capture()); DecryptRequest actualDecryptRequest = decrypt.getValue(); assertArrayEquals( generateDataKeyResult.getProviderInformation(), actualDecryptRequest.getKeyId().getBytes(StandardCharsets.UTF_8)); assertEquals(GRANT_TOKENS, actualDecryptRequest.getGrantTokens()); assertEquals(ENCRYPTION_CONTEXT, actualDecryptRequest.getEncryptionContext()); assertArrayEquals( generateDataKeyResult.getEncryptedDataKey(), actualDecryptRequest.getCiphertextBlob().array()); assertUserAgent(actualDecryptRequest); assertEquals(generateDataKeyResult.getKey(), decryptDataKeyResult.getKey()); assertArrayEquals( keyId.getBytes(StandardCharsets.UTF_8), decryptDataKeyResult.getProviderInformation()); } @Test public void testEncryptWithRawKeyId() { AWSKMS client = spy(new MockKMSClient()); Supplier supplier = mock(Supplier.class); when(supplier.get()).thenReturn(client); MasterKey otherMasterKey = mock(MasterKey.class); when(otherMasterKey.getProviderId()).thenReturn(OTHER_PROVIDER_ID); when(otherMasterKey.getKeyId()).thenReturn("someOtherId"); DataKey dataKey = new DataKey( DATA_KEY, new byte[0], OTHER_PROVIDER_ID.getBytes(StandardCharsets.UTF_8), otherMasterKey); MasterKeyProvider mkp = mock(MasterKeyProvider.class); when(mkp.getDefaultProviderId()).thenReturn(AWS_KMS_PROVIDER_ID); String keyId = client.createKey().getKeyMetadata().getArn(); String rawKeyId = keyId.split("/")[1]; KmsMasterKey kmsMasterKey = KmsMasterKey.getInstance(supplier, rawKeyId, mkp); kmsMasterKey.setGrantTokens(GRANT_TOKENS); DataKey<KmsMasterKey> encryptDataKeyResult = kmsMasterKey.encryptDataKey(ALGORITHM_SUITE, ENCRYPTION_CONTEXT, dataKey); ArgumentCaptor<EncryptRequest> er = ArgumentCaptor.forClass(EncryptRequest.class); verify(client, times(1)).encrypt(er.capture()); EncryptRequest actualRequest = er.getValue(); assertEquals(rawKeyId, actualRequest.getKeyId()); assertEquals(GRANT_TOKENS, actualRequest.getGrantTokens()); assertEquals(ENCRYPTION_CONTEXT, actualRequest.getEncryptionContext()); assertArrayEquals(DATA_KEY.getEncoded(), actualRequest.getPlaintext().array()); assertUserAgent(actualRequest); assertEquals(AWS_KMS_PROVIDER_ID, encryptDataKeyResult.getProviderId()); assertArrayEquals( keyId.getBytes(StandardCharsets.UTF_8), encryptDataKeyResult.getProviderInformation()); assertNotNull(encryptDataKeyResult.getEncryptedDataKey()); } @Test public void testEncryptWrongKeyFormat() { SecretKey key = mock(SecretKey.class); when(key.getFormat()).thenReturn("BadFormat"); AWSKMS client = spy(new MockKMSClient()); Supplier supplier = mock(Supplier.class); when(supplier.get()).thenReturn(client); MasterKey otherMasterKey = mock(MasterKey.class); when(otherMasterKey.getProviderId()).thenReturn(OTHER_PROVIDER_ID); when(otherMasterKey.getKeyId()).thenReturn("someOtherId"); DataKey dataKey = new DataKey( key, new byte[0], OTHER_PROVIDER_ID.getBytes(StandardCharsets.UTF_8), otherMasterKey); MasterKeyProvider mkp = mock(MasterKeyProvider.class); when(mkp.getDefaultProviderId()).thenReturn(AWS_KMS_PROVIDER_ID); String keyId = client.createKey().getKeyMetadata().getArn(); KmsMasterKey kmsMasterKey = KmsMasterKey.getInstance(supplier, keyId, mkp); assertThrows( IllegalArgumentException.class, () -> kmsMasterKey.encryptDataKey(ALGORITHM_SUITE, ENCRYPTION_CONTEXT, dataKey)); } @Test public void testGenerateBadKmsKeyLength() { AWSKMS client = spy(new MockKMSClient()); Supplier supplier = mock(Supplier.class); when(supplier.get()).thenReturn(client); MasterKeyProvider mkp = mock(MasterKeyProvider.class); when(mkp.getDefaultProviderId()).thenReturn(AWS_KMS_PROVIDER_ID); String keyId = client.createKey().getKeyMetadata().getArn(); KmsMasterKey kmsMasterKey = KmsMasterKey.getInstance(supplier, keyId, mkp); GenerateDataKeyResult badResult = new GenerateDataKeyResult(); badResult.setKeyId(keyId); badResult.setPlaintext(ByteBuffer.allocate(ALGORITHM_SUITE.getDataKeyLength() + 1)); doReturn(badResult).when(client).generateDataKey(isA(GenerateDataKeyRequest.class)); assertThrows( IllegalStateException.class, () -> kmsMasterKey.generateDataKey(ALGORITHM_SUITE, ENCRYPTION_CONTEXT)); } @Test public void testDecryptBadKmsKeyLength() { AWSKMS client = spy(new MockKMSClient()); Supplier supplier = mock(Supplier.class); when(supplier.get()).thenReturn(client); MasterKeyProvider mkp = mock(MasterKeyProvider.class); when(mkp.getDefaultProviderId()).thenReturn(AWS_KMS_PROVIDER_ID); String keyId = client.createKey().getKeyMetadata().getArn(); KmsMasterKey kmsMasterKey = KmsMasterKey.getInstance(supplier, keyId, mkp); DecryptResult badResult = new DecryptResult(); badResult.setKeyId(keyId); badResult.setPlaintext(ByteBuffer.allocate(ALGORITHM_SUITE.getDataKeyLength() + 1)); doReturn(badResult).when(client).decrypt(isA(DecryptRequest.class)); EncryptedDataKey edk = new KeyBlob( AWS_KMS_PROVIDER_ID, keyId.getBytes(StandardCharsets.UTF_8), generate(ALGORITHM_SUITE.getDataKeyLength())); assertThrows( IllegalStateException.class, () -> kmsMasterKey.decryptDataKey( ALGORITHM_SUITE, Collections.singletonList(edk), ENCRYPTION_CONTEXT)); } @Test public void testDecryptMissingKmsKeyId() { AWSKMS client = spy(new MockKMSClient()); Supplier supplier = mock(Supplier.class); when(supplier.get()).thenReturn(client); MasterKeyProvider mkp = mock(MasterKeyProvider.class); when(mkp.getDefaultProviderId()).thenReturn(AWS_KMS_PROVIDER_ID); String keyId = client.createKey().getKeyMetadata().getArn(); KmsMasterKey kmsMasterKey = KmsMasterKey.getInstance(supplier, keyId, mkp); DecryptResult badResult = new DecryptResult(); badResult.setPlaintext(ByteBuffer.allocate(ALGORITHM_SUITE.getDataKeyLength())); doReturn(badResult).when(client).decrypt(isA(DecryptRequest.class)); EncryptedDataKey edk = new KeyBlob( AWS_KMS_PROVIDER_ID, keyId.getBytes(StandardCharsets.UTF_8), generate(ALGORITHM_SUITE.getDataKeyLength())); assertThrows( IllegalStateException.class, "Received an empty keyId from KMS", () -> kmsMasterKey.decryptDataKey( ALGORITHM_SUITE, Collections.singletonList(edk), ENCRYPTION_CONTEXT)); } @Test public void testDecryptMismatchedKmsKeyId() { AWSKMS client = spy(new MockKMSClient()); Supplier supplier = mock(Supplier.class); when(supplier.get()).thenReturn(client); MasterKeyProvider mkp = mock(MasterKeyProvider.class); when(mkp.getDefaultProviderId()).thenReturn(AWS_KMS_PROVIDER_ID); String keyId = client.createKey().getKeyMetadata().getArn(); KmsMasterKey kmsMasterKey = KmsMasterKey.getInstance(supplier, keyId, mkp); DecryptResult badResult = new DecryptResult(); badResult.setKeyId("mismatchedID"); badResult.setPlaintext(ByteBuffer.allocate(ALGORITHM_SUITE.getDataKeyLength())); doReturn(badResult).when(client).decrypt(isA(DecryptRequest.class)); EncryptedDataKey edk = new KeyBlob( AWS_KMS_PROVIDER_ID, keyId.getBytes(StandardCharsets.UTF_8), generate(ALGORITHM_SUITE.getDataKeyLength())); assertThrows( CannotUnwrapDataKeyException.class, () -> kmsMasterKey.decryptDataKey( ALGORITHM_SUITE, Collections.singletonList(edk), ENCRYPTION_CONTEXT)); } @Test public void testDecryptSkipsMismatchedIdEDK() { AWSKMS client = spy(new MockKMSClient()); Supplier supplier = mock(Supplier.class); when(supplier.get()).thenReturn(client); MasterKeyProvider mkp = mock(MasterKeyProvider.class); when(mkp.getDefaultProviderId()).thenReturn(AWS_KMS_PROVIDER_ID); String keyId = client.createKey().getKeyMetadata().getArn(); KmsMasterKey kmsMasterKey = KmsMasterKey.getInstance(supplier, keyId, mkp); // Mock expected KMS response to verify success if second EDK is ok, // and the mismatched EDK is skipped vs failing outright DecryptResult kmsResponse = new DecryptResult(); kmsResponse.setKeyId(keyId); kmsResponse.setPlaintext(ByteBuffer.allocate(ALGORITHM_SUITE.getDataKeyLength())); doReturn(kmsResponse).when(client).decrypt(isA(DecryptRequest.class)); EncryptedDataKey edk = new KeyBlob( AWS_KMS_PROVIDER_ID, keyId.getBytes(StandardCharsets.UTF_8), generate(ALGORITHM_SUITE.getDataKeyLength())); EncryptedDataKey mismatchedEDK = new KeyBlob( AWS_KMS_PROVIDER_ID, "mismatchedID".getBytes(StandardCharsets.UTF_8), generate(ALGORITHM_SUITE.getDataKeyLength())); DataKey<KmsMasterKey> decryptDataKeyResult = kmsMasterKey.decryptDataKey( ALGORITHM_SUITE, Arrays.asList(mismatchedEDK, edk), ENCRYPTION_CONTEXT); ArgumentCaptor<DecryptRequest> decrypt = ArgumentCaptor.forClass(DecryptRequest.class); verify(client, times(1)).decrypt(decrypt.capture()); DecryptRequest actualDecryptRequest = decrypt.getValue(); assertArrayEquals( edk.getProviderInformation(), actualDecryptRequest.getKeyId().getBytes(StandardCharsets.UTF_8)); } private void assertUserAgent(AmazonWebServiceRequest request) { assertTrue( request .getRequestClientOptions() .getClientMarker(RequestClientOptions.Marker.USER_AGENT) .contains(VersionInfo.loadUserAgent())); } }
729
0
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk/kms/KmsMasterKeyProviderTest.java
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package com.amazonaws.encryptionsdk.kms; import static com.amazonaws.encryptionsdk.TestUtils.assertThrows; import static com.amazonaws.encryptionsdk.internal.RandomBytesGenerator.generate; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.isA; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; import com.amazonaws.AmazonServiceException; import com.amazonaws.AmazonWebServiceRequest; import com.amazonaws.RequestClientOptions; import com.amazonaws.auth.AWSCredentials; import com.amazonaws.auth.AWSStaticCredentialsProvider; import com.amazonaws.encryptionsdk.CryptoAlgorithm; import com.amazonaws.encryptionsdk.DataKey; import com.amazonaws.encryptionsdk.EncryptedDataKey; import com.amazonaws.encryptionsdk.MasterKeyProvider; import com.amazonaws.encryptionsdk.MasterKeyRequest; import com.amazonaws.encryptionsdk.exception.CannotUnwrapDataKeyException; import com.amazonaws.encryptionsdk.internal.VersionInfo; import com.amazonaws.encryptionsdk.kms.KmsMasterKeyProvider.Builder; import com.amazonaws.encryptionsdk.kms.KmsMasterKeyProvider.RegionalClientSupplier; import com.amazonaws.encryptionsdk.model.KeyBlob; import com.amazonaws.services.kms.model.DecryptRequest; import com.amazonaws.services.kms.model.DecryptResult; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Map; import org.junit.Test; import org.junit.experimental.runners.Enclosed; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.mockito.ArgumentCaptor; @RunWith(Enclosed.class) public class KmsMasterKeyProviderTest { private static final String AWS_PARTITION = "aws"; private static final String AWS_KMS_PROVIDER_ID = "aws-kms"; private static final String OTHER_PARTITION = "not-aws"; private static final String OTHER_PROVIDER_ID = "not-aws-kms"; private static final String ACCOUNT_ID = "999999999999"; private static final String OTHER_ACCOUNT_ID = "000000000000"; private static final String KEY_ID_1 = "arn:" + AWS_PARTITION + ":kms:us-east-1:" + ACCOUNT_ID + ":key/01234567-89ab-cdef-fedc-ba9876543210"; private static final String KEY_ID_2 = "arn:" + AWS_PARTITION + ":kms:us-east-1:" + ACCOUNT_ID + ":key/01234567-89ab-cdef-fedc-ba9876543211"; private static final String KEY_ID_3 = "arn:" + AWS_PARTITION + ":kms:us-east-1:" + ACCOUNT_ID + ":key/01234567-89ab-cdef-fedc-ba9876543212"; private static final String KEY_ID_4 = "arn:" + AWS_PARTITION + ":kms:us-east-1:" + OTHER_ACCOUNT_ID + ":key/01234567-89ab-cdef-fedc-ba9876543210"; private static final String KEY_ID_5 = "arn:" + OTHER_PARTITION + ":kms:us-east-1:" + ACCOUNT_ID + ":key/01234567-89ab-cdef-fedc-ba9876543210"; private static final CryptoAlgorithm ALGORITHM_SUITE = CryptoAlgorithm.ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA256; private static final Map<String, String> ENCRYPTION_CONTEXT = Collections.singletonMap("myKey", "myValue"); private static final EncryptedDataKey EDK_ID_1 = new KeyBlob( AWS_KMS_PROVIDER_ID, KEY_ID_1.getBytes(StandardCharsets.UTF_8), generate(ALGORITHM_SUITE.getDataKeyLength())); private static final EncryptedDataKey EDK_ID_1_OTHER_CIPHERTEXT = new KeyBlob( AWS_KMS_PROVIDER_ID, KEY_ID_1.getBytes(StandardCharsets.UTF_8), generate(ALGORITHM_SUITE.getDataKeyLength())); private static final EncryptedDataKey EDK_ID_2 = new KeyBlob( AWS_KMS_PROVIDER_ID, KEY_ID_2.getBytes(StandardCharsets.UTF_8), generate(ALGORITHM_SUITE.getDataKeyLength())); private static final EncryptedDataKey EDK_ID_3 = new KeyBlob( AWS_KMS_PROVIDER_ID, KEY_ID_3.getBytes(StandardCharsets.UTF_8), generate(ALGORITHM_SUITE.getDataKeyLength())); private static final EncryptedDataKey EDK_NON_ARN = new KeyBlob( AWS_KMS_PROVIDER_ID, "someAlias".getBytes(StandardCharsets.UTF_8), generate(ALGORITHM_SUITE.getDataKeyLength())); private static final EncryptedDataKey EDK_EMPTY_PROVIDER = new KeyBlob( "", "someId".getBytes(StandardCharsets.UTF_8), generate(ALGORITHM_SUITE.getDataKeyLength())); private static final EncryptedDataKey EDK_OTHER_PROVIDER = new KeyBlob( OTHER_PROVIDER_ID, "someId".getBytes(StandardCharsets.UTF_8), generate(ALGORITHM_SUITE.getDataKeyLength())); private static final EncryptedDataKey EDK_OTHER_ACCOUNT = new KeyBlob( AWS_KMS_PROVIDER_ID, KEY_ID_4.getBytes(StandardCharsets.UTF_8), generate(ALGORITHM_SUITE.getDataKeyLength())); private static final EncryptedDataKey EDK_OTHER_PARTITION = new KeyBlob( AWS_KMS_PROVIDER_ID, KEY_ID_5.getBytes(StandardCharsets.UTF_8), generate(ALGORITHM_SUITE.getDataKeyLength())); @RunWith(Parameterized.class) public static class ParameterizedDecryptTest { MKPTestConfiguration mkpConfig; List<EncryptedDataKey> inputEDKs; List<EncryptedDataKey> decryptableEDKs; private static class MKPTestConfiguration { // instance vars are public for easier access during testing public boolean isDiscovery; public DiscoveryFilter discoveryFilter; public List<String> keyIds; public MKPTestConfiguration( boolean isDiscovery, DiscoveryFilter discoveryFilter, List<String> keyIds) { this.isDiscovery = isDiscovery; this.discoveryFilter = discoveryFilter; this.keyIds = keyIds; } } public ParameterizedDecryptTest( MKPTestConfiguration mkpConfig, List<EncryptedDataKey> inputEDKs, List<EncryptedDataKey> decryptableEDKs) { this.mkpConfig = mkpConfig; this.inputEDKs = inputEDKs; this.decryptableEDKs = decryptableEDKs; } @Parameterized.Parameters(name = "{index}: mkpConfig={0}, inputEDKs={1}, decryptableEDKs={2}") public static Collection<Object[]> testCases() { // Create MKP configuration options to test against MKPTestConfiguration strict_oneCMK = new MKPTestConfiguration(false, null, Arrays.asList(KEY_ID_1)); MKPTestConfiguration strict_twoCMKs = new MKPTestConfiguration(false, null, Arrays.asList(KEY_ID_1, KEY_ID_2)); MKPTestConfiguration explicitDiscovery = new MKPTestConfiguration(true, null, null); MKPTestConfiguration explicitDiscovery_filter = new MKPTestConfiguration( true, new DiscoveryFilter(AWS_PARTITION, Arrays.asList(ACCOUNT_ID)), null); // Define all test cases Collection<Object[]> testCases = Arrays.asList( new Object[][] { // Test cases where no EDKs are expected to be decrypted {strict_oneCMK, Collections.emptyList(), Collections.emptyList()}, {strict_oneCMK, Arrays.asList(EDK_ID_2), Collections.emptyList()}, {strict_oneCMK, Arrays.asList(EDK_ID_2, EDK_ID_3), Collections.emptyList()}, {strict_twoCMKs, Collections.emptyList(), Collections.emptyList()}, {strict_twoCMKs, Arrays.asList(EDK_ID_3), Collections.emptyList()}, { strict_twoCMKs, Arrays.asList(EDK_ID_3, EDK_OTHER_PROVIDER), Collections.emptyList() }, {explicitDiscovery, Collections.emptyList(), Collections.emptyList()}, {explicitDiscovery, Arrays.asList(EDK_OTHER_PROVIDER), Collections.emptyList()}, {explicitDiscovery, Arrays.asList(EDK_EMPTY_PROVIDER), Collections.emptyList()}, { explicitDiscovery, Arrays.asList(EDK_OTHER_PROVIDER, EDK_EMPTY_PROVIDER), Collections.emptyList() }, {explicitDiscovery_filter, Collections.emptyList(), Collections.emptyList()}, { explicitDiscovery_filter, Arrays.asList(EDK_OTHER_PROVIDER), Collections.emptyList() }, { explicitDiscovery_filter, Arrays.asList(EDK_EMPTY_PROVIDER), Collections.emptyList() }, {explicitDiscovery_filter, Arrays.asList(EDK_NON_ARN), Collections.emptyList()}, { explicitDiscovery_filter, Arrays.asList(EDK_OTHER_PARTITION), Collections.emptyList() }, { explicitDiscovery_filter, Arrays.asList(EDK_OTHER_ACCOUNT), Collections.emptyList() }, { explicitDiscovery_filter, Arrays.asList(EDK_OTHER_PROVIDER, EDK_EMPTY_PROVIDER), Collections.emptyList() }, // Test cases where one EDK is expected to be decryptable {strict_oneCMK, Arrays.asList(EDK_ID_1), Arrays.asList(EDK_ID_1)}, {strict_oneCMK, Arrays.asList(EDK_ID_2, EDK_ID_1), Arrays.asList(EDK_ID_1)}, {strict_oneCMK, Arrays.asList(EDK_ID_1, EDK_ID_2), Arrays.asList(EDK_ID_1)}, {strict_twoCMKs, Arrays.asList(EDK_ID_1), Arrays.asList(EDK_ID_1)}, {strict_twoCMKs, Arrays.asList(EDK_ID_2), Arrays.asList(EDK_ID_2)}, {strict_twoCMKs, Arrays.asList(EDK_ID_3, EDK_ID_1), Arrays.asList(EDK_ID_1)}, {strict_twoCMKs, Arrays.asList(EDK_ID_1, EDK_ID_3), Arrays.asList(EDK_ID_1)}, {explicitDiscovery, Arrays.asList(EDK_ID_1), Arrays.asList(EDK_ID_1)}, { explicitDiscovery, Arrays.asList(EDK_OTHER_PROVIDER, EDK_ID_1), Arrays.asList(EDK_ID_1) }, { explicitDiscovery, Arrays.asList(EDK_ID_1, EDK_OTHER_PROVIDER), Arrays.asList(EDK_ID_1) }, {explicitDiscovery_filter, Arrays.asList(EDK_ID_1), Arrays.asList(EDK_ID_1)}, { explicitDiscovery_filter, Arrays.asList(EDK_OTHER_ACCOUNT, EDK_ID_1), Arrays.asList(EDK_ID_1) }, { explicitDiscovery_filter, Arrays.asList(EDK_ID_1, EDK_OTHER_ACCOUNT), Arrays.asList(EDK_ID_1) }, // Test cases where multiple EDKs are expected to be decryptable { strict_oneCMK, Arrays.asList(EDK_ID_1, EDK_ID_1_OTHER_CIPHERTEXT), Arrays.asList(EDK_ID_1, EDK_ID_1_OTHER_CIPHERTEXT) }, { strict_twoCMKs, Arrays.asList(EDK_ID_1, EDK_ID_2), Arrays.asList(EDK_ID_1, EDK_ID_2) }, { explicitDiscovery, Arrays.asList(EDK_ID_1, EDK_ID_2), Arrays.asList(EDK_ID_1, EDK_ID_2) }, { explicitDiscovery_filter, Arrays.asList(EDK_ID_1, EDK_ID_2), Arrays.asList(EDK_ID_1, EDK_ID_2) }, }); return testCases; } @SuppressWarnings("deprecation") private KmsMasterKeyProvider constructMKPForTest( MKPTestConfiguration mkpConfig, RegionalClientSupplier supplier) { Builder builder = KmsMasterKeyProvider.builder().withCustomClientFactory(supplier); KmsMasterKeyProvider mkp; if (mkpConfig.isDiscovery && mkpConfig.discoveryFilter == null) { mkp = builder.buildDiscovery(); } else if (mkpConfig.isDiscovery) { mkp = builder.buildDiscovery(mkpConfig.discoveryFilter); } else { mkp = builder.buildStrict(mkpConfig.keyIds); } return mkp; } @Test public void testDecrypt() throws Exception { MockKMSClient client = spy(new MockKMSClient()); RegionalClientSupplier supplier = mock(RegionalClientSupplier.class); when(supplier.getClient(any())).thenReturn(client); // create MKP to test KmsMasterKeyProvider mkp = constructMKPForTest(mkpConfig, supplier); // if we expect none of them to decrypt, just test that we get the correct // failure and KMS was not called if (decryptableEDKs.size() <= 0) { assertThrows( CannotUnwrapDataKeyException.class, () -> mkp.decryptDataKey(ALGORITHM_SUITE, inputEDKs, ENCRYPTION_CONTEXT)); ArgumentCaptor<DecryptRequest> decrypt = ArgumentCaptor.forClass(DecryptRequest.class); verifyNoInteractions(client); return; } // Test that the mkp calls KMS for the first expected EDK EncryptedDataKey expectedEDK = decryptableEDKs.get(0); // mock KMS to return the KeyId for the expected EDK, // we verify that we call KMS with this KeyId, so this is ok DecryptResult decryptResult = new DecryptResult(); decryptResult.setKeyId( new String(expectedEDK.getProviderInformation(), StandardCharsets.UTF_8)); decryptResult.setPlaintext(ByteBuffer.allocate(ALGORITHM_SUITE.getDataKeyLength())); doReturn(decryptResult).when(client).decrypt(isA(DecryptRequest.class)); DataKey<KmsMasterKey> dataKeyResult = mkp.decryptDataKey(ALGORITHM_SUITE, inputEDKs, ENCRYPTION_CONTEXT); ArgumentCaptor<DecryptRequest> decrypt = ArgumentCaptor.forClass(DecryptRequest.class); verify(client, times(1)).decrypt(decrypt.capture()); verifyNoMoreInteractions(client); DecryptRequest actualRequest = decrypt.getValue(); assertArrayEquals( expectedEDK.getProviderInformation(), actualRequest.getKeyId().getBytes(StandardCharsets.UTF_8)); assertEquals(ENCRYPTION_CONTEXT, actualRequest.getEncryptionContext()); assertArrayEquals( expectedEDK.getEncryptedDataKey(), actualRequest.getCiphertextBlob().array()); assertUserAgent(actualRequest); assertArrayEquals( expectedEDK.getProviderInformation(), dataKeyResult.getProviderInformation()); assertArrayEquals(expectedEDK.getEncryptedDataKey(), dataKeyResult.getEncryptedDataKey()); } @Test public void testDecryptKMSFailsOnce() throws Exception { MockKMSClient client = spy(new MockKMSClient()); RegionalClientSupplier supplier = mock(RegionalClientSupplier.class); when(supplier.getClient(any())).thenReturn(client); // create MKP to test KmsMasterKeyProvider mkp = constructMKPForTest(mkpConfig, supplier); // if we expect one or less KMS call, just test that we get the correct // failure and KMS was called the expected number of times if (decryptableEDKs.size() <= 1) { // Mock KMS to fail doThrow(new AmazonServiceException("fail")).when(client).decrypt(isA(DecryptRequest.class)); assertThrows( CannotUnwrapDataKeyException.class, () -> mkp.decryptDataKey(ALGORITHM_SUITE, inputEDKs, ENCRYPTION_CONTEXT)); ArgumentCaptor<DecryptRequest> decrypt = ArgumentCaptor.forClass(DecryptRequest.class); verify(client, times(decryptableEDKs.size())).decrypt(decrypt.capture()); return; } EncryptedDataKey expectedFailedEDK = decryptableEDKs.get(0); EncryptedDataKey expectedSuccessfulEDK = decryptableEDKs.get(1); // Mock KMS to fail the first call then succeed for the second call DecryptResult decryptResult = new DecryptResult(); decryptResult.setKeyId( new String(expectedSuccessfulEDK.getProviderInformation(), StandardCharsets.UTF_8)); decryptResult.setPlaintext(ByteBuffer.allocate(ALGORITHM_SUITE.getDataKeyLength())); doThrow(new AmazonServiceException("fail")) .doReturn(decryptResult) .when(client) .decrypt(isA(DecryptRequest.class)); DataKey<KmsMasterKey> dataKeyResult = mkp.decryptDataKey(ALGORITHM_SUITE, inputEDKs, ENCRYPTION_CONTEXT); ArgumentCaptor<DecryptRequest> decrypt = ArgumentCaptor.forClass(DecryptRequest.class); verify(client, times(2)).decrypt(decrypt.capture()); verifyNoMoreInteractions(client); List<DecryptRequest> actualRequests = decrypt.getAllValues(); DecryptRequest failedRequest = actualRequests.get(0); assertArrayEquals( expectedFailedEDK.getProviderInformation(), failedRequest.getKeyId().getBytes(StandardCharsets.UTF_8)); assertEquals(ENCRYPTION_CONTEXT, failedRequest.getEncryptionContext()); assertArrayEquals( expectedFailedEDK.getEncryptedDataKey(), failedRequest.getCiphertextBlob().array()); assertUserAgent(failedRequest); DecryptRequest successfulRequest = actualRequests.get(1); assertArrayEquals( expectedSuccessfulEDK.getProviderInformation(), successfulRequest.getKeyId().getBytes(StandardCharsets.UTF_8)); assertEquals(ENCRYPTION_CONTEXT, successfulRequest.getEncryptionContext()); assertArrayEquals( expectedSuccessfulEDK.getEncryptedDataKey(), successfulRequest.getCiphertextBlob().array()); assertUserAgent(successfulRequest); assertArrayEquals( expectedSuccessfulEDK.getProviderInformation(), dataKeyResult.getProviderInformation()); assertArrayEquals( expectedSuccessfulEDK.getEncryptedDataKey(), dataKeyResult.getEncryptedDataKey()); } private void assertUserAgent(AmazonWebServiceRequest request) { assertTrue( request .getRequestClientOptions() .getClientMarker(RequestClientOptions.Marker.USER_AGENT) .contains(VersionInfo.loadUserAgent())); } } public static class NonParameterized { @Test public void testBuildStrictWithNoCMKs() throws Exception { RegionalClientSupplier supplier = mock(RegionalClientSupplier.class); assertThrows( IllegalArgumentException.class, () -> KmsMasterKeyProvider.builder().withCustomClientFactory(supplier).buildStrict()); assertThrows( IllegalArgumentException.class, () -> KmsMasterKeyProvider.builder() .withCustomClientFactory(supplier) .buildStrict(Collections.emptyList())); assertThrows( IllegalArgumentException.class, () -> KmsMasterKeyProvider.builder() .withCustomClientFactory(supplier) .buildStrict((List) null)); } @Test public void testBuildStrictWithNullCMK() throws Exception { RegionalClientSupplier supplier = mock(RegionalClientSupplier.class); assertThrows( IllegalArgumentException.class, () -> KmsMasterKeyProvider.builder() .withCustomClientFactory(supplier) .buildStrict((String) null)); assertThrows( IllegalArgumentException.class, () -> KmsMasterKeyProvider.builder() .withCustomClientFactory(supplier) .buildStrict(Arrays.asList((String) null))); } @Test public void testBuildDiscoveryWithFilter() throws Exception { RegionalClientSupplier supplier = mock(RegionalClientSupplier.class); KmsMasterKeyProvider mkp1 = KmsMasterKeyProvider.builder() .withCustomClientFactory(supplier) .buildDiscovery(new DiscoveryFilter("aws", Arrays.asList("accountId"))); assertNotNull(mkp1); } @Test public void testBuildDiscoveryWithNullFilter() throws Exception { RegionalClientSupplier supplier = mock(RegionalClientSupplier.class); assertThrows( IllegalArgumentException.class, () -> KmsMasterKeyProvider.builder() .withCustomClientFactory(supplier) .buildDiscovery(null)); } @Test public void testDecryptMismatchedKMSKeyIdResponse() throws Exception { MockKMSClient client = spy(new MockKMSClient()); RegionalClientSupplier supplier = mock(RegionalClientSupplier.class); when(supplier.getClient(any())).thenReturn(client); DecryptResult badResult = new DecryptResult(); badResult.setKeyId(KEY_ID_2); badResult.setPlaintext(ByteBuffer.allocate(ALGORITHM_SUITE.getDataKeyLength())); doReturn(badResult).when(client).decrypt(isA(DecryptRequest.class)); KmsMasterKeyProvider mkp = KmsMasterKeyProvider.builder().withCustomClientFactory(supplier).buildDiscovery(); assertThrows( CannotUnwrapDataKeyException.class, () -> mkp.decryptDataKey(ALGORITHM_SUITE, Arrays.asList(EDK_ID_1), ENCRYPTION_CONTEXT)); } } @Test public void testExplicitCredentials() throws Exception { AWSCredentials creds = new AWSCredentials() { @Override public String getAWSAccessKeyId() { throw new UsedExplicitCredentials(); } @Override public String getAWSSecretKey() { throw new UsedExplicitCredentials(); } }; MasterKeyProvider<KmsMasterKey> mkp = KmsMasterKeyProvider.builder() .withCredentials(creds) .buildStrict("arn:aws:kms:us-east-1:012345678901:key/foo-bar"); assertExplicitCredentialsUsed(mkp); mkp = KmsMasterKeyProvider.builder() .withCredentials(new AWSStaticCredentialsProvider(creds)) .buildStrict("arn:aws:kms:us-east-1:012345678901:key/foo-bar"); assertExplicitCredentialsUsed(mkp); } private void assertExplicitCredentialsUsed(final MasterKeyProvider<KmsMasterKey> mkp) { try { MasterKeyRequest mkr = MasterKeyRequest.newBuilder() .setEncryptionContext(Collections.emptyMap()) .setStreaming(true) .build(); mkp.getMasterKeysForEncryption(mkr) .forEach(mk -> mk.generateDataKey(ALGORITHM_SUITE, Collections.emptyMap())); fail("Expected exception"); } catch (UsedExplicitCredentials e) { // ok } } private static class UsedExplicitCredentials extends RuntimeException {} }
730
0
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk/jce/JceMasterKeyTest.java
package com.amazonaws.encryptionsdk.jce; import java.security.*; import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec; import org.junit.Test; public class JceMasterKeyTest { private static final SecretKey SECRET_KEY = new SecretKeySpec(new byte[1], "AES"); private static final PrivateKey PRIVATE_KEY; private static final PublicKey PUBLIC_KEY; static { try { KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA"); KeyPair keyPair = keyPairGenerator.generateKeyPair(); PUBLIC_KEY = keyPair.getPublic(); PRIVATE_KEY = keyPair.getPrivate(); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } } private JceMasterKey jceGetInstance(final String algorithmName) { return JceMasterKey.getInstance(SECRET_KEY, "mockProvider", "mockKey", algorithmName); } private JceMasterKey jceGetInstanceAsymmetric(final String algorithmName) { return JceMasterKey.getInstance( PUBLIC_KEY, PRIVATE_KEY, "mockProvider", "mockKey", algorithmName); } @Test(expected = IllegalArgumentException.class) public void testGetInstanceInvalidWrappingAlgorithm() { jceGetInstance("blatently/unsupported/algorithm"); } @Test(expected = UnsupportedOperationException.class) public void testGetInstanceAsymmetricInvalidWrappingAlgorithm() { jceGetInstanceAsymmetric("rsa/ec/unsupportedAlgorithm"); } /** * Calls JceMasterKey.getInstance with differently cased wrappingAlgorithm names. Passes if no * Exception is thrown. Relies on passing an invalid algorithm name to result in an Exception. */ @Test public void testGetInstanceAllLowercase() { jceGetInstance("aes/gcm/nopadding"); } @Test public void testGetInstanceMixedCasing() { jceGetInstance("AES/GCm/NOpadding"); } @Test public void testGetInstanceAsymmetricAllLowercase() { jceGetInstanceAsymmetric("rsa/ecb/oaepwithsha-256andmgf1padding"); } @Test public void testGetInstanceAsymmetricMixedCasing() { jceGetInstanceAsymmetric("RSA/ECB/OAepwithsha-256andmgf1padding"); } }
731
0
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk/jce/KeyStoreProviderTest.java
/* * Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except * in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.amazonaws.encryptionsdk.jce; import static com.amazonaws.encryptionsdk.internal.RandomBytesGenerator.generate; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import com.amazonaws.encryptionsdk.AwsCrypto; import com.amazonaws.encryptionsdk.CryptoResult; import com.amazonaws.encryptionsdk.MasterKeyProvider; import com.amazonaws.encryptionsdk.exception.CannotUnwrapDataKeyException; import com.amazonaws.encryptionsdk.multi.MultipleProviderFactory; import java.io.IOException; import java.math.BigInteger; import java.security.GeneralSecurityException; import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.KeyStore; import java.security.KeyStore.PasswordProtection; import java.security.KeyStoreException; import java.security.SecureRandom; import java.security.cert.Certificate; import java.security.cert.X509Certificate; import java.time.Instant; import java.time.temporal.ChronoUnit; import java.util.Date; import javax.crypto.spec.SecretKeySpec; import org.junit.Before; import org.junit.Test; import sun.security.x509.AlgorithmId; import sun.security.x509.CertificateAlgorithmId; import sun.security.x509.CertificateSerialNumber; import sun.security.x509.CertificateValidity; import sun.security.x509.CertificateX509Key; import sun.security.x509.X500Name; import sun.security.x509.X509CertImpl; import sun.security.x509.X509CertInfo; /* These internal sun classes are included solely for test purposes as this test cannot use BouncyCastle cert generation, as there are incompatibilities between how standard BC and FIPS BC perform cert generation. */ public class KeyStoreProviderTest { private static final SecureRandom RND = new SecureRandom(); private static final KeyPairGenerator KG; private static final byte[] PLAINTEXT = generate(1024); private static final char[] PASSWORD = "Password".toCharArray(); private static final KeyStore.PasswordProtection PP = new PasswordProtection(PASSWORD); private KeyStore ks; static { try { KG = KeyPairGenerator.getInstance("RSA"); KG.initialize(2048); } catch (Exception ex) { throw new RuntimeException(ex); } } @Before public void setup() throws Exception { ks = KeyStore.getInstance(KeyStore.getDefaultType()); ks.load(null, PASSWORD); } @Test public void singleKeyPkcs1() throws Exception { addEntry("key1"); final KeyStoreProvider mkp = new KeyStoreProvider(ks, PP, "KeyStore", "RSA/ECB/PKCS1Padding", "key1"); final JceMasterKey mk1 = mkp.getMasterKey("key1"); final AwsCrypto crypto = AwsCrypto.standard(); final CryptoResult<byte[], JceMasterKey> ct = crypto.encryptData(mkp, PLAINTEXT); assertEquals(1, ct.getMasterKeyIds().size()); final CryptoResult<byte[], JceMasterKey> result = crypto.decryptData(mkp, ct.getResult()); assertArrayEquals(PLAINTEXT, result.getResult()); // Only the first found key should be used assertEquals(1, result.getMasterKeys().size()); assertEquals(mk1, result.getMasterKeys().get(0)); } @Test public void singleKeyOaepSha1() throws Exception { addEntry("key1"); final KeyStoreProvider mkp = new KeyStoreProvider(ks, PP, "KeyStore", "RSA/ECB/OAEPWithSHA-1AndMGF1Padding", "key1"); final JceMasterKey mk1 = mkp.getMasterKey("key1"); final AwsCrypto crypto = AwsCrypto.standard(); final CryptoResult<byte[], JceMasterKey> ct = crypto.encryptData(mkp, PLAINTEXT); assertEquals(1, ct.getMasterKeyIds().size()); final CryptoResult<byte[], JceMasterKey> result = crypto.decryptData(mkp, ct.getResult()); assertArrayEquals(PLAINTEXT, result.getResult()); // Only the first found key should be used assertEquals(1, result.getMasterKeys().size()); assertEquals(mk1, result.getMasterKeys().get(0)); } @Test public void singleKeyOaepSha256() throws Exception { addEntry("key1"); final KeyStoreProvider mkp = new KeyStoreProvider(ks, PP, "KeyStore", "RSA/ECB/OAEPWithSHA-256AndMGF1Padding", "key1"); final JceMasterKey mk1 = mkp.getMasterKey("key1"); final AwsCrypto crypto = AwsCrypto.standard(); final CryptoResult<byte[], JceMasterKey> ct = crypto.encryptData(mkp, PLAINTEXT); assertEquals(1, ct.getMasterKeyIds().size()); final CryptoResult<byte[], JceMasterKey> result = crypto.decryptData(mkp, ct.getResult()); assertArrayEquals(PLAINTEXT, result.getResult()); // Only the first found key should be used assertEquals(1, result.getMasterKeys().size()); assertEquals(mk1, result.getMasterKeys().get(0)); } @Test public void multipleKeys() throws Exception { addEntry("key1"); addEntry("key2"); final KeyStoreProvider mkp = new KeyStoreProvider( ks, PP, "KeyStore", "RSA/ECB/OAEPWithSHA-256AndMGF1Padding", "key1", "key2"); @SuppressWarnings("unused") final JceMasterKey mk1 = mkp.getMasterKey("key1"); final JceMasterKey mk2 = mkp.getMasterKey("key2"); final AwsCrypto crypto = AwsCrypto.standard(); final CryptoResult<byte[], JceMasterKey> ct = crypto.encryptData(mkp, PLAINTEXT); assertEquals(2, ct.getMasterKeyIds().size()); CryptoResult<byte[], JceMasterKey> result = crypto.decryptData(mkp, ct.getResult()); assertArrayEquals(PLAINTEXT, result.getResult()); // Order is non-deterministic assertEquals(1, result.getMasterKeys().size()); // Delete the first key and see if it works ks.deleteEntry("key1"); result = crypto.decryptData(mkp, ct.getResult()); assertArrayEquals(PLAINTEXT, result.getResult()); // Only the first found key should be used assertEquals(1, result.getMasterKeys().size()); assertEquals(mk2, result.getMasterKeys().get(0)); } @Test(expected = CannotUnwrapDataKeyException.class) public void encryptOnly() throws Exception { addPublicEntry("key1"); final KeyStoreProvider mkp = new KeyStoreProvider(ks, PP, "KeyStore", "RSA/ECB/OAEPWithSHA-256AndMGF1Padding", "key1"); final AwsCrypto crypto = AwsCrypto.standard(); final CryptoResult<byte[], JceMasterKey> ct = crypto.encryptData(mkp, PLAINTEXT); assertEquals(1, ct.getMasterKeyIds().size()); crypto.decryptData(mkp, ct.getResult()); } @Test public void escrowAndSymmetric() throws Exception { addPublicEntry("key1"); addEntry("key2"); final KeyStoreProvider mkp = new KeyStoreProvider( ks, PP, "KeyStore", "RSA/ECB/OAEPWithSHA-256AndMGF1Padding", "key1", "key2"); @SuppressWarnings("unused") final JceMasterKey mk1 = mkp.getMasterKey("key1"); final JceMasterKey mk2 = mkp.getMasterKey("key2"); final AwsCrypto crypto = AwsCrypto.standard(); final CryptoResult<byte[], JceMasterKey> ct = crypto.encryptData(mkp, PLAINTEXT); assertEquals(2, ct.getMasterKeyIds().size()); CryptoResult<byte[], JceMasterKey> result = crypto.decryptData(mkp, ct.getResult()); assertArrayEquals(PLAINTEXT, result.getResult()); // Only could have decrypted with the keypair assertEquals(1, result.getMasterKeys().size()); assertEquals(mk2, result.getMasterKeys().get(0)); // Delete the first key and see if it works ks.deleteEntry("key1"); result = crypto.decryptData(mkp, ct.getResult()); assertArrayEquals(PLAINTEXT, result.getResult()); // Only the first found key should be used assertEquals(1, result.getMasterKeys().size()); assertEquals(mk2, result.getMasterKeys().get(0)); } @Test public void escrowAndSymmetricSecondProvider() throws GeneralSecurityException, IOException { addPublicEntry("key1"); addEntry("key2"); final KeyStoreProvider mkp = new KeyStoreProvider( ks, PP, "KeyStore", "RSA/ECB/OAEPWithSHA-256AndMGF1Padding", "key1", "key2"); @SuppressWarnings("unused") final JceMasterKey mk1 = mkp.getMasterKey("key1"); final JceMasterKey mk2 = mkp.getMasterKey("key2"); final AwsCrypto crypto = AwsCrypto.standard(); final CryptoResult<byte[], JceMasterKey> ct = crypto.encryptData(mkp, PLAINTEXT); assertEquals(2, ct.getMasterKeyIds().size()); final KeyStoreProvider mkp2 = new KeyStoreProvider(ks, PP, "KeyStore", "RSA/ECB/OAEPWithSHA-256AndMGF1Padding", "key1"); CryptoResult<byte[], JceMasterKey> result = crypto.decryptData(mkp2, ct.getResult()); assertArrayEquals(PLAINTEXT, result.getResult()); // Only could have decrypted with the keypair assertEquals(1, result.getMasterKeys().size()); assertEquals(mk2, result.getMasterKeys().get(0)); } @Test public void escrowCase() throws GeneralSecurityException, IOException { addEntry("escrowKey"); KeyStore ks2 = KeyStore.getInstance(KeyStore.getDefaultType()); ks2.load(null, PASSWORD); copyPublicPart(ks, ks2, "escrowKey"); final KeyStoreProvider mkp = new KeyStoreProvider( ks, PP, "KeyStore", "RSA/ECB/OAEPWithSHA-256AndMGF1Padding", "escrowKey"); final KeyStoreProvider escrowProvider = new KeyStoreProvider( ks2, PP, "KeyStore", "RSA/ECB/OAEPWithSHA-256AndMGF1Padding", "escrowKey"); final JceMasterKey mk1 = escrowProvider.getMasterKey("escrowKey"); final AwsCrypto crypto = AwsCrypto.standard(); final CryptoResult<byte[], JceMasterKey> ct = crypto.encryptData(escrowProvider, PLAINTEXT); assertEquals(1, ct.getMasterKeyIds().size()); try { crypto.decryptData(escrowProvider, ct.getResult()); fail("Expected CannotUnwrapDataKeyException"); } catch (final CannotUnwrapDataKeyException ex) { // expected } CryptoResult<byte[], JceMasterKey> result = crypto.decryptData(mkp, ct.getResult()); assertArrayEquals(PLAINTEXT, result.getResult()); // Only could have decrypted with the keypair assertEquals(1, result.getMasterKeys().size()); assertEquals(mk1, result.getMasterKeys().get(0)); } @Test public void keystoreAndRawProvider() throws GeneralSecurityException, IOException { addEntry("key1"); final SecretKeySpec k1 = new SecretKeySpec(generate(32), "AES"); final JceMasterKey jcep = JceMasterKey.getInstance(k1, "jce", "1", "AES/GCM/NoPadding"); final KeyStoreProvider ksp = new KeyStoreProvider(ks, PP, "KeyStore", "RSA/ECB/OAEPWithSHA-256AndMGF1Padding", "key1"); MasterKeyProvider<JceMasterKey> multiProvider = MultipleProviderFactory.buildMultiProvider(JceMasterKey.class, jcep, ksp); assertEquals(jcep, multiProvider.getMasterKey("jce", "1")); final AwsCrypto crypto = AwsCrypto.standard(); final CryptoResult<byte[], JceMasterKey> ct = crypto.encryptData(multiProvider, PLAINTEXT); assertEquals(2, ct.getMasterKeyIds().size()); CryptoResult<byte[], JceMasterKey> result = crypto.decryptData(multiProvider, ct.getResult()); assertArrayEquals(PLAINTEXT, result.getResult()); assertEquals(jcep, result.getMasterKeys().get(0)); // Decrypt just using each individually assertArrayEquals(PLAINTEXT, crypto.decryptData(jcep, ct.getResult()).getResult()); assertArrayEquals(PLAINTEXT, crypto.decryptData(ksp, ct.getResult()).getResult()); } private void addEntry(final String alias) throws GeneralSecurityException, IOException { final KeyPair pair = KG.generateKeyPair(); ks.setEntry( alias, new KeyStore.PrivateKeyEntry( pair.getPrivate(), new X509Certificate[] {generateCertificate(pair, alias)}), PP); } private void addPublicEntry(final String alias) throws GeneralSecurityException, IOException { final KeyPair pair = KG.generateKeyPair(); ks.setEntry( alias, new KeyStore.TrustedCertificateEntry(generateCertificate(pair, alias)), null); } private X509Certificate generateCertificate(final KeyPair pair, final String alias) throws GeneralSecurityException, IOException { final X509CertInfo info = new X509CertInfo(); final X500Name name = new X500Name("dc=" + alias); info.set(X509CertInfo.SERIAL_NUMBER, new CertificateSerialNumber(new BigInteger(256, RND))); info.set(X509CertInfo.SUBJECT, name); info.set(X509CertInfo.ISSUER, name); info.set( X509CertInfo.VALIDITY, new CertificateValidity( Date.from(Instant.now().minus(1, ChronoUnit.DAYS)), Date.from(Instant.now().plus(730, ChronoUnit.DAYS)))); info.set(X509CertInfo.KEY, new CertificateX509Key(pair.getPublic())); info.set( X509CertInfo.ALGORITHM_ID, new CertificateAlgorithmId(new AlgorithmId(AlgorithmId.sha256WithRSAEncryption_oid))); final X509CertImpl cert = new X509CertImpl(info); cert.sign(pair.getPrivate(), AlgorithmId.sha256WithRSAEncryption_oid.toString()); return cert; } private void copyPublicPart(final KeyStore src, final KeyStore dst, final String alias) throws KeyStoreException { Certificate cert = src.getCertificate(alias); dst.setCertificateEntry(alias, cert); } }
732
0
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk/kmssdkv2/MockKmsClient.java
/* * Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except * in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.amazonaws.encryptionsdk.kmssdkv2; import java.nio.ByteBuffer; import java.security.SecureRandom; import java.time.Instant; import java.util.*; import software.amazon.awssdk.core.SdkBytes; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.kms.KmsClient; import software.amazon.awssdk.services.kms.model.*; import software.amazon.awssdk.services.kms.model.UnsupportedOperationException; public class MockKmsClient implements KmsClient { private static final SecureRandom rnd = new SecureRandom(); private static final String ACCOUNT_ID = "01234567890"; private final Map<DecryptMapKey, DecryptResponse> responses_ = new HashMap<>(); private final Set<String> activeKeys = new HashSet<>(); private final Map<String, String> keyAliases = new HashMap<>(); private Region region_ = Region.US_WEST_2; @Override public final String serviceName() { return SERVICE_NAME; } @Override public void close() {} @Override public CreateAliasResponse createAlias(CreateAliasRequest req) { assertExists(req.targetKeyId()); keyAliases.put("alias/" + req.aliasName(), keyAliases.get(req.targetKeyId())); return CreateAliasResponse.builder().build(); } @Override public CreateKeyResponse createKey() { return createKey(CreateKeyRequest.builder().build()); } @Override public CreateKeyResponse createKey(CreateKeyRequest req) { String keyId = UUID.randomUUID().toString(); String arn = "arn:aws:kms:" + region_.id() + ":" + ACCOUNT_ID + ":key/" + keyId; activeKeys.add(arn); keyAliases.put(keyId, arn); keyAliases.put(arn, arn); return CreateKeyResponse.builder() .keyMetadata( KeyMetadata.builder() .awsAccountId(ACCOUNT_ID) .creationDate(Instant.now()) .description(req.description()) .enabled(true) .keyId(keyId) .keyUsage(KeyUsageType.ENCRYPT_DECRYPT) .arn(arn) .build()) .build(); } @Override public DecryptResponse decrypt(DecryptRequest req) { DecryptResponse response = responses_.get(new DecryptMapKey(req)); if (response != null) { // Copy it to avoid external modification return DecryptResponse.builder() .keyId(retrieveArn(response.keyId())) .plaintext(SdkBytes.fromByteArray(response.plaintext().asByteArray())) .build(); } else { throw InvalidCiphertextException.builder().message("Invalid Ciphertext").build(); } } @Override public DescribeKeyResponse describeKey(DescribeKeyRequest req) { final String arn = retrieveArn(req.keyId()); return DescribeKeyResponse.builder() .keyMetadata(KeyMetadata.builder().arn(arn).keyId(arn).build()) .build(); } @Override public EncryptResponse encrypt(EncryptRequest req) { // We internally delegate to encrypt, so as to avoid mockito detecting extra calls to encrypt // when spying on the // MockKMSClient, we put the real logic into a separate function. return encrypt0(req); } private EncryptResponse encrypt0(EncryptRequest req) { String arn = retrieveArn(req.keyId()); final byte[] cipherText = new byte[512]; rnd.nextBytes(cipherText); DecryptResponse dec = DecryptResponse.builder() .keyId(retrieveArn(arn)) .plaintext(SdkBytes.fromByteArray(req.plaintext().asByteArray())) .build(); ByteBuffer ctBuff = ByteBuffer.wrap(cipherText); responses_.put(new DecryptMapKey(ctBuff, req.encryptionContext()), dec); return EncryptResponse.builder() .ciphertextBlob(SdkBytes.fromByteBuffer(ctBuff)) .keyId(arn) .build(); } @Override public GenerateDataKeyResponse generateDataKey(GenerateDataKeyRequest req) { byte[] pt; DataKeySpec keySpec = req.keySpec(); if (keySpec == null) { pt = new byte[req.numberOfBytes()]; } else { switch (keySpec) { case AES_256: pt = new byte[32]; break; case AES_128: pt = new byte[16]; break; default: throw UnsupportedOperationException.builder().build(); } } rnd.nextBytes(pt); String arn = retrieveArn(req.keyId()); EncryptResponse encryptResponse = encrypt0( EncryptRequest.builder() .keyId(arn) .plaintext(SdkBytes.fromByteArray(pt)) .encryptionContext(req.encryptionContext()) .build()); return GenerateDataKeyResponse.builder() .keyId(arn) .ciphertextBlob(encryptResponse.ciphertextBlob()) .plaintext(SdkBytes.fromByteArray(pt)) .build(); } public GenerateDataKeyWithoutPlaintextResponse generateDataKeyWithoutPlaintext( GenerateDataKeyWithoutPlaintextRequest req) { String arn = retrieveArn(req.keyId()); GenerateDataKeyRequest generateDataKeyRequest = GenerateDataKeyRequest.builder() .encryptionContext(req.encryptionContext()) .grantTokens(req.grantTokens()) .keyId(arn) .keySpec(req.keySpec()) .numberOfBytes(req.numberOfBytes()) .build(); GenerateDataKeyResponse generateDataKey = generateDataKey(generateDataKeyRequest); return GenerateDataKeyWithoutPlaintextResponse.builder() .ciphertextBlob(generateDataKey.ciphertextBlob()) .keyId(arn) .build(); } public void setRegion(Region req) { region_ = req; } public void deleteKey(final String keyId) { final String arn = retrieveArn(keyId); activeKeys.remove(arn); } private String retrieveArn(final String keyId) { String arn = keyAliases.get(keyId); assertExists(arn); return arn; } private void assertExists(String keyId) { if (keyAliases.containsKey(keyId)) { keyId = keyAliases.get(keyId); } if (keyId == null || !activeKeys.contains(keyId)) { throw NotFoundException.builder().message("Key doesn't exist: " + keyId).build(); } } private static class DecryptMapKey { private final ByteBuffer cipherText; private final Map<String, String> ec; public DecryptMapKey(DecryptRequest req) { cipherText = req.ciphertextBlob().asByteBuffer(); if (req.encryptionContext() != null) { ec = Collections.unmodifiableMap(new HashMap<>(req.encryptionContext())); } else { ec = Collections.emptyMap(); } } public DecryptMapKey(ByteBuffer ctBuff, Map<String, String> ec) { cipherText = ctBuff.asReadOnlyBuffer(); if (ec != null) { this.ec = Collections.unmodifiableMap(new HashMap<>(ec)); } else { this.ec = Collections.emptyMap(); } } public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((cipherText == null) ? 0 : cipherText.hashCode()); result = prime * result + ((ec == null) ? 0 : ec.hashCode()); return result; } public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; DecryptMapKey other = (DecryptMapKey) obj; if (cipherText == null) { if (other.cipherText != null) return false; } else if (!cipherText.equals(other.cipherText)) return false; if (ec == null) { if (other.ec != null) return false; } else if (!ec.equals(other.ec)) return false; return true; } public String toString() { return "DecryptMapKey [cipherText=" + cipherText + ", ec=" + ec + "]"; } } }
733
0
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk/kmssdkv2/KMSProviderBuilderMockTests.java
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package com.amazonaws.encryptionsdk.kmssdkv2; import static com.amazonaws.encryptionsdk.multi.MultipleProviderFactory.buildMultiProvider; import static java.util.Collections.singletonList; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.notNull; import static org.mockito.Mockito.*; import com.amazonaws.encryptionsdk.AwsCrypto; import com.amazonaws.encryptionsdk.MasterKeyProvider; import com.amazonaws.encryptionsdk.internal.VersionInfo; import java.util.Arrays; import java.util.Optional; import org.junit.Test; import org.mockito.ArgumentCaptor; import software.amazon.awssdk.awscore.AwsRequest; import software.amazon.awssdk.awscore.AwsRequestOverrideConfiguration; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.kms.model.CreateAliasRequest; import software.amazon.awssdk.services.kms.model.DecryptRequest; import software.amazon.awssdk.services.kms.model.EncryptRequest; import software.amazon.awssdk.services.kms.model.GenerateDataKeyRequest; public class KMSProviderBuilderMockTests { @Test public void testBareAliasMapping() { MockKmsClient client = spy(new MockKmsClient()); RegionalClientSupplier supplier = mock(RegionalClientSupplier.class); when(supplier.getClient(notNull())).thenReturn(client); String key1 = client.createKey().keyMetadata().keyId(); client.createAlias(CreateAliasRequest.builder().aliasName("foo").targetKeyId(key1).build()); KmsMasterKeyProvider mkp0 = KmsMasterKeyProvider.builder() .customRegionalClientSupplier(supplier) .defaultRegion(Region.US_WEST_2) .buildStrict("alias/foo"); AwsCrypto.standard().encryptData(mkp0, new byte[0]); } @Test public void testGrantTokenPassthrough_usingMKsetCall() throws Exception { MockKmsClient client = spy(new MockKmsClient()); RegionalClientSupplier supplier = mock(RegionalClientSupplier.class); when(supplier.getClient(any())).thenReturn(client); String key1 = client.createKey().keyMetadata().arn(); String key2 = client.createKey().keyMetadata().arn(); KmsMasterKeyProvider mkp0 = KmsMasterKeyProvider.builder() .defaultRegion(Region.US_WEST_2) .customRegionalClientSupplier(supplier) .buildStrict(key1, key2); KmsMasterKey mk1 = mkp0.getMasterKey(key1); KmsMasterKey mk2 = mkp0.getMasterKey(key2); mk1.setGrantTokens(singletonList("foo")); mk2.setGrantTokens(singletonList("foo")); MasterKeyProvider<?> mkp = buildMultiProvider(mk1, mk2); byte[] ciphertext = AwsCrypto.standard().encryptData(mkp, new byte[0]).getResult(); ArgumentCaptor<GenerateDataKeyRequest> gdkr = ArgumentCaptor.forClass(GenerateDataKeyRequest.class); verify(client, times(1)).generateDataKey(gdkr.capture()); assertEquals(key1, gdkr.getValue().keyId()); assertEquals(1, gdkr.getValue().grantTokens().size()); assertEquals("foo", gdkr.getValue().grantTokens().get(0)); ArgumentCaptor<EncryptRequest> er = ArgumentCaptor.forClass(EncryptRequest.class); verify(client, times(1)).encrypt(er.capture()); assertEquals(key2, er.getValue().keyId()); assertEquals(1, er.getValue().grantTokens().size()); assertEquals("foo", er.getValue().grantTokens().get(0)); AwsCrypto.standard().decryptData(mkp, ciphertext); ArgumentCaptor<DecryptRequest> decrypt = ArgumentCaptor.forClass(DecryptRequest.class); verify(client, times(1)).decrypt(decrypt.capture()); assertEquals(1, decrypt.getValue().grantTokens().size()); assertEquals("foo", decrypt.getValue().grantTokens().get(0)); verify(supplier, atLeastOnce()).getClient(Region.US_WEST_2); verifyNoMoreInteractions(supplier); } @Test public void testGrantTokenPassthrough_usingMKPWithers() throws Exception { MockKmsClient client = spy(new MockKmsClient()); RegionalClientSupplier supplier = mock(RegionalClientSupplier.class); when(supplier.getClient(any())).thenReturn(client); String key1 = client.createKey().keyMetadata().arn(); String key2 = client.createKey().keyMetadata().arn(); KmsMasterKeyProvider mkp0 = KmsMasterKeyProvider.builder() .defaultRegion(Region.US_WEST_2) .customRegionalClientSupplier(supplier) .buildStrict(key1, key2); MasterKeyProvider<?> mkp = mkp0.withGrantTokens("foo"); byte[] ciphertext = AwsCrypto.standard().encryptData(mkp, new byte[0]).getResult(); ArgumentCaptor<GenerateDataKeyRequest> gdkr = ArgumentCaptor.forClass(GenerateDataKeyRequest.class); verify(client, times(1)).generateDataKey(gdkr.capture()); assertEquals(key1, gdkr.getValue().keyId()); assertEquals(1, gdkr.getValue().grantTokens().size()); assertEquals("foo", gdkr.getValue().grantTokens().get(0)); ArgumentCaptor<EncryptRequest> er = ArgumentCaptor.forClass(EncryptRequest.class); verify(client, times(1)).encrypt(er.capture()); assertEquals(key2, er.getValue().keyId()); assertEquals(1, er.getValue().grantTokens().size()); assertEquals("foo", er.getValue().grantTokens().get(0)); mkp = mkp0.withGrantTokens(Arrays.asList("bar")); AwsCrypto.standard().decryptData(mkp, ciphertext); ArgumentCaptor<DecryptRequest> decrypt = ArgumentCaptor.forClass(DecryptRequest.class); verify(client, times(1)).decrypt(decrypt.capture()); assertEquals(1, decrypt.getValue().grantTokens().size()); assertEquals("bar", decrypt.getValue().grantTokens().get(0)); verify(supplier, atLeastOnce()).getClient(Region.US_WEST_2); verifyNoMoreInteractions(supplier); } @Test public void testUserAgentPassthrough() throws Exception { MockKmsClient client = spy(new MockKmsClient()); String key1 = client.createKey().keyMetadata().arn(); String key2 = client.createKey().keyMetadata().arn(); KmsMasterKeyProvider mkp = KmsMasterKeyProvider.builder() .customRegionalClientSupplier(ignored -> client) .buildStrict(key1, key2); AwsCrypto.standard() .decryptData(mkp, AwsCrypto.standard().encryptData(mkp, new byte[0]).getResult()); ArgumentCaptor<GenerateDataKeyRequest> gdkr = ArgumentCaptor.forClass(GenerateDataKeyRequest.class); verify(client, times(1)).generateDataKey(gdkr.capture()); assertApiName(gdkr.getValue()); ArgumentCaptor<EncryptRequest> encr = ArgumentCaptor.forClass(EncryptRequest.class); verify(client, times(1)).encrypt(encr.capture()); assertApiName(encr.getValue()); ArgumentCaptor<DecryptRequest> decr = ArgumentCaptor.forClass(DecryptRequest.class); verify(client, times(1)).decrypt(decr.capture()); assertApiName(decr.getValue()); } private void assertApiName(AwsRequest request) { Optional<AwsRequestOverrideConfiguration> overrideConfig = request.overrideConfiguration(); assertTrue(overrideConfig.isPresent()); assertTrue( overrideConfig.get().apiNames().stream() .anyMatch( api -> api.name().equals(VersionInfo.apiName()) && api.version().equals(VersionInfo.versionNumber()))); } }
734
0
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk/kmssdkv2/MaxEncryptedDataKeysIntegrationTest.java
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package com.amazonaws.encryptionsdk.kmssdkv2; import static org.junit.Assert.assertArrayEquals; import static org.mockito.Mockito.*; import com.amazonaws.encryptionsdk.AwsCrypto; import com.amazonaws.encryptionsdk.TestUtils; import com.amazonaws.encryptionsdk.exception.AwsCryptoException; import com.amazonaws.encryptionsdk.kms.KMSTestFixtures; import java.util.ArrayList; import java.util.List; import org.junit.Before; import org.junit.Test; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.kms.KmsClient; import software.amazon.awssdk.services.kms.model.DecryptRequest; public class MaxEncryptedDataKeysIntegrationTest { private static final byte[] PLAINTEXT = {1, 2, 3, 4}; private static final int MAX_EDKS = 3; private KmsClient testClient_; private RegionalClientSupplier testClientSupplier_; private AwsCrypto testCryptoClient_; @Before public void setup() { testClient_ = spy(new ProxyKmsClient(KmsClient.builder().region(Region.US_WEST_2).build())); testClientSupplier_ = region -> { if (region == Region.US_WEST_2) { return testClient_; } throw new AwsCryptoException( "test supplier only configured for us-west-2 and eu-central-1"); }; testCryptoClient_ = AwsCrypto.standard().toBuilder().withMaxEncryptedDataKeys(MAX_EDKS).build(); } private KmsMasterKeyProvider providerWithEdks(int numKeys) { List<String> keyIds = new ArrayList<>(numKeys); for (int i = 0; i < numKeys; i++) { keyIds.add(KMSTestFixtures.US_WEST_2_KEY_ID); } return KmsMasterKeyProvider.builder() .customRegionalClientSupplier(testClientSupplier_) .buildStrict(keyIds); } @Test public void encryptDecryptWithLessThanMaxEdks() { KmsMasterKeyProvider provider = providerWithEdks(MAX_EDKS - 1); byte[] ciphertext = testCryptoClient_.encryptData(provider, PLAINTEXT).getResult(); byte[] decrypted = testCryptoClient_.decryptData(provider, ciphertext).getResult(); assertArrayEquals(decrypted, PLAINTEXT); } @Test public void encryptDecryptWithMaxEdks() { KmsMasterKeyProvider provider = providerWithEdks(MAX_EDKS); byte[] ciphertext = testCryptoClient_.encryptData(provider, PLAINTEXT).getResult(); byte[] decrypted = testCryptoClient_.decryptData(provider, ciphertext).getResult(); assertArrayEquals(decrypted, PLAINTEXT); } @Test public void noEncryptWithMoreThanMaxEdks() { KmsMasterKeyProvider provider = providerWithEdks(MAX_EDKS + 1); TestUtils.assertThrows( AwsCryptoException.class, "Encrypted data keys exceed maxEncryptedDataKeys", () -> testCryptoClient_.encryptData(provider, PLAINTEXT)); } @Test public void noDecryptWithMoreThanMaxEdks() { KmsMasterKeyProvider provider = providerWithEdks(MAX_EDKS + 1); byte[] ciphertext = AwsCrypto.standard().encryptData(provider, PLAINTEXT).getResult(); TestUtils.assertThrows( AwsCryptoException.class, "Ciphertext encrypted data keys exceed maxEncryptedDataKeys", () -> testCryptoClient_.decryptData(provider, ciphertext)); verify(testClient_, never()).decrypt((DecryptRequest) any()); } }
735
0
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk/kmssdkv2/AwsKmsMrkAwareMasterKeyTest.java
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package com.amazonaws.encryptionsdk.kmssdkv2; import static com.amazonaws.encryptionsdk.internal.RandomBytesGenerator.generate; import static org.junit.Assert.*; import static org.mockito.Mockito.*; import com.amazonaws.encryptionsdk.*; import com.amazonaws.encryptionsdk.exception.CannotUnwrapDataKeyException; import com.amazonaws.encryptionsdk.model.KeyBlob; import java.lang.reflect.Method; import java.nio.charset.StandardCharsets; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Map; import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec; import org.junit.Test; import org.junit.experimental.runners.Enclosed; import org.junit.jupiter.api.DisplayName; import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; import software.amazon.awssdk.awscore.exception.AwsServiceException; import software.amazon.awssdk.core.SdkBytes; import software.amazon.awssdk.services.kms.KmsClient; import software.amazon.awssdk.services.kms.model.*; @RunWith(Enclosed.class) public class AwsKmsMrkAwareMasterKeyTest { public static class getInstance { @Test public void basic_use() { KmsClient client = spy(new MockKmsClient()); MasterKeyProvider mkp = mock(MasterKeyProvider.class); // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.6 // = type=test // # On initialization, the caller MUST provide: final AwsKmsMrkAwareMasterKey test = AwsKmsMrkAwareMasterKey.getInstance( client, "arn:aws:kms:us-west-2:658956600833:key/b3537ef1-d8dc-4780-9f5a-55776cbb2f7f", mkp); // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.5 // = type=test // # MUST implement the Master Key Interface (../master-key- // # interface.md#interface) assertTrue(MasterKey.class.isInstance(test)); } @Test // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.6 // = type=test // # The AWS KMS key identifier MUST NOT be null or empty. public void requires_valid_identifiers() { KmsClient client = spy(new MockKmsClient()); MasterKeyProvider mkp = mock(MasterKeyProvider.class); assertThrows( IllegalArgumentException.class, () -> AwsKmsMrkAwareMasterKey.getInstance(client, "", mkp)); assertThrows( IllegalArgumentException.class, () -> AwsKmsMrkAwareMasterKey.getInstance(client, null, mkp)); // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.6 // = type=test // # The AWS KMS // # key identifier MUST be a valid identifier (aws-kms-key-arn.md#a- // # valid-aws-kms-identifier). assertThrows( IllegalArgumentException.class, () -> AwsKmsMrkAwareMasterKey.getInstance( client, "arn:aws:dynamodb:us-east-2:123456789012:table/myDynamoDBTable", mkp)); } @Test // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.6 // = type=test // # The AWS KMS SDK client MUST not be null. public void requires_valid_client() { MasterKeyProvider mkp = mock(MasterKeyProvider.class); assertThrows( IllegalArgumentException.class, () -> AwsKmsMrkAwareMasterKey.getInstance( null, "arn:aws:kms:us-west-2:658956600833:key/b3537ef1-d8dc-4780-9f5a-55776cbb2f7f", mkp)); } @Test @DisplayName("Precondition: A provider is required.") public void requires_valid_provider() { KmsClient client = spy(new MockKmsClient()); assertThrows( IllegalArgumentException.class, () -> AwsKmsMrkAwareMasterKey.getInstance( client, "arn:aws:kms:us-west-2:658956600833:key/b3537ef1-d8dc-4780-9f5a-55776cbb2f7f", null)); } } public static class generateDataKey { @Test public void basic_use() { final CryptoAlgorithm ALGORITHM_SUITE = CryptoAlgorithm.ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA256; final List<String> GRANT_TOKENS = Collections.singletonList("testGrantToken"); final Map<String, String> ENCRYPTION_CONTEXT = Collections.singletonMap("myKey", "myValue"); final String keyIdentifier = "arn:aws:kms:us-west-2:658956600833:key/b3537ef1-d8dc-4780-9f5a-55776cbb2f7f"; final KmsClient client = mock(KmsClient.class); when(client.generateDataKey((GenerateDataKeyRequest) any())) .thenReturn( GenerateDataKeyResponse.builder() .plaintext(SdkBytes.fromByteArray(new byte[ALGORITHM_SUITE.getDataKeyLength()])) .keyId(keyIdentifier) .ciphertextBlob(SdkBytes.fromByteArray(new byte[10])) .build()); final MasterKeyProvider mkp = mock(MasterKeyProvider.class); when(mkp.getDefaultProviderId()).thenReturn("aws-kms"); AwsKmsMrkAwareMasterKey masterKey = AwsKmsMrkAwareMasterKey.getInstance(client, keyIdentifier, mkp); // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.6 // = type=test // # The master key MUST be able to be configured with an optional list of // # Grant Tokens. masterKey.setGrantTokens(GRANT_TOKENS); // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.10 // = type=test // # The inputs MUST be the same as the Master Key Generate Data Key // # (../master-key-interface.md#generate-data-key) interface. DataKey<AwsKmsMrkAwareMasterKey> test = masterKey.generateDataKey(ALGORITHM_SUITE, ENCRYPTION_CONTEXT); ArgumentCaptor<GenerateDataKeyRequest> gr = ArgumentCaptor.forClass(GenerateDataKeyRequest.class); // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.10 // = type=test // # This // # master key MUST use the configured AWS KMS client to make an AWS KMS // # GenerateDatakey (https://docs.aws.amazon.com/kms/latest/APIReference/ // # API_GenerateDataKey.html) request constructed as follows: verify(client, times(1)).generateDataKey(gr.capture()); // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.10 // = type=test // # The output MUST be the same as the Master Key Generate Data Key // # (../master-key-interface.md#generate-data-key) interface. assertTrue(DataKey.class.isInstance(test)); GenerateDataKeyRequest actualRequest = gr.getValue(); assertEquals(keyIdentifier, actualRequest.keyId()); assertEquals(GRANT_TOKENS, actualRequest.grantTokens()); assertEquals(ENCRYPTION_CONTEXT, actualRequest.encryptionContext()); assertEquals(ALGORITHM_SUITE.getDataKeyLength(), actualRequest.numberOfBytes().longValue()); assertTrue(actualRequest.overrideConfiguration().isPresent()); assertTrue( actualRequest .overrideConfiguration() .get() .apiNames() .contains(AwsKmsMrkAwareMasterKey.API_NAME)); assertNotNull(test.getKey()); // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.10 // = type=test // # The response's "Plaintext" MUST be the plaintext in // # the output. assertEquals(ALGORITHM_SUITE.getDataKeyLength(), test.getKey().getEncoded().length); assertEquals(ALGORITHM_SUITE.getDataKeyAlgo(), test.getKey().getAlgorithm()); assertNotNull(test.getEncryptedDataKey()); // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.10 // = type=test // # The response's cipher text blob MUST be used as the // # returned as the ciphertext for the encrypted data key in the output. assertEquals(10, test.getEncryptedDataKey().length); } @Test // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.10 // = type=test // # If the call succeeds the AWS KMS Generate Data Key response's // # "Plaintext" MUST match the key derivation input length specified by // # the algorithm suite included in the input. public void length_must_match() { final CryptoAlgorithm ALGORITHM_SUITE = CryptoAlgorithm.ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA256; final Map<String, String> ENCRYPTION_CONTEXT = Collections.singletonMap("myKey", "myValue"); final String keyIdentifier = "arn:aws:kms:us-west-2:658956600833:key/b3537ef1-d8dc-4780-9f5a-55776cbb2f7f"; // I use more, because less _should_ trigger an underflow... but the condition should _always_ // fail final int wrongLength = ALGORITHM_SUITE.getDataKeyLength() + 1; final KmsClient client = mock(KmsClient.class); when(client.generateDataKey((GenerateDataKeyRequest) any())) .thenReturn( GenerateDataKeyResponse.builder() .plaintext(SdkBytes.fromByteArray(new byte[wrongLength])) .keyId(keyIdentifier) .ciphertextBlob(SdkBytes.fromByteArray(new byte[10])) .build()); final MasterKeyProvider mkp = mock(MasterKeyProvider.class); when(mkp.getDefaultProviderId()).thenReturn("aws-kms"); AwsKmsMrkAwareMasterKey masterKey = AwsKmsMrkAwareMasterKey.getInstance(client, keyIdentifier, mkp); assertThrows( IllegalStateException.class, () -> masterKey.generateDataKey(ALGORITHM_SUITE, ENCRYPTION_CONTEXT)); } @Test @DisplayName( "Exceptional Postcondition: Must have an AWS KMS ARN from AWS KMS generateDataKey.") public void need_an_arn() { final CryptoAlgorithm ALGORITHM_SUITE = CryptoAlgorithm.ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA256; final Map<String, String> ENCRYPTION_CONTEXT = Collections.singletonMap("myKey", "myValue"); final String keyIdentifier = "arn:aws:kms:us-west-2:658956600833:key/b3537ef1-d8dc-4780-9f5a-55776cbb2f7f"; final KmsClient client = mock(KmsClient.class); when(client.generateDataKey((GenerateDataKeyRequest) any())) .thenReturn( GenerateDataKeyResponse.builder() .plaintext(SdkBytes.fromByteArray(new byte[ALGORITHM_SUITE.getDataKeyLength()])) // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.10 // = type=test // # The response's "KeyId" // # MUST be valid. .keyId("b3537ef1-d8dc-4780-9f5a-55776cbb2f7f") .ciphertextBlob(SdkBytes.fromByteArray(new byte[10])) .build()); final MasterKeyProvider mkp = mock(MasterKeyProvider.class); when(mkp.getDefaultProviderId()).thenReturn("aws-kms"); AwsKmsMrkAwareMasterKey masterKey = AwsKmsMrkAwareMasterKey.getInstance(client, keyIdentifier, mkp); assertThrows( IllegalStateException.class, () -> masterKey.generateDataKey(ALGORITHM_SUITE, ENCRYPTION_CONTEXT)); } } public static class encryptDataKey { @Test public void basic_use() { final CryptoAlgorithm ALGORITHM_SUITE = CryptoAlgorithm.ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA256; final List<String> GRANT_TOKENS = Collections.singletonList("testGrantToken"); final Map<String, String> ENCRYPTION_CONTEXT = Collections.singletonMap("myKey", "myValue"); final String keyIdentifier = "arn:aws:kms:us-west-2:658956600833:key/b3537ef1-d8dc-4780-9f5a-55776cbb2f7f"; final SecretKey SECRET_KEY = new SecretKeySpec( generate(ALGORITHM_SUITE.getDataKeyLength()), ALGORITHM_SUITE.getDataKeyAlgo()); final MasterKeyProvider<AwsKmsMrkAwareMasterKey> mkp = mock(MasterKeyProvider.class); when(mkp.getDefaultProviderId()).thenReturn("aws-kms"); final DataKey dataKey = new DataKey( SECRET_KEY, new byte[0], "aws-kms".getBytes(StandardCharsets.UTF_8), mock(MasterKey.class)); final KmsClient client = mock(KmsClient.class); when(client.encrypt((EncryptRequest) any())) .thenReturn( EncryptResponse.builder() .keyId(keyIdentifier) .ciphertextBlob(SdkBytes.fromByteArray(new byte[10])) .build()); AwsKmsMrkAwareMasterKey masterKey = AwsKmsMrkAwareMasterKey.getInstance(client, keyIdentifier, mkp); masterKey.setGrantTokens(GRANT_TOKENS); // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.11 // = type=test // # The inputs MUST be the same as the Master Key Encrypt Data Key // # (../master-key-interface.md#encrypt-data-key) interface. DataKey<AwsKmsMrkAwareMasterKey> test = masterKey.encryptDataKey(ALGORITHM_SUITE, ENCRYPTION_CONTEXT, dataKey); // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.11 // = type=test // # The output MUST be the same as the Master Key Encrypt Data Key // # (../master-key-interface.md#encrypt-data-key) interface. assertTrue(DataKey.class.isInstance(test)); // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.11 // = type=test // # The master // # key MUST use the configured AWS KMS client to make an AWS KMS Encrypt // # (https://docs.aws.amazon.com/kms/latest/APIReference/ // # API_Encrypt.html) request constructed as follows: verify(client, times(1)).encrypt((EncryptRequest) any()); ArgumentCaptor<EncryptRequest> gr = ArgumentCaptor.forClass(EncryptRequest.class); verify(client, times(1)).encrypt(gr.capture()); final EncryptRequest actualRequest = gr.getValue(); assertEquals(keyIdentifier, actualRequest.keyId()); assertEquals(GRANT_TOKENS, actualRequest.grantTokens()); assertEquals(ENCRYPTION_CONTEXT, actualRequest.encryptionContext()); assertTrue(actualRequest.overrideConfiguration().isPresent()); assertTrue( actualRequest .overrideConfiguration() .get() .apiNames() .contains(AwsKmsMrkAwareMasterKey.API_NAME)); assertNotNull(test.getKey()); assertEquals(ALGORITHM_SUITE.getDataKeyLength(), test.getKey().getEncoded().length); assertEquals(ALGORITHM_SUITE.getDataKeyAlgo(), test.getKey().getAlgorithm()); assertNotNull(test.getEncryptedDataKey()); // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.11 // = type=test // # The // # response's cipher text blob MUST be used as the "ciphertext" for the // # encrypted data key. assertEquals(10, test.getEncryptedDataKey().length); } @Test @DisplayName("Precondition: The key format MUST be RAW.") public void secret_key_must_be_raw() { final CryptoAlgorithm ALGORITHM_SUITE = CryptoAlgorithm.ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA256; final List<String> GRANT_TOKENS = Collections.singletonList("testGrantToken"); final Map<String, String> ENCRYPTION_CONTEXT = Collections.singletonMap("myKey", "myValue"); final String keyIdentifier = "arn:aws:kms:us-west-2:658956600833:key/b3537ef1-d8dc-4780-9f5a-55776cbb2f7f"; final MasterKeyProvider<AwsKmsMrkAwareMasterKey> mkp = mock(MasterKeyProvider.class); when(mkp.getDefaultProviderId()).thenReturn("aws-kms"); // Test "stuff" here final SecretKey SECRET_KEY = mock(SecretKeySpec.class); when(SECRET_KEY.getFormat()).thenReturn("NOT-RAW"); final DataKey dataKey = new DataKey( SECRET_KEY, new byte[0], "aws-kms".getBytes(StandardCharsets.UTF_8), mock(MasterKey.class)); final KmsClient client = mock(KmsClient.class); when(client.encrypt((EncryptRequest) any())) .thenReturn( EncryptResponse.builder() .keyId(keyIdentifier) .ciphertextBlob(SdkBytes.fromByteArray(new byte[10])) .build()); AwsKmsMrkAwareMasterKey masterKey = AwsKmsMrkAwareMasterKey.getInstance(client, keyIdentifier, mkp); masterKey.setGrantTokens(GRANT_TOKENS); assertThrows( "Only RAW encoded keys are supported", IllegalArgumentException.class, () -> masterKey.encryptDataKey(ALGORITHM_SUITE, ENCRYPTION_CONTEXT, dataKey)); } @Test @DisplayName("Postcondition: Must have an AWS KMS ARN from AWS KMS encrypt.") public void need_an_arn() { final CryptoAlgorithm ALGORITHM_SUITE = CryptoAlgorithm.ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA256; final List<String> GRANT_TOKENS = Collections.singletonList("testGrantToken"); final Map<String, String> ENCRYPTION_CONTEXT = Collections.singletonMap("myKey", "myValue"); final String keyIdentifier = "arn:aws:kms:us-west-2:658956600833:key/b3537ef1-d8dc-4780-9f5a-55776cbb2f7f"; final SecretKey SECRET_KEY = new SecretKeySpec( generate(ALGORITHM_SUITE.getDataKeyLength()), ALGORITHM_SUITE.getDataKeyAlgo()); final MasterKeyProvider<AwsKmsMrkAwareMasterKey> mkp = mock(MasterKeyProvider.class); when(mkp.getDefaultProviderId()).thenReturn("aws-kms"); final DataKey dataKey = new DataKey( SECRET_KEY, new byte[0], "aws-kms".getBytes(StandardCharsets.UTF_8), mock(MasterKey.class)); final KmsClient client = mock(KmsClient.class); when(client.encrypt((EncryptRequest) any())) .thenReturn( EncryptResponse.builder() // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.11 // = type=test // # The AWS KMS Encrypt response MUST contain a valid "KeyId". .keyId("b3537ef1-d8dc-4780-9f5a-55776cbb2f7f") .ciphertextBlob(SdkBytes.fromByteArray(new byte[10])) .build()); AwsKmsMrkAwareMasterKey masterKey = AwsKmsMrkAwareMasterKey.getInstance(client, keyIdentifier, mkp); masterKey.setGrantTokens(GRANT_TOKENS); assertThrows( IllegalStateException.class, () -> masterKey.encryptDataKey(ALGORITHM_SUITE, ENCRYPTION_CONTEXT, dataKey)); } } public static class filterEncryptedDataKeys { @Test public void basic_use() { final String keyIdentifier = "arn:aws:kms:us-west-2:658956600833:key/b3537ef1-d8dc-4780-9f5a-55776cbb2f7f"; final String providerId = "aws-kms"; final EncryptedDataKey edk = new KeyBlob(providerId, keyIdentifier.getBytes(StandardCharsets.UTF_8), new byte[10]); assertTrue(AwsKmsMrkAwareMasterKey.filterEncryptedDataKeys(providerId, keyIdentifier, edk)); } @Test public void mrk_specific() { /* This may be overkill, * but the whole point * of multi-region optimization * is this fuzzy match. */ final String configuredIdentifier = "arn:aws:kms:us-west-2:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574"; final String ekdIdentifier = "arn:aws:kms:us-east-2:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574"; final String providerId = "aws-kms"; final EncryptedDataKey edk = new KeyBlob(providerId, ekdIdentifier.getBytes(StandardCharsets.UTF_8), new byte[10]); assertTrue( AwsKmsMrkAwareMasterKey.filterEncryptedDataKeys(providerId, configuredIdentifier, edk)); } @Test public void provider_info_must_be_arn() { final String configuredIdentifier = "arn:aws:kms:us-west-2:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574"; final String rawKeyId = "mrk-edb7fe6942894d32ac46dbb1c922d574"; final String alias = "arn:aws:kms:us-west-2:111122223333:alias/mrk-edb7fe6942894d32ac46dbb1c922d574"; final String providerId = "aws-kms"; final EncryptedDataKey edkNotArn = new KeyBlob(providerId, rawKeyId.getBytes(StandardCharsets.UTF_8), new byte[10]); final EncryptedDataKey edkAliasArn = new KeyBlob(providerId, rawKeyId.getBytes(StandardCharsets.UTF_8), new byte[10]); // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.9 // = type=test // # Additionally each provider info MUST be a valid AWS KMS ARN // # (aws-kms-key-arn.md#a-valid-aws-kms-arn) with a resource type of // # "key". assertThrows( IllegalStateException.class, () -> AwsKmsMrkAwareMasterKey.filterEncryptedDataKeys( providerId, configuredIdentifier, edkNotArn)); assertThrows( IllegalStateException.class, () -> AwsKmsMrkAwareMasterKey.filterEncryptedDataKeys( providerId, configuredIdentifier, edkAliasArn)); } @Test // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.9 // = type=test // # To match the encrypted data key's // # provider ID MUST exactly match the value "aws-kms" and the the // # function AWS KMS MRK Match for Decrypt (aws-kms-mrk-match-for- // # decrypt.md#implementation) called with the configured AWS KMS key // # identifier and the encrypted data key's provider info MUST return // # "true". public void may_not_match() { final String keyIdentifier = "arn:aws:kms:us-west-2:658956600833:key/b3537ef1-d8dc-4780-9f5a-55776cbb2f7f"; final String providerId = "aws-kms"; final EncryptedDataKey edk = new KeyBlob(providerId, keyIdentifier.getBytes(StandardCharsets.UTF_8), new byte[10]); assertFalse( AwsKmsMrkAwareMasterKey.filterEncryptedDataKeys("not-aws-kms", keyIdentifier, edk)); assertFalse( AwsKmsMrkAwareMasterKey.filterEncryptedDataKeys( providerId, "arn:aws:kms:us-west-2:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574", edk)); } } public static class decryptSingleEncryptedDataKey { @Test public void basic_use() { final CryptoAlgorithm ALGORITHM_SUITE = CryptoAlgorithm.ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA256; final List<String> GRANT_TOKENS = Collections.singletonList("testGrantToken"); final Map<String, String> ENCRYPTION_CONTEXT = Collections.singletonMap("myKey", "myValue"); final String keyIdentifier = "arn:aws:kms:us-west-2:658956600833:key/b3537ef1-d8dc-4780-9f5a-55776cbb2f7f"; final String providerId = "aws-kms"; final EncryptedDataKey edk = new KeyBlob(providerId, keyIdentifier.getBytes(StandardCharsets.UTF_8), new byte[10]); final MasterKeyProvider mkp = mock(MasterKeyProvider.class); when(mkp.getDefaultProviderId()).thenReturn(providerId); final KmsClient client = mock(KmsClient.class); when(client.decrypt((DecryptRequest) any())) .thenReturn( DecryptResponse.builder() .keyId(keyIdentifier) .plaintext(SdkBytes.fromByteArray(new byte[ALGORITHM_SUITE.getDataKeyLength()])) .build()); AwsKmsMrkAwareMasterKey masterKey = AwsKmsMrkAwareMasterKey.getInstance(client, keyIdentifier, mkp); masterKey.setGrantTokens(GRANT_TOKENS); DataKey<AwsKmsMrkAwareMasterKey> test = AwsKmsMrkAwareMasterKey.decryptSingleEncryptedDataKey( any(), client, keyIdentifier, GRANT_TOKENS, ALGORITHM_SUITE, edk, ENCRYPTION_CONTEXT); verify(client, times(1)).decrypt((DecryptRequest) any()); ArgumentCaptor<DecryptRequest> gr = ArgumentCaptor.forClass(DecryptRequest.class); verify(client, times(1)).decrypt(gr.capture()); final DecryptRequest actualRequest = gr.getValue(); // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.9 // = type=test // # To decrypt the encrypted data key this master key MUST use the // # configured AWS KMS client to make an AWS KMS Decrypt // # (https://docs.aws.amazon.com/kms/latest/APIReference/ // # API_Decrypt.html) request constructed as follows: assertEquals(keyIdentifier, actualRequest.keyId()); assertEquals(GRANT_TOKENS, actualRequest.grantTokens()); assertEquals(ENCRYPTION_CONTEXT, actualRequest.encryptionContext()); assertTrue(actualRequest.overrideConfiguration().isPresent()); assertTrue( actualRequest .overrideConfiguration() .get() .apiNames() .contains(AwsKmsMrkAwareMasterKey.API_NAME)); assertNotNull(test.getKey()); assertEquals(ALGORITHM_SUITE.getDataKeyLength(), test.getKey().getEncoded().length); assertEquals(ALGORITHM_SUITE.getDataKeyAlgo(), test.getKey().getAlgorithm()); } @Test @DisplayName("Exceptional Postcondition: Must have a CMK ARN from AWS KMS to match.") public void expect_key_arn() { final CryptoAlgorithm ALGORITHM_SUITE = CryptoAlgorithm.ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA256; final List<String> GRANT_TOKENS = Collections.singletonList("testGrantToken"); final Map<String, String> ENCRYPTION_CONTEXT = Collections.singletonMap("myKey", "myValue"); final String keyIdentifier = "arn:aws:kms:us-west-2:658956600833:key/b3537ef1-d8dc-4780-9f5a-55776cbb2f7f"; final String providerId = "aws-kms"; final EncryptedDataKey edk = new KeyBlob(providerId, keyIdentifier.getBytes(StandardCharsets.UTF_8), new byte[10]); final MasterKeyProvider mkp = mock(MasterKeyProvider.class); when(mkp.getDefaultProviderId()).thenReturn(providerId); final KmsClient client = mock(KmsClient.class); when(client.decrypt((DecryptRequest) any())) .thenReturn( DecryptResponse.builder() .keyId(null) .plaintext(SdkBytes.fromByteArray(new byte[ALGORITHM_SUITE.getDataKeyLength()])) .build()); AwsKmsMrkAwareMasterKey masterKey = AwsKmsMrkAwareMasterKey.getInstance(client, keyIdentifier, mkp); masterKey.setGrantTokens(GRANT_TOKENS); assertThrows( IllegalStateException.class, () -> AwsKmsMrkAwareMasterKey.decryptSingleEncryptedDataKey( any(), client, keyIdentifier, GRANT_TOKENS, ALGORITHM_SUITE, edk, ENCRYPTION_CONTEXT)); } @Test // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.9 // = type=test // # If the call succeeds then the response's "KeyId" MUST be equal to the // # configured AWS KMS key identifier otherwise the function MUST collect // # an error. public void returned_arn_must_match() { final CryptoAlgorithm ALGORITHM_SUITE = CryptoAlgorithm.ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA256; final List<String> GRANT_TOKENS = Collections.singletonList("testGrantToken"); final Map<String, String> ENCRYPTION_CONTEXT = Collections.singletonMap("myKey", "myValue"); final String keyIdentifier = "arn:aws:kms:us-west-2:658956600833:key/b3537ef1-d8dc-4780-9f5a-55776cbb2f7f"; final String providerId = "aws-kms"; final EncryptedDataKey edk = new KeyBlob(providerId, keyIdentifier.getBytes(StandardCharsets.UTF_8), new byte[10]); final MasterKeyProvider mkp = mock(MasterKeyProvider.class); when(mkp.getDefaultProviderId()).thenReturn(providerId); final KmsClient client = mock(KmsClient.class); when(client.decrypt((DecryptRequest) any())) .thenReturn( DecryptResponse.builder() .keyId("arn:aws:kms:us-west-2:658956600833:key/something-else") .plaintext(SdkBytes.fromByteArray(new byte[ALGORITHM_SUITE.getDataKeyLength()])) .build()); AwsKmsMrkAwareMasterKey masterKey = AwsKmsMrkAwareMasterKey.getInstance(client, keyIdentifier, mkp); masterKey.setGrantTokens(GRANT_TOKENS); assertThrows( IllegalStateException.class, () -> AwsKmsMrkAwareMasterKey.decryptSingleEncryptedDataKey( any(), client, keyIdentifier, GRANT_TOKENS, ALGORITHM_SUITE, edk, ENCRYPTION_CONTEXT)); } @Test // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.9 // = type=test // # The response's "Plaintext"'s length MUST equal the length // # required by the requested algorithm suite otherwise the function MUST // # collect an error. public void key_length_must_match() { final CryptoAlgorithm ALGORITHM_SUITE = CryptoAlgorithm.ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA256; final List<String> GRANT_TOKENS = Collections.singletonList("testGrantToken"); final Map<String, String> ENCRYPTION_CONTEXT = Collections.singletonMap("myKey", "myValue"); final String keyIdentifier = "arn:aws:kms:us-west-2:658956600833:key/b3537ef1-d8dc-4780-9f5a-55776cbb2f7f"; final String providerId = "aws-kms"; // I use more, because less _should_ trigger an underflow... but the condition should _always_ // fail final int wrongLength = ALGORITHM_SUITE.getDataKeyLength() + 1; final EncryptedDataKey edk = new KeyBlob(providerId, keyIdentifier.getBytes(StandardCharsets.UTF_8), new byte[10]); final MasterKeyProvider mkp = mock(MasterKeyProvider.class); when(mkp.getDefaultProviderId()).thenReturn(providerId); final KmsClient client = mock(KmsClient.class); when(client.decrypt((DecryptRequest) any())) .thenReturn( DecryptResponse.builder() .keyId(keyIdentifier) .plaintext(SdkBytes.fromByteArray(new byte[wrongLength])) .build()); AwsKmsMrkAwareMasterKey masterKey = AwsKmsMrkAwareMasterKey.getInstance(client, keyIdentifier, mkp); masterKey.setGrantTokens(GRANT_TOKENS); assertThrows( IllegalStateException.class, () -> AwsKmsMrkAwareMasterKey.decryptSingleEncryptedDataKey( any(), client, keyIdentifier, GRANT_TOKENS, ALGORITHM_SUITE, edk, ENCRYPTION_CONTEXT)); } } public static class decryptDataKey { @Test public void basic_use() { final String keyIdentifier = "arn:aws:kms:us-west-2:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574"; final CryptoAlgorithm ALGORITHM_SUITE = CryptoAlgorithm.ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA256; final List<String> GRANT_TOKENS = Collections.singletonList("testGrantToken"); final Map<String, String> ENCRYPTION_CONTEXT = Collections.singletonMap("myKey", "myValue"); final byte[] cipherText = new byte[10]; final String providerId = "aws-kms"; final MasterKeyProvider mkp = mock(MasterKeyProvider.class); when(mkp.getDefaultProviderId()).thenReturn(providerId); final EncryptedDataKey edk1 = new KeyBlob("aws-kms", keyIdentifier.getBytes(StandardCharsets.UTF_8), cipherText); final EncryptedDataKey edk2 = new KeyBlob("aws-kms", keyIdentifier.getBytes(StandardCharsets.UTF_8), cipherText); final KmsClient client = mock(KmsClient.class); when(client.decrypt((DecryptRequest) any())) .thenReturn( DecryptResponse.builder() .keyId(keyIdentifier) .plaintext(SdkBytes.fromByteArray(new byte[ALGORITHM_SUITE.getDataKeyLength()])) .build()); final AwsKmsMrkAwareMasterKey mk = AwsKmsMrkAwareMasterKey.getInstance(client, keyIdentifier, mkp); mk.setGrantTokens(GRANT_TOKENS); // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.9 // = type=test // # The inputs MUST be the same as the Master Key Decrypt Data Key // # (../master-key-interface.md#decrypt-data-key) interface. final DataKey<AwsKmsMrkAwareMasterKey> test = mk.decryptDataKey(ALGORITHM_SUITE, Arrays.asList(edk1, edk2), ENCRYPTION_CONTEXT); // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.9 // = type=test // # For each encrypted data key in the filtered set, one at a time, the // # master key MUST attempt to decrypt the data key. // // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.9 // = type=test // # If the AWS KMS response satisfies the requirements then it MUST be // # use and this function MUST return and not attempt to decrypt any more // # encrypted data keys. verify(client, times((1))) .decrypt( DecryptRequest.builder() .overrideConfiguration( builder -> builder.addApiName(AwsKmsMrkAwareMasterKey.API_NAME)) .grantTokens(GRANT_TOKENS) .encryptionContext(ENCRYPTION_CONTEXT) .keyId(keyIdentifier) .ciphertextBlob(SdkBytes.fromByteArray(cipherText)) .build()); // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.9 // = type=test // # The output MUST be the same as the Master Key Decrypt Data Key // # (../master-key-interface.md#decrypt-data-key) interface. assertTrue(DataKey.class.isInstance(test)); } @Test // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.9 // = type=test // # The set of encrypted data keys MUST first be filtered to match this // # master key's configuration. public void edk_match() { final CryptoAlgorithm ALGORITHM_SUITE = CryptoAlgorithm.ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA256; final List<String> GRANT_TOKENS = Collections.singletonList("testGrantToken"); final Map<String, String> ENCRYPTION_CONTEXT = Collections.singletonMap("myKey", "myValue"); final String keyIdentifier = "arn:aws:kms:us-west-2:658956600833:key/b3537ef1-d8dc-4780-9f5a-55776cbb2f7f"; final String providerId = "aws-kms"; final String clientErrMsg = "asdf"; final EncryptedDataKey edk1 = new KeyBlob("not-aws-kms", keyIdentifier.getBytes(StandardCharsets.UTF_8), new byte[10]); final EncryptedDataKey edk2 = new KeyBlob( providerId, "not-key-identifier".getBytes(StandardCharsets.UTF_8), new byte[10]); final MasterKeyProvider mkp = mock(MasterKeyProvider.class); when(mkp.getDefaultProviderId()).thenReturn(providerId); final KmsClient client = mock(KmsClient.class); when(client.decrypt((DecryptRequest) any())) .thenThrow(AwsServiceException.builder().message(clientErrMsg).build()); final RegionalClientSupplier supplier = mock(RegionalClientSupplier.class); when(supplier.getClient(any())).thenReturn(client); final AwsKmsMrkAwareMasterKey masterKey = AwsKmsMrkAwareMasterKey.getInstance(client, keyIdentifier, mkp); masterKey.setGrantTokens(GRANT_TOKENS); final CannotUnwrapDataKeyException testProviderNotMatch = assertThrows( "Unable to decrypt any data keys", CannotUnwrapDataKeyException.class, () -> masterKey.decryptDataKey( ALGORITHM_SUITE, Arrays.asList(edk1), ENCRYPTION_CONTEXT)); assertEquals(0, testProviderNotMatch.getSuppressed().length); final IllegalStateException testArnNotMatch = assertThrows( "Unable to decrypt any data keys", IllegalStateException.class, () -> masterKey.decryptDataKey( ALGORITHM_SUITE, Arrays.asList(edk2), ENCRYPTION_CONTEXT)); assertEquals(0, testArnNotMatch.getSuppressed().length); } @Test @DisplayName("Exceptional Postcondition: Master key was unable to decrypt.") // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.9 // = type=test // # If this attempt // # results in an error, then these errors MUST be collected. // // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.9 // = type=test // # If all the input encrypted data keys have been processed then this // # function MUST yield an error that includes all the collected errors. public void exception_wrapped() { final CryptoAlgorithm ALGORITHM_SUITE = CryptoAlgorithm.ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA256; final List<String> GRANT_TOKENS = Collections.singletonList("testGrantToken"); final Map<String, String> ENCRYPTION_CONTEXT = Collections.singletonMap("myKey", "myValue"); final String keyIdentifier = "arn:aws:kms:us-west-2:658956600833:key/b3537ef1-d8dc-4780-9f5a-55776cbb2f7f"; final String providerId = "aws-kms"; final String clientErrMsg = "asdf"; final EncryptedDataKey edk = new KeyBlob(providerId, keyIdentifier.getBytes(StandardCharsets.UTF_8), new byte[10]); final MasterKeyProvider mkp = mock(MasterKeyProvider.class); when(mkp.getDefaultProviderId()).thenReturn(providerId); final KmsClient client = mock(KmsClient.class); when(client.decrypt((DecryptRequest) any())) .thenThrow(AwsServiceException.builder().message(clientErrMsg).build()); RegionalClientSupplier supplier = mock(RegionalClientSupplier.class); when(supplier.getClient(any())).thenReturn(client); AwsKmsMrkAwareMasterKey masterKey = AwsKmsMrkAwareMasterKey.getInstance(client, keyIdentifier, mkp); masterKey.setGrantTokens(GRANT_TOKENS); final CannotUnwrapDataKeyException test = assertThrows( "Unable to decrypt any data keys", CannotUnwrapDataKeyException.class, () -> masterKey.decryptDataKey( ALGORITHM_SUITE, Arrays.asList(edk), ENCRYPTION_CONTEXT)); assertEquals(1, test.getSuppressed().length); Throwable fromClient = Arrays.stream(test.getSuppressed()).findFirst().get(); assertTrue(fromClient instanceof AwsServiceException); assertTrue(fromClient.getMessage().startsWith(clientErrMsg)); } } public static class getMasterKey { @Test // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.7 // = type=test // # MUST be unchanged from the Master Key interface. public void test_get_master_key() throws NoSuchMethodException { String methodName = "getMasterKey"; Class<?>[] parameterTypes = new Class<?>[] {String.class, String.class}; // Make sure the signature is correct by fetching the base method Method baseMethod = MasterKey.class.getDeclaredMethod(methodName, parameterTypes); assertNotNull(baseMethod); // Assert AwsKmsMrkAwareMasterKey does not declare the same method directly assertThrows( NoSuchMethodException.class, () -> AwsKmsMrkAwareMasterKey.class.getDeclaredMethod(methodName, parameterTypes)); } } public static class getMasterKeysForEncryption { @Test // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key.txt#2.8 // = type=test // # MUST be unchanged from the Master Key interface. public void test_getMasterKeysForEncryption() throws NoSuchMethodException { String methodName = "getMasterKeysForEncryption"; Class<?>[] parameterTypes = new Class<?>[] {MasterKeyRequest.class}; // Make sure the signature is correct by fetching the base method Method baseMethod = MasterKey.class.getDeclaredMethod(methodName, parameterTypes); assertNotNull(baseMethod); // Assert AwsKmsMrkAwareMasterKey does no declare the same method directly assertThrows( NoSuchMethodException.class, () -> AwsKmsMrkAwareMasterKey.class.getDeclaredMethod(methodName, parameterTypes)); } } }
736
0
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk/kmssdkv2/XCompatKmsDecryptTest.java
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package com.amazonaws.encryptionsdk.kmssdkv2; import static org.junit.Assert.assertArrayEquals; import com.amazonaws.encryptionsdk.AwsCrypto; import com.amazonaws.encryptionsdk.CryptoResult; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import java.io.File; import java.nio.file.Files; import java.nio.file.Paths; import java.util.*; import org.apache.commons.lang3.StringUtils; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; @RunWith(Parameterized.class) public class XCompatKmsDecryptTest { private final String plaintextFileName; private final String ciphertextFileName; private final String kmsKeyId; public XCompatKmsDecryptTest( String plaintextFileName, String ciphertextFileName, String kmsKeyId) { this.plaintextFileName = plaintextFileName; this.ciphertextFileName = ciphertextFileName; this.kmsKeyId = kmsKeyId; } @Parameters(name = "{index}: testDecryptFromFile({0}, {1}, {2})") public static Collection<Object[]> data() throws Exception { String baseDirName; baseDirName = System.getProperty("staticCompatibilityResourcesDir"); if (baseDirName == null) { baseDirName = XCompatKmsDecryptTest.class.getProtectionDomain().getCodeSource().getLocation().getPath() + "aws_encryption_sdk_resources"; } List<Object[]> testCases_ = new ArrayList<>(); String ciphertextManifestName = StringUtils.join( new String[] {baseDirName, "manifests", "ciphertext.manifest"}, File.separator); File ciphertextManifestFile = new File(ciphertextManifestName); if (!ciphertextManifestFile.exists()) { return Collections.emptyList(); } ObjectMapper ciphertextManifestMapper = new ObjectMapper(); Map<String, Object> ciphertextManifest = ciphertextManifestMapper.readValue( ciphertextManifestFile, new TypeReference<Map<String, Object>>() {}); List<Map<String, Object>> testCases = (List<Map<String, Object>>) ciphertextManifest.get("test_cases"); for (Map<String, Object> testCase : testCases) { Map<String, String> plaintext = (Map<String, String>) testCase.get("plaintext"); Map<String, String> ciphertext = (Map<String, String>) testCase.get("ciphertext"); List<Map<String, Object>> masterKeys = (List<Map<String, Object>>) testCase.get("master_keys"); for (Map<String, Object> masterKey : masterKeys) { String providerId = (String) masterKey.get("provider_id"); if (providerId.equals("aws-kms") && (boolean) masterKey.get("decryptable")) { testCases_.add( new Object[] { baseDirName + File.separator + plaintext.get("filename"), baseDirName + File.separator + ciphertext.get("filename"), (String) masterKey.get("key_id") }); break; } } } return testCases_; } @Test public void testDecryptFromFile() throws Exception { AwsCrypto crypto = AwsCrypto.standard(); final KmsMasterKeyProvider masterKeyProvider = KmsMasterKeyProvider.builder().buildStrict(kmsKeyId); byte[] ciphertextBytes = Files.readAllBytes(Paths.get(ciphertextFileName)); byte[] plaintextBytes = Files.readAllBytes(Paths.get(plaintextFileName)); final CryptoResult<byte[], KmsMasterKey> decryptResult = crypto.decryptData(masterKeyProvider, ciphertextBytes); assertArrayEquals(plaintextBytes, decryptResult.getResult()); } }
737
0
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk/kmssdkv2/KMSProviderBuilderIntegrationTests.java
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package com.amazonaws.encryptionsdk.kmssdkv2; import static com.amazonaws.encryptionsdk.TestUtils.assertThrows; import static org.junit.Assert.*; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.*; import com.amazonaws.encryptionsdk.*; import com.amazonaws.encryptionsdk.exception.AwsCryptoException; import com.amazonaws.encryptionsdk.exception.CannotUnwrapDataKeyException; import com.amazonaws.encryptionsdk.internal.VersionInfo; import com.amazonaws.encryptionsdk.kms.DiscoveryFilter; import com.amazonaws.encryptionsdk.kms.KMSTestFixtures; import com.amazonaws.encryptionsdk.model.KeyBlob; import java.nio.charset.StandardCharsets; import java.time.Duration; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicReference; import org.junit.Before; import org.junit.Test; import org.mockito.ArgumentCaptor; import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider; import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider; import software.amazon.awssdk.awscore.AwsRequest; import software.amazon.awssdk.awscore.AwsRequestOverrideConfiguration; import software.amazon.awssdk.core.ApiName; import software.amazon.awssdk.core.SdkRequest; import software.amazon.awssdk.core.client.config.ClientOverrideConfiguration; import software.amazon.awssdk.core.exception.ApiCallAttemptTimeoutException; import software.amazon.awssdk.core.exception.ApiCallTimeoutException; import software.amazon.awssdk.core.interceptor.Context; import software.amazon.awssdk.core.interceptor.ExecutionAttributes; import software.amazon.awssdk.core.interceptor.ExecutionInterceptor; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.kms.KmsClient; import software.amazon.awssdk.services.kms.model.DecryptRequest; import software.amazon.awssdk.services.kms.model.EncryptRequest; import software.amazon.awssdk.services.kms.model.GenerateDataKeyRequest; public class KMSProviderBuilderIntegrationTests { private static final String AWS_KMS_PROVIDER_ID = "aws-kms"; private KmsClient testUSWestClient__; private KmsClient testEUCentralClient__; private RegionalClientSupplier testClientSupplier__; @Before public void setup() { testUSWestClient__ = spy(new ProxyKmsClient(KmsClient.builder().region(Region.US_WEST_2).build())); testEUCentralClient__ = spy(new ProxyKmsClient(KmsClient.builder().region(Region.EU_CENTRAL_1).build())); testClientSupplier__ = region -> { if (region == Region.US_WEST_2) { return testUSWestClient__; } else if (region == Region.EU_CENTRAL_1) { return testEUCentralClient__; } else { throw new AwsCryptoException( "test supplier only configured for us-west-2 and eu-central-1"); } }; } @Test public void whenBogusRegionsDecrypted_doesNotLeakClients() throws Exception { AtomicReference<ConcurrentHashMap<Region, KmsClient>> kmsCache = new AtomicReference<>(); KmsMasterKeyProvider mkp = (new KmsMasterKeyProvider.Builder() { @Override protected void snoopClientCache(final ConcurrentHashMap<Region, KmsClient> map) { kmsCache.set(map); } }) .buildDiscovery(); try { mkp.decryptDataKey( CryptoAlgorithm.ALG_AES_128_GCM_IV12_TAG16_HKDF_SHA256, Collections.singleton( new KeyBlob( "aws-kms", "arn:aws:kms:us-bogus-1:123456789010:key/b3537ef1-d8dc-4780-9f5a-55776cbb2f7f" .getBytes(StandardCharsets.UTF_8), new byte[40])), new HashMap<>()); fail("Expected CannotUnwrapDataKeyException"); } catch (CannotUnwrapDataKeyException e) { // ok } assertTrue(kmsCache.get().isEmpty()); } @Test public void whenOperationSuccessful_clientIsCached() { AtomicReference<ConcurrentHashMap<Region, KmsClient>> kmsCache = new AtomicReference<>(); KmsMasterKeyProvider mkp = (new KmsMasterKeyProvider.Builder() { @Override protected void snoopClientCache(final ConcurrentHashMap<Region, KmsClient> map) { kmsCache.set(map); } }) .buildStrict(KMSTestFixtures.TEST_KEY_IDS[0]); AwsCrypto.standard().encryptData(mkp, new byte[1]); KmsClient kms = kmsCache.get().get(Region.US_WEST_2); assertNotNull(kms); AwsCrypto.standard().encryptData(mkp, new byte[1]); // Cache entry should stay the same assertEquals(kms, kmsCache.get().get(Region.US_WEST_2)); } // ============================================================================== GOOD @Test public void whenConstructedWithoutArguments_canUseMultipleRegions() throws Exception { KmsMasterKeyProvider mkp = KmsMasterKeyProvider.builder().buildDiscovery(); for (String key : KMSTestFixtures.TEST_KEY_IDS) { byte[] ciphertext = AwsCrypto.standard() .encryptData(KmsMasterKeyProvider.builder().buildStrict(key), new byte[1]) .getResult(); AwsCrypto.standard().decryptData(mkp, ciphertext); } } @Test public void whenConstructedInStrictMode_encryptDecrypt() throws Exception { KmsMasterKeyProvider mkp = KmsMasterKeyProvider.builder() .customRegionalClientSupplier(testClientSupplier__) .buildStrict(KMSTestFixtures.TEST_KEY_IDS[0]); byte[] ciphertext = AwsCrypto.standard().encryptData(mkp, new byte[1]).getResult(); verify(testUSWestClient__, times(1)).generateDataKey((GenerateDataKeyRequest) any()); AwsCrypto.standard().decryptData(mkp, ciphertext); verify(testUSWestClient__, times(1)).decrypt((DecryptRequest) any()); } @Test public void whenConstructedInStrictMode_encryptDecryptMultipleCmks() throws Exception { KmsMasterKeyProvider mkp = KmsMasterKeyProvider.builder() .customRegionalClientSupplier(testClientSupplier__) .buildStrict(KMSTestFixtures.US_WEST_2_KEY_ID, KMSTestFixtures.EU_CENTRAL_1_KEY_ID); byte[] ciphertext = AwsCrypto.standard().encryptData(mkp, new byte[1]).getResult(); verify(testUSWestClient__, times(1)).generateDataKey((GenerateDataKeyRequest) any()); verify(testEUCentralClient__, times(1)).encrypt((EncryptRequest) any()); AwsCrypto.standard().decryptData(mkp, ciphertext); verify(testUSWestClient__, times(1)).decrypt((DecryptRequest) any()); } @Test public void whenConstructedInStrictMode_encryptSingleBadKeyIdFails() throws Exception { KmsMasterKeyProvider mkp = KmsMasterKeyProvider.builder() .customRegionalClientSupplier(testClientSupplier__) .defaultRegion(Region.US_WEST_2) .buildStrict(KMSTestFixtures.US_WEST_2_KEY_ID, "badKeyId"); assertThrows( AwsCryptoException.class, () -> AwsCrypto.standard().encryptData(mkp, new byte[1]).getResult()); verify(testUSWestClient__, times(1)).generateDataKey((GenerateDataKeyRequest) any()); verify(testUSWestClient__, times(1)).encrypt((EncryptRequest) any()); } @Test public void whenConstructedInStrictMode_decryptBadEDKFails() throws Exception { KmsMasterKeyProvider mkp = KmsMasterKeyProvider.builder() .customRegionalClientSupplier(testClientSupplier__) .defaultRegion(Region.US_WEST_2) .buildStrict("badKeyId"); final CryptoAlgorithm algSuite = CryptoAlgorithm.ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA256; final Map<String, String> encCtx = Collections.singletonMap("myKey", "myValue"); final EncryptedDataKey badEDK = new KeyBlob( AWS_KMS_PROVIDER_ID, "badKeyId".getBytes(StandardCharsets.UTF_8), new byte[algSuite.getDataKeyLength()]); assertThrows( CannotUnwrapDataKeyException.class, () -> mkp.decryptDataKey(algSuite, Collections.singletonList(badEDK), encCtx)); verify(testUSWestClient__, times(1)).decrypt((DecryptRequest) any()); } @Test public void whenConstructedInDiscoveryMode_decrypt() throws Exception { KmsMasterKeyProvider singleCmkMkp = KmsMasterKeyProvider.builder() .customRegionalClientSupplier(testClientSupplier__) .buildStrict(KMSTestFixtures.TEST_KEY_IDS[0]); byte[] singleCmkCiphertext = AwsCrypto.standard().encryptData(singleCmkMkp, new byte[1]).getResult(); KmsMasterKeyProvider mkpToTest = KmsMasterKeyProvider.builder() .customRegionalClientSupplier(testClientSupplier__) .buildDiscovery(); AwsCrypto.standard().decryptData(mkpToTest, singleCmkCiphertext); verify(testUSWestClient__, times(1)).decrypt((DecryptRequest) any()); } @Test public void whenConstructedInDiscoveryMode_decryptBadEDKFails() throws Exception { KmsMasterKeyProvider mkp = KmsMasterKeyProvider.builder() .customRegionalClientSupplier(testClientSupplier__) .defaultRegion(Region.US_WEST_2) .buildDiscovery(); final CryptoAlgorithm algSuite = CryptoAlgorithm.ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA256; final Map<String, String> encCtx = Collections.singletonMap("myKey", "myValue"); final EncryptedDataKey badEDK = new KeyBlob( AWS_KMS_PROVIDER_ID, "badKeyId".getBytes(StandardCharsets.UTF_8), new byte[algSuite.getDataKeyLength()]); assertThrows( CannotUnwrapDataKeyException.class, () -> mkp.decryptDataKey(algSuite, Collections.singletonList(badEDK), encCtx)); verify(testUSWestClient__, times(1)).decrypt((DecryptRequest) any()); } @Test public void whenConstructedWithDiscoveryFilter_decrypt() throws Exception { KmsMasterKeyProvider singleCmkMkp = KmsMasterKeyProvider.builder() .customRegionalClientSupplier(testClientSupplier__) .buildStrict(KMSTestFixtures.TEST_KEY_IDS[0]); byte[] singleCmkCiphertext = AwsCrypto.standard().encryptData(singleCmkMkp, new byte[1]).getResult(); KmsMasterKeyProvider mkpToTest = KmsMasterKeyProvider.builder() .customRegionalClientSupplier(testClientSupplier__) .buildDiscovery( new DiscoveryFilter( KMSTestFixtures.PARTITION, Arrays.asList(KMSTestFixtures.ACCOUNT_ID))); AwsCrypto.standard().decryptData(mkpToTest, singleCmkCiphertext); verify(testUSWestClient__, times(1)).decrypt((DecryptRequest) any()); } @Test public void whenConstructedWithDiscoveryFilter_decryptBadEDKFails() throws Exception { KmsMasterKeyProvider mkp = KmsMasterKeyProvider.builder() .customRegionalClientSupplier(testClientSupplier__) .defaultRegion(Region.US_WEST_2) .buildDiscovery( new DiscoveryFilter( KMSTestFixtures.PARTITION, Arrays.asList(KMSTestFixtures.ACCOUNT_ID))); final CryptoAlgorithm algSuite = CryptoAlgorithm.ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA256; final Map<String, String> encCtx = Collections.singletonMap("myKey", "myValue"); final String badARN = "arn:aws:kms:us-west-2:658956600833:key/badID"; final EncryptedDataKey badEDK = new KeyBlob( AWS_KMS_PROVIDER_ID, badARN.getBytes(StandardCharsets.UTF_8), new byte[algSuite.getDataKeyLength()]); assertThrows( CannotUnwrapDataKeyException.class, () -> mkp.decryptDataKey(algSuite, Collections.singletonList(badEDK), encCtx)); verify(testUSWestClient__, times(1)).decrypt((DecryptRequest) any()); } @Test public void whenHandlerConfigured_handlerIsInvoked() throws Exception { ExecutionInterceptor interceptor = spy( new ExecutionInterceptor() { @Override public void beforeExecution( Context.BeforeExecution context, ExecutionAttributes executionAttributes) {} }); KmsMasterKeyProvider mkp = KmsMasterKeyProvider.builder() .builderSupplier( () -> KmsClient.builder() .overrideConfiguration( ClientOverrideConfiguration.builder() .addExecutionInterceptor(interceptor) .build())) .buildStrict(KMSTestFixtures.TEST_KEY_IDS[0]); AwsCrypto.standard().encryptData(mkp, new byte[1]); verify(interceptor).beforeExecution(any(), any()); } @Test public void whenShortTimeoutSet_timesOut() throws Exception { // By setting a timeout of 1ms, it's not physically possible to complete both the us-west-2 and // eu-central-1 // requests due to speed of light limits. KmsMasterKeyProvider mkp = KmsMasterKeyProvider.builder() .builderSupplier( () -> KmsClient.builder() .overrideConfiguration( ClientOverrideConfiguration.builder() .apiCallTimeout(Duration.ofMillis(1)) .build())) .buildStrict(Arrays.asList(KMSTestFixtures.TEST_KEY_IDS)); try { AwsCrypto.standard().encryptData(mkp, new byte[1]); fail("Expected exception"); } catch (Exception e) { if (!(e instanceof ApiCallAttemptTimeoutException) && !(e instanceof ApiCallTimeoutException)) { throw e; } } } // ================================================= BAD @Test public void whenBuilderCloned_configurationIsRetained() throws Exception { // TODO: remove test of credentials provider since no longer domain of builder supplier AwsCredentialsProvider customProvider1 = spy(new ProxyCredentialsProvider(DefaultCredentialsProvider.builder().build())); AwsCredentialsProvider customProvider2 = spy(new ProxyCredentialsProvider(DefaultCredentialsProvider.builder().build())); KmsMasterKeyProvider.Builder builder = KmsMasterKeyProvider.builder() .builderSupplier(() -> KmsClient.builder().credentialsProvider(customProvider1)); KmsMasterKeyProvider.Builder builder2 = builder.clone(); // This will mutate the first builder to change the creds, but leave the clone unchanged. MasterKeyProvider<?> mkp2 = builder .builderSupplier(() -> KmsClient.builder().credentialsProvider(customProvider2)) .buildStrict(KMSTestFixtures.TEST_KEY_IDS[0]); MasterKeyProvider<?> mkp1 = builder2.buildStrict(KMSTestFixtures.TEST_KEY_IDS[0]); CryptoResult<byte[], ?> result = AwsCrypto.standard().encryptData(mkp1, new byte[0]); verify(customProvider1, atLeastOnce()).resolveCredentials(); verify(customProvider2, never()).resolveCredentials(); reset(customProvider1, customProvider2); result = AwsCrypto.standard().encryptData(mkp2, new byte[0]); verify(customProvider1, never()).resolveCredentials(); verify(customProvider2, atLeastOnce()).resolveCredentials(); } @Test public void whenBuilderCloned_clientBuilderCustomizationIsRetained() throws Exception { ExecutionInterceptor interceptor = spy( new ExecutionInterceptor() { @Override public void beforeExecution( Context.BeforeExecution context, ExecutionAttributes executionAttributes) {} }); KmsMasterKeyProvider mkp = KmsMasterKeyProvider.builder() .builderSupplier( () -> KmsClient.builder() .overrideConfiguration( builder -> builder.addExecutionInterceptor(interceptor))) .clone() .buildStrict(KMSTestFixtures.TEST_KEY_IDS[0]); AwsCrypto.standard().encryptData(mkp, new byte[0]); verify(interceptor, atLeastOnce()).beforeExecution(any(), any()); } @Test public void whenUserAgentsOverridden_originalUAsPreserved() throws Exception { ExecutionInterceptor interceptor = spy( new ExecutionInterceptor() { @Override public SdkRequest modifyRequest( Context.ModifyRequest context, ExecutionAttributes executionAttributes) { if (!(context.request() instanceof AwsRequest)) { return context.request(); } AwsRequest awsRequest = (AwsRequest) context.request(); AwsRequestOverrideConfiguration.Builder overrideConfiguration; if (awsRequest.overrideConfiguration().isPresent()) { overrideConfiguration = awsRequest.overrideConfiguration().get().toBuilder(); } else { overrideConfiguration = AwsRequestOverrideConfiguration.builder(); } AwsRequestOverrideConfiguration newConfig = overrideConfiguration .addApiName(ApiName.builder().name("NEW_API").version("0.0.1").build()) .build(); awsRequest = awsRequest.toBuilder().overrideConfiguration(newConfig).build(); return awsRequest; } @Override public void beforeTransmission( Context.BeforeTransmission context, ExecutionAttributes executionAttributes) { // Just for spying } }); KmsMasterKeyProvider mkp = KmsMasterKeyProvider.builder() .builderSupplier( () -> KmsClient.builder() .overrideConfiguration( ClientOverrideConfiguration.builder() .addExecutionInterceptor(interceptor) .build())) .buildStrict(KMSTestFixtures.TEST_KEY_IDS[0]); AwsCrypto.standard().encryptData(mkp, new byte[0]); verify(interceptor, atLeastOnce()).modifyRequest(any(), any()); ArgumentCaptor<Context.BeforeTransmission> captor = ArgumentCaptor.forClass(Context.BeforeTransmission.class); verify(interceptor, atLeastOnce()).beforeTransmission(captor.capture(), any()); String ua = captor.getValue().httpRequest().headers().get("User-Agent").get(0); assertTrue(ua.contains("NEW_API/0.0.1")); assertTrue(ua.contains(VersionInfo.loadUserAgent())); } @Test public void whenDefaultRegionSet_itIsUsedForBareKeyIds() throws Exception { // TODO: Need to set up a role to assume as bare key IDs are relative to the caller account } }
738
0
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk/kmssdkv2/ProxyKmsClient.java
package com.amazonaws.encryptionsdk.kmssdkv2; import software.amazon.awssdk.awscore.exception.AwsServiceException; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.services.kms.KmsClient; import software.amazon.awssdk.services.kms.model.DecryptRequest; import software.amazon.awssdk.services.kms.model.DecryptResponse; import software.amazon.awssdk.services.kms.model.DependencyTimeoutException; import software.amazon.awssdk.services.kms.model.DisabledException; import software.amazon.awssdk.services.kms.model.EncryptRequest; import software.amazon.awssdk.services.kms.model.EncryptResponse; import software.amazon.awssdk.services.kms.model.GenerateDataKeyRequest; import software.amazon.awssdk.services.kms.model.GenerateDataKeyResponse; import software.amazon.awssdk.services.kms.model.IncorrectKeyException; import software.amazon.awssdk.services.kms.model.InvalidCiphertextException; import software.amazon.awssdk.services.kms.model.InvalidGrantTokenException; import software.amazon.awssdk.services.kms.model.InvalidKeyUsageException; import software.amazon.awssdk.services.kms.model.KeyUnavailableException; import software.amazon.awssdk.services.kms.model.KmsException; import software.amazon.awssdk.services.kms.model.KmsInternalException; import software.amazon.awssdk.services.kms.model.KmsInvalidStateException; import software.amazon.awssdk.services.kms.model.NotFoundException; /** This wraps KmsClient since the default implementation is final. */ class ProxyKmsClient implements KmsClient { private final KmsClient proxiedClient_; ProxyKmsClient(KmsClient kmsClient) { proxiedClient_ = kmsClient; } @Override public String serviceName() { return proxiedClient_.serviceName(); } @Override public void close() { proxiedClient_.close(); } @Override public DecryptResponse decrypt(DecryptRequest decryptRequest) throws NotFoundException, DisabledException, InvalidCiphertextException, KeyUnavailableException, IncorrectKeyException, InvalidKeyUsageException, DependencyTimeoutException, InvalidGrantTokenException, KmsInternalException, KmsInvalidStateException, AwsServiceException, SdkClientException, KmsException { return proxiedClient_.decrypt(decryptRequest); } @Override public EncryptResponse encrypt(EncryptRequest encryptRequest) throws NotFoundException, DisabledException, KeyUnavailableException, DependencyTimeoutException, InvalidKeyUsageException, InvalidGrantTokenException, KmsInternalException, KmsInvalidStateException, AwsServiceException, SdkClientException, KmsException { return proxiedClient_.encrypt(encryptRequest); } @Override public GenerateDataKeyResponse generateDataKey(GenerateDataKeyRequest generateDataKeyRequest) throws NotFoundException, DisabledException, KeyUnavailableException, DependencyTimeoutException, InvalidKeyUsageException, InvalidGrantTokenException, KmsInternalException, KmsInvalidStateException, AwsServiceException, SdkClientException, KmsException { return proxiedClient_.generateDataKey(generateDataKeyRequest); } }
739
0
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk/kmssdkv2/ProxyCredentialsProvider.java
package com.amazonaws.encryptionsdk.kmssdkv2; import software.amazon.awssdk.auth.credentials.AwsCredentials; import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider; class ProxyCredentialsProvider implements AwsCredentialsProvider { private final AwsCredentialsProvider proxiedProvider_; ProxyCredentialsProvider(AwsCredentialsProvider credentialsProvider) { proxiedProvider_ = credentialsProvider; } @Override public AwsCredentials resolveCredentials() { return proxiedProvider_.resolveCredentials(); } }
740
0
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk/kmssdkv2/AwsKmsMrkAwareMasterKeyProviderTest.java
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package com.amazonaws.encryptionsdk.kmssdkv2; import static com.amazonaws.encryptionsdk.internal.AwsKmsCmkArnInfo.parseInfoFromKeyArn; import static org.junit.Assert.*; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.*; import com.amazonaws.encryptionsdk.*; import com.amazonaws.encryptionsdk.exception.AwsCryptoException; import com.amazonaws.encryptionsdk.exception.CannotUnwrapDataKeyException; import com.amazonaws.encryptionsdk.exception.NoSuchMasterKeyException; import com.amazonaws.encryptionsdk.exception.UnsupportedProviderException; import com.amazonaws.encryptionsdk.kms.DiscoveryFilter; import com.amazonaws.encryptionsdk.model.KeyBlob; import java.lang.reflect.Field; import java.nio.charset.StandardCharsets; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.function.Consumer; import org.junit.Test; import org.junit.experimental.runners.Enclosed; import org.junit.jupiter.api.DisplayName; import org.junit.runner.RunWith; import software.amazon.awssdk.auth.credentials.AwsBasicCredentials; import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider; import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider; import software.amazon.awssdk.awscore.exception.AwsServiceException; import software.amazon.awssdk.core.SdkBytes; import software.amazon.awssdk.core.client.config.ClientOverrideConfiguration; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.kms.KmsClient; import software.amazon.awssdk.services.kms.KmsClientBuilder; import software.amazon.awssdk.services.kms.model.DecryptRequest; import software.amazon.awssdk.services.kms.model.DecryptResponse; @RunWith(Enclosed.class) public class AwsKmsMrkAwareMasterKeyProviderTest { public static class getResourceForResourceTypeKey { @Test @DisplayName("Postcondition: Return the key id.") public void basic_use() { assertEquals( "mrk-edb7fe6942894d32ac46dbb1c922d574", AwsKmsMrkAwareMasterKeyProvider.getResourceForResourceTypeKey( "arn:aws:kms:us-west-2:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574")); } @Test @DisplayName("Check for early return (Postcondition): Non-ARNs may be raw resources.") public void not_an_arn() { assertEquals( "mrk-edb7fe6942894d32ac46dbb1c922d574", AwsKmsMrkAwareMasterKeyProvider.getResourceForResourceTypeKey( "mrk-edb7fe6942894d32ac46dbb1c922d574")); final String malformed = "aws:kms:us-west-2::key/garbage"; assertEquals( malformed, AwsKmsMrkAwareMasterKeyProvider.getResourceForResourceTypeKey(malformed)); } @Test @DisplayName( "Check for early return (Postcondition): Return the identifier for non-key resource types.") public void not_a_key() { final String alias = "arn:aws:kms:us-west-2:658956600833:alias/EncryptDecrypt"; assertEquals(alias, AwsKmsMrkAwareMasterKeyProvider.getResourceForResourceTypeKey(alias)); } } public static class assertMrksAreUnique { @Test // = compliance/framework/aws-kms/aws-kms-mrk-are-unique.txt#2.5 // = type=test // # The caller MUST provide: public void basic_use() { AwsKmsMrkAwareMasterKeyProvider.assertMrksAreUnique( Arrays.asList( "arn:aws:kms:us-west-2:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574")); } @Test public void no_duplicates() { // = compliance/framework/aws-kms/aws-kms-mrk-are-unique.txt#2.5 // = type=test // # If there are zero duplicate resource ids between the multi-region // # keys, this function MUST exit successfully AwsKmsMrkAwareMasterKeyProvider.assertMrksAreUnique( Arrays.asList( "arn:aws:kms:us-west-2:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574", "arn:aws:kms:us-west-2:658956600833:key/b3537ef1-d8dc-4780-9f5a-55776cbb2f7f")); } @Test // = compliance/framework/aws-kms/aws-kms-mrk-are-unique.txt#2.5 // = type=test // # If the list does not contain any multi-Region keys (aws-kms-key- // # arn.md#identifying-an-aws-kms-multi-region-key) this function MUST // # exit successfully. public void no_mrks_at_all() { AwsKmsMrkAwareMasterKeyProvider.assertMrksAreUnique( Arrays.asList( "arn:aws:kms:us-west-2:658956600833:key/b3537ef1-d8dc-4780-9f5a-55776cbb2f7f", "arn:aws:kms:us-west-2:658956600833:key/b3537ef1-d8dc-4780-9f5a-55776cbb2f7f")); } @Test @DisplayName("Postcondition: Filter out duplicate resources that are not multi-region keys.") public void non_mrk_duplicates_ok() { AwsKmsMrkAwareMasterKeyProvider.assertMrksAreUnique( Arrays.asList( "arn:aws:kms:us-west-2:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574", "arn:aws:kms:us-west-2:658956600833:key/b3537ef1-d8dc-4780-9f5a-55776cbb2f7f", "arn:aws:kms:us-west-2:658956600833:key/b3537ef1-d8dc-4780-9f5a-55776cbb2f7f", "arn:aws:kms:us-west-2:658956600833:alias/EncryptDecrypt", "arn:aws:kms:us-west-2:658956600833:alias/EncryptDecrypt")); } @Test // = compliance/framework/aws-kms/aws-kms-mrk-are-unique.txt#2.5 // = type=test // # If any duplicate multi-region resource ids exist, this function MUST // # yield an error that includes all identifiers with duplicate resource // # ids not only the first duplicate found. public void no_duplicate_mrks() { assertThrows( IllegalArgumentException.class, () -> AwsKmsMrkAwareMasterKeyProvider.assertMrksAreUnique( Arrays.asList( "arn:aws:kms:us-west-2:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574", "arn:aws:kms:us-east-1:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574"))); } } // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.6 // = type=test // # On initialization the caller MUST provide: public static class AwsKmsMrkAwareMasterKeyProviderBuilderTests { @Test public void basic_use() { final AwsKmsMrkAwareMasterKeyProvider strict = AwsKmsMrkAwareMasterKeyProvider.builder() .buildStrict( "arn:aws:kms:us-west-2:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574"); final AwsKmsMrkAwareMasterKeyProvider discovery = AwsKmsMrkAwareMasterKeyProvider.builder().buildDiscovery(); // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.5 // = type=test // # MUST implement the Master Key Provider Interface (../master-key- // # provider-interface.md#interface) assertTrue(MasterKeyProvider.class.isInstance(strict)); assertTrue(MasterKeyProvider.class.isInstance(discovery)); // These are not testable because of how the builder is structured. // // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.6 // = type=test // # A discovery filter MUST NOT be configured in strict mode. // // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.6 // = type=test // # A default MRK Region MUST NOT be configured in strict mode. // // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.6 // = type=test // # In // # discovery mode if a default MRK Region is not configured the AWS SDK // # Default Region MUST be used. // // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.6 // = type=test // # The key id list MUST be empty in discovery mode. // // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.6 // = type=test // # The regional client // # supplier MUST be defined in discovery mode. } @Test // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.6 // = type=test // # The key id list MUST NOT be empty or null in strict mode. public void no_noop() { assertThrows( IllegalArgumentException.class, () -> AwsKmsMrkAwareMasterKeyProvider.builder().buildStrict()); assertThrows( IllegalArgumentException.class, () -> AwsKmsMrkAwareMasterKeyProvider.builder().buildStrict(new ArrayList<String>())); } @Test // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.6 // = type=test // # The key id // # list MUST NOT contain any null or empty string values. public void no_null_identifiers() { assertThrows( IllegalArgumentException.class, () -> AwsKmsMrkAwareMasterKeyProvider.builder() .buildStrict( "arn:aws:kms:us-west-2:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574", "")); assertThrows( IllegalArgumentException.class, () -> AwsKmsMrkAwareMasterKeyProvider.builder() .buildStrict( "arn:aws:kms:us-west-2:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574", null)); } @Test // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.6 // = type=test // # All AWS KMS // # key identifiers are be passed to Assert AWS KMS MRK are unique (aws- // # kms-mrk-are-unique.md#Implementation) and the function MUST return // # success. public void no_duplicate_mrks() { assertThrows( IllegalArgumentException.class, () -> AwsKmsMrkAwareMasterKeyProvider.builder() .buildStrict( "arn:aws:kms:us-west-2:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574", "arn:aws:kms:us-east-1:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574")); } @Test @DisplayName("Precondition: A region is required to contact AWS KMS.") public void always_need_a_region() { assertThrows( AwsCryptoException.class, () -> AwsKmsMrkAwareMasterKeyProvider.builder() .defaultRegion(null) .buildStrict("mrk-edb7fe6942894d32ac46dbb1c922d574")); AwsKmsMrkAwareMasterKeyProvider.builder() .defaultRegion(Region.US_EAST_1) .buildStrict("mrk-edb7fe6942894d32ac46dbb1c922d574"); } @Test // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.6 // = type=test // # If an AWS SDK Default Region can not be // # obtained initialization MUST fail. public void discovery_region_can_not_be_null() { assertThrows( IllegalArgumentException.class, () -> AwsKmsMrkAwareMasterKeyProvider.builder() // need to force the default region to `null` // otherwise it may pick one up from the environment. .defaultRegion(null) .discoveryMrkRegion(null) .buildDiscovery()); } @Test @DisplayName("Precondition: Discovery filter is only valid in discovery mode.") public void strict_cannot_have_discovery_filter() { assertThrows( IllegalArgumentException.class, () -> { AwsKmsMrkAwareMasterKeyProvider mkp = AwsKmsMrkAwareMasterKeyProvider.builder() .buildStrict( "arn:aws:kms:us-west-2:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574"); Field field = mkp.getClass().getDeclaredField("discoveryFilter_"); field.setAccessible(true); DiscoveryFilter filter = new DiscoveryFilter("partition", "accountId1"); field.set(mkp, filter); field.setAccessible(false); mkp.withGrantTokens("token1", "token2"); }); } @Test @DisplayName("Precondition: Discovery mode can not have any keys to filter.") public void discovery_cannot_have_any_keys() { assertThrows( IllegalArgumentException.class, () -> { AwsKmsMrkAwareMasterKeyProvider mkp = AwsKmsMrkAwareMasterKeyProvider.builder().buildDiscovery(); Field field = mkp.getClass().getDeclaredField("keyIds_"); field.setAccessible(true); List<String> keyIds = Arrays.asList("keyId1", "keyId2"); field.set(mkp, keyIds); field.setAccessible(false); mkp.withGrantTokens("token1", "token2"); }); } @Test public void get_grant_tokens() { AwsKmsMrkAwareMasterKeyProvider mkp = AwsKmsMrkAwareMasterKeyProvider.builder().buildDiscovery(); mkp = mkp.withGrantTokens("token1", "token2"); assert (mkp.getGrantTokens()).contains("token1"); assert (mkp.getGrantTokens()).contains("token2"); } @Test public void basic_credentials_and_builder() { AwsCredentialsProvider credsProvider = StaticCredentialsProvider.create(AwsBasicCredentials.create("asdf", "qwer")); AwsKmsMrkAwareMasterKeyProvider.builder() .builderSupplier(() -> KmsClient.builder().credentialsProvider(credsProvider)) .buildDiscovery(); } } public static class extractRegion { @Test public void basic_use() { final Region test = AwsKmsMrkAwareMasterKeyProvider.extractRegion( Region.US_EAST_1, Region.US_EAST_2, Optional.of( "arn:aws:kms:us-west-2:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574"), parseInfoFromKeyArn( "arn:aws:kms:us-west-2:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574"), false); assertEquals(Region.US_WEST_2, test); } @Test // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.7 // = type=test // # If the requested AWS KMS key identifier is not a well formed ARN the // # AWS Region MUST be the configured default region this SHOULD be // # obtained from the AWS SDK. public void not_an_arn() { final Region test = AwsKmsMrkAwareMasterKeyProvider.extractRegion( Region.US_EAST_1, Region.US_EAST_2, Optional.empty(), parseInfoFromKeyArn("mrk-edb7fe6942894d32ac46dbb1c922d574"), false); assertEquals(Region.US_EAST_1, test); } @Test // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.7 // = type=test // # Otherwise if the requested AWS KMS key // # identifier is identified as a multi-Region key (aws-kms-key- // # arn.md#identifying-an-aws-kms-multi-region-key), then AWS Region MUST // # be the region from the AWS KMS key ARN stored in the provider info // # from the encrypted data key. public void not_an_mrk() { final Region test = AwsKmsMrkAwareMasterKeyProvider.extractRegion( Region.US_EAST_1, Region.US_EAST_2, Optional.of( "arn:aws:kms:us-west-2:658956600833:key/b3537ef1-d8dc-4780-9f5a-55776cbb2f7f"), parseInfoFromKeyArn( "arn:aws:kms:us-west-2:658956600833:key/b3537ef1-d8dc-4780-9f5a-55776cbb2f7f"), false); assertEquals(Region.US_WEST_2, test); final Region test2 = AwsKmsMrkAwareMasterKeyProvider.extractRegion( Region.US_EAST_1, Region.US_EAST_2, Optional.of("arn:aws:kms:us-west-2:658956600833:alias/mrk-nasty"), parseInfoFromKeyArn("arn:aws:kms:us-west-2:658956600833:alias/mrk-nasty"), false); assertEquals(Region.US_WEST_2, test2); } @Test // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.7 // = type=test // # Otherwise if the mode is discovery then // # the AWS Region MUST be the discovery MRK region. public void mrk_in_discovery() { final Region test = AwsKmsMrkAwareMasterKeyProvider.extractRegion( Region.US_EAST_1, Region.US_EAST_2, Optional.empty(), parseInfoFromKeyArn( "arn:aws:kms:us-west-2:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574"), true); assertEquals(Region.US_EAST_2, test); } @Test // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.7 // = type=test // # Finally if the // # provider info is identified as a multi-Region key (aws-kms-key- // # arn.md#identifying-an-aws-kms-multi-region-key) the AWS Region MUST // # be the region from the AWS KMS key in the configured key ids matched // # to the requested AWS KMS key by using AWS KMS MRK Match for Decrypt // # (aws-kms-mrk-match-for-decrypt.md#implementation). public void fuzzy_match_mrk() { final Region test = AwsKmsMrkAwareMasterKeyProvider.extractRegion( Region.US_EAST_1, Region.US_EAST_2, Optional.of( "arn:aws:kms:us-west-2:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574"), parseInfoFromKeyArn( "arn:aws:kms:us-west-1:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574"), false); assertEquals(Region.US_WEST_2, test); } } public static class getMasterKey { @Test public void basic_use() { final String identifier = "arn:aws:kms:us-west-2:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574"; final KmsClient client = spy(new MockKmsClient()); final RegionalClientSupplier supplier = mock(RegionalClientSupplier.class); when(supplier.getClient(any())).thenReturn(client); AwsKmsMrkAwareMasterKeyProvider mkp = AwsKmsMrkAwareMasterKeyProvider.builder() .customRegionalClientSupplier(supplier) .buildStrict(identifier); // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.7 // = type=test // # The input MUST be the same as the Master Key Provider Get Master Key // # (../master-key-provider-interface.md#get-master-key) interface. AwsKmsMrkAwareMasterKey test = mkp.getMasterKey("aws-kms", identifier); // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.7 // = type=test // # The output MUST be the same as the Master Key Provider Get Master Key // # (../master-key-provider-interface.md#get-master-key) interface. assertTrue(AwsKmsMrkAwareMasterKey.class.isInstance((test))); assertEquals(identifier, test.getKeyId()); verify(supplier, times(1)).getClient(Region.US_WEST_2); } @Test public void basic_mrk_use() { final String configuredIdentifier = "arn:aws:kms:us-west-2:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574"; final String requestedIdentifier = "arn:aws:kms:us-east-1:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574"; final KmsClient client = spy(new MockKmsClient()); final RegionalClientSupplier supplier = mock(RegionalClientSupplier.class); when(supplier.getClient(any())).thenReturn(client); AwsKmsMrkAwareMasterKeyProvider mkp = AwsKmsMrkAwareMasterKeyProvider.builder() .customRegionalClientSupplier(supplier) .buildStrict(configuredIdentifier); AwsKmsMrkAwareMasterKey test = mkp.getMasterKey("aws-kms", requestedIdentifier); assertEquals(configuredIdentifier, test.getKeyId()); verify(supplier, times(1)).getClient(Region.US_WEST_2); } @Test public void other_basic_uses() { final KmsClient client = spy(new MockKmsClient()); final RegionalClientSupplier supplier = mock(RegionalClientSupplier.class); when(supplier.getClient(any())).thenReturn(client); // A raw alias is a valid configuration for encryption final String rawAliasIdentifier = "alias/my-alias"; AwsKmsMrkAwareMasterKeyProvider.builder() .customRegionalClientSupplier(supplier) .buildStrict(rawAliasIdentifier) .getMasterKey("aws-kms", rawAliasIdentifier); // A raw alias is a valid configuration for encryption final String rawKeyIdentifier = "mrk-edb7fe6942894d32ac46dbb1c922d574"; AwsKmsMrkAwareMasterKeyProvider.builder() .customRegionalClientSupplier(supplier) .buildStrict(rawKeyIdentifier) .getMasterKey("aws-kms", rawKeyIdentifier); } @Test // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.7 // = type=test // # The function MUST only provide master keys if the input provider id // # equals "aws-kms". public void only_this_provider() { final String identifier = "arn:aws:kms:us-west-2:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574"; final KmsClient client = spy(new MockKmsClient()); final RegionalClientSupplier supplier = mock(RegionalClientSupplier.class); when(supplier.getClient(any())).thenReturn(client); AwsKmsMrkAwareMasterKeyProvider mkp = AwsKmsMrkAwareMasterKeyProvider.builder() .customRegionalClientSupplier(supplier) .buildStrict(identifier); assertThrows( UnsupportedProviderException.class, () -> mkp.getMasterKey("not-aws-kms", identifier)); } @Test // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.7 // = type=test // # In strict mode, the requested AWS KMS key ARN MUST // # match a member of the configured key ids by using AWS KMS MRK Match // # for Decrypt (aws-kms-mrk-match-for-decrypt.md#implementation) // # otherwise this function MUST error. public void no_key_id_match() { final String identifier = "arn:aws:kms:us-west-2:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574"; final KmsClient client = spy(new MockKmsClient()); final RegionalClientSupplier supplier = mock(RegionalClientSupplier.class); when(supplier.getClient(any())).thenReturn(client); final AwsKmsMrkAwareMasterKeyProvider mkp = AwsKmsMrkAwareMasterKeyProvider.builder() .customRegionalClientSupplier(supplier) .buildStrict(identifier); assertThrows( NoSuchMasterKeyException.class, () -> mkp.getMasterKey("aws-kms", "does-not-match-configured")); } @Test @DisplayName("Precondition: Discovery mode requires requestedKeyArn be an ARN.") // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.7 // = type=test // # In discovery mode, the requested // # AWS KMS key identifier MUST be a well formed AWS KMS ARN. public void discovery_request_must_be_arn() { AwsKmsMrkAwareMasterKeyProvider mkp = AwsKmsMrkAwareMasterKeyProvider.builder().buildDiscovery(); assertThrows( NoSuchMasterKeyException.class, () -> mkp.getMasterKey("aws-kms", "mrk-edb7fe6942894d32ac46dbb1c922d574")); } @Test // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.7 // = type=test // # In // # discovery mode if a discovery filter is configured the requested AWS // # KMS key ARN's "partition" MUST match the discovery filter's // # "partition" and the AWS KMS key ARN's "account" MUST exist in the // # discovery filter's account id set. public void discovery_filter_must_match() { final String identifier = "arn:aws:kms:us-west-2:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574"; final KmsClient client = spy(new MockKmsClient()); final RegionalClientSupplier supplier = mock(RegionalClientSupplier.class); when(supplier.getClient(any())).thenReturn(client); assertThrows( NoSuchMasterKeyException.class, () -> AwsKmsMrkAwareMasterKeyProvider.builder() .buildDiscovery(new DiscoveryFilter("aws", Arrays.asList("not-111122223333"))) .getMasterKey("aws-kms", identifier)); assertThrows( NoSuchMasterKeyException.class, () -> AwsKmsMrkAwareMasterKeyProvider.builder() .buildDiscovery(new DiscoveryFilter("not-aws", Arrays.asList("111122223333"))) .getMasterKey("aws-kms", identifier)); } @Test // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.7 // = type=test // # In discovery mode a AWS KMS MRK Aware Master Key (aws-kms-mrk-aware- // # master-key.md) MUST be returned configured with public void discovery_magic_to_make_the_region_match() { final String identifier = "arn:aws:kms:us-west-2:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574"; final KmsClient client = spy(new MockKmsClient()); final RegionalClientSupplier supplier = mock(RegionalClientSupplier.class); when(supplier.getClient(any())).thenReturn(client); AwsKmsMrkAwareMasterKeyProvider mkp = AwsKmsMrkAwareMasterKeyProvider.builder() .customRegionalClientSupplier(supplier) .discoveryMrkRegion(Region.of("my-region")) .buildDiscovery(); AwsKmsMrkAwareMasterKey test = mkp.getMasterKey("aws-kms", identifier); // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.7 // = type=test // # An AWS KMS client // # MUST be obtained by calling the regional client supplier with this // # AWS Region. assertEquals( "arn:aws:kms:my-region:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574", test.getKeyId()); verify(supplier, times(1)).getClient(Region.of("my-region")); } @Test // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.7 // = type=test // # In strict mode a AWS KMS MRK Aware Master Key (aws-kms-mrk-aware- // # master-key.md) MUST be returned configured with public void strict_mrk_region_match() { final String identifier = "arn:aws:kms:us-west-2:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574"; final String configIdentifier = "arn:aws:kms:us-east-1:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574"; final KmsClient client = spy(new MockKmsClient()); final RegionalClientSupplier supplier = mock(RegionalClientSupplier.class); when(supplier.getClient(any())).thenReturn(client); AwsKmsMrkAwareMasterKeyProvider mkp = AwsKmsMrkAwareMasterKeyProvider.builder() .customRegionalClientSupplier(supplier) .buildStrict(configIdentifier); AwsKmsMrkAwareMasterKey test = mkp.getMasterKey("aws-kms", identifier); assertEquals(configIdentifier, test.getKeyId()); verify(supplier, times(1)).getClient(Region.US_EAST_1); } } public static class decryptDataKey { @Test public void basic_use() { final String identifier = "arn:aws:kms:us-west-2:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574"; final CryptoAlgorithm ALGORITHM_SUITE = CryptoAlgorithm.ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA256; final List<String> GRANT_TOKENS = Collections.singletonList("testGrantToken"); final Map<String, String> ENCRYPTION_CONTEXT = Collections.singletonMap("myKey", "myValue"); final byte[] cipherText = new byte[10]; final EncryptedDataKey edk1 = new KeyBlob("aws-kms", identifier.getBytes(StandardCharsets.UTF_8), cipherText); final EncryptedDataKey edk2 = new KeyBlob("aws-kms", identifier.getBytes(StandardCharsets.UTF_8), cipherText); final RegionalClientSupplier supplier = mock(RegionalClientSupplier.class); final KmsClient client = mock(KmsClient.class); when(client.decrypt((DecryptRequest) any())) .thenReturn( DecryptResponse.builder() .keyId(identifier) .plaintext(SdkBytes.fromByteArray(new byte[ALGORITHM_SUITE.getDataKeyLength()])) .build()); when(supplier.getClient(any())).thenReturn(client); AwsKmsMrkAwareMasterKeyProvider mkp = AwsKmsMrkAwareMasterKeyProvider.builder() .customRegionalClientSupplier(supplier) .buildStrict(identifier) .withGrantTokens(GRANT_TOKENS); // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.9 // = type=test // # The input MUST be the same as the Master Key Provider Decrypt Data // # Key (../master-key-provider-interface.md#decrypt-data-key) interface. final DataKey<AwsKmsMrkAwareMasterKey> test = mkp.decryptDataKey(ALGORITHM_SUITE, Arrays.asList(edk1, edk2), ENCRYPTION_CONTEXT); // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.9 // = type=test // # For each encrypted data key in the filtered set, one at a time, the // # master key provider MUST call Get Master Key (aws-kms-mrk-aware- // # master-key-provider.md#get-master-key) with the encrypted data key's // # provider info as the AWS KMS key ARN. // // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.9 // = type=test // # It MUST call Decrypt Data Key // # (aws-kms-mrk-aware-master-key.md#decrypt-data-key) on this master key // # with the input algorithm, this single encrypted data key, and the // # input encryption context. // // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.9 // = type=test // # If the decrypt data key call is // # successful, then this function MUST return this result and not // # attempt to decrypt any more encrypted data keys. verify(client, times((1))) .decrypt( DecryptRequest.builder() .overrideConfiguration( builder -> builder.addApiName(AwsKmsMrkAwareMasterKey.API_NAME)) .grantTokens(GRANT_TOKENS) .encryptionContext(ENCRYPTION_CONTEXT) .keyId(identifier) .ciphertextBlob(SdkBytes.fromByteArray(cipherText)) .build()); // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.9 // = type=test // # The output MUST be the same as the Master Key Provider Decrypt Data // # Key (../master-key-provider-interface.md#decrypt-data-key) interface. assertTrue(DataKey.class.isInstance(test)); } @Test // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.9 // = type=test // # The set of encrypted data keys MUST first be filtered to match this // # master key's configuration. public void only_if_providers_match() { final String identifier = "arn:aws:kms:us-west-2:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574"; final CryptoAlgorithm ALGORITHM_SUITE = CryptoAlgorithm.ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA256; final Map<String, String> ENCRYPTION_CONTEXT = Collections.singletonMap("myKey", "myValue"); final EncryptedDataKey edk = new KeyBlob( "not-aws-kms", "not the identifier".getBytes(StandardCharsets.UTF_8), new byte[10]); AwsKmsMrkAwareMasterKeyProvider mkp = AwsKmsMrkAwareMasterKeyProvider.builder().buildStrict(identifier); // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.9 // = type=test // # To match the encrypted data key's // # provider ID MUST exactly match the value "aws-kms". final CannotUnwrapDataKeyException test = assertThrows( "Unable to decrypt any data keys", CannotUnwrapDataKeyException.class, () -> mkp.decryptDataKey(ALGORITHM_SUITE, Arrays.asList(edk), ENCRYPTION_CONTEXT)); assertEquals(0, test.getSuppressed().length); } @Test // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.9 // = type=test // # Additionally // # each provider info MUST be a valid AWS KMS ARN (aws-kms-key-arn.md#a- // # valid-aws-kms-arn) with a resource type of "key". public void provider_info_must_be_arn() { final String identifier = "arn:aws:kms:us-west-2:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574"; final String aliasArn = "arn:aws:kms:us-west-2:111122223333:alias/mrk-edb7fe6942894d32ac46dbb1c922d574"; final CryptoAlgorithm ALGORITHM_SUITE = CryptoAlgorithm.ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA256; final Map<String, String> ENCRYPTION_CONTEXT = Collections.singletonMap("myKey", "myValue"); final EncryptedDataKey edk = new KeyBlob("aws-kms", aliasArn.getBytes(StandardCharsets.UTF_8), new byte[10]); AwsKmsMrkAwareMasterKeyProvider mkp = AwsKmsMrkAwareMasterKeyProvider.builder().buildStrict(identifier); final IllegalStateException test = assertThrows( "Invalid provider info in message.", IllegalStateException.class, () -> mkp.decryptDataKey(ALGORITHM_SUITE, Arrays.asList(edk), ENCRYPTION_CONTEXT)); assertEquals(0, test.getSuppressed().length); } @Test // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.9 // = type=test // # If this attempt results in an error, then // # these errors MUST be collected. // // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.9 // = type=test // # If all the input encrypted data keys have been processed then this // # function MUST yield an error that includes all the collected errors. public void exception_wrapped() { final String identifier = "arn:aws:kms:us-west-2:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574"; final CryptoAlgorithm ALGORITHM_SUITE = CryptoAlgorithm.ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA256; final Map<String, String> ENCRYPTION_CONTEXT = Collections.singletonMap("myKey", "myValue"); final EncryptedDataKey edk = new KeyBlob("aws-kms", identifier.getBytes(StandardCharsets.UTF_8), new byte[10]); final RegionalClientSupplier supplier = mock(RegionalClientSupplier.class); final KmsClient client = mock(KmsClient.class); final String clientErrMsg = "asdf"; when(client.decrypt((DecryptRequest) any())) .thenThrow(AwsServiceException.builder().message(clientErrMsg).build()); when(supplier.getClient(any())).thenReturn(client); AwsKmsMrkAwareMasterKeyProvider mkp = AwsKmsMrkAwareMasterKeyProvider.builder() .customRegionalClientSupplier(supplier) .buildStrict(identifier); CannotUnwrapDataKeyException test = assertThrows( "Unable to decrypt any data keys", CannotUnwrapDataKeyException.class, () -> mkp.decryptDataKey(ALGORITHM_SUITE, Arrays.asList(edk), ENCRYPTION_CONTEXT)); assertEquals(1, test.getSuppressed().length); Throwable fromMasterKey = Arrays.stream(test.getSuppressed()).findFirst().get(); assertTrue(fromMasterKey instanceof CannotUnwrapDataKeyException); assertEquals(1, fromMasterKey.getSuppressed().length); Throwable fromClient = Arrays.stream(fromMasterKey.getSuppressed()).findFirst().get(); assertTrue(fromClient instanceof AwsServiceException); assertTrue(fromClient.getMessage().startsWith(clientErrMsg)); } } public static class clientFactory { @Test public void basic_use() { final ConcurrentHashMap<Region, KmsClient> cache = spy(new ConcurrentHashMap<>()); final Region region = Region.of("asdf"); final KmsClient test = AwsKmsMrkAwareMasterKeyProvider.Builder.clientFactory(cache, null).getClient(region); assertNotEquals(null, test); verify(cache, times(1)).containsKey(region); } @Test @DisplayName("Check for early return (Postcondition): If a client already exists, use that.") public void use_clients_that_exist() { final Region region = Region.of("asdf"); final ConcurrentHashMap<Region, KmsClient> cache = spy(new ConcurrentHashMap<>()); // Add something so we can verify that we get it final KmsClient client = mock(KmsClient.class); cache.put(region, client); final KmsClient test = AwsKmsMrkAwareMasterKeyProvider.Builder.clientFactory(cache, null).getClient(region); assertEquals(client, test); } @Test public void uses_builder_supplier() { final ConcurrentHashMap<Region, KmsClient> cache = spy(new ConcurrentHashMap<>()); final Region region = Region.of("asdf"); KmsClientBuilder builder = mock(KmsClientBuilder.class); KmsClient client = mock(KmsClient.class); ClientOverrideConfiguration.Builder overrideBuilder = mock(ClientOverrideConfiguration.Builder.class); when(builder.region(any())).thenReturn(builder); when(builder.build()).thenReturn(client); doAnswer( ans -> { Consumer<ClientOverrideConfiguration.Builder> consumer = ans.getArgument(0); consumer.accept(overrideBuilder); return builder; }) .when(builder) .overrideConfiguration((Consumer<ClientOverrideConfiguration.Builder>) any()); final KmsClient test = AwsKmsMrkAwareMasterKeyProvider.Builder.clientFactory(cache, () -> builder) .getClient(region); verify(builder, times(1)).build(); verify(overrideBuilder, times(1)).addExecutionInterceptor(any()); assertEquals(client, test); } } public static class getMasterKeysForEncryption { @Test public void basic_use() { final String identifier = "arn:aws:kms:us-west-2:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574"; final KmsClient client = spy(new MockKmsClient()); final RegionalClientSupplier supplier = mock(RegionalClientSupplier.class); when(supplier.getClient(Region.US_WEST_2)).thenReturn(client); final MasterKeyRequest request = MasterKeyRequest.newBuilder().build(); final AwsKmsMrkAwareMasterKeyProvider mkp = AwsKmsMrkAwareMasterKeyProvider.builder() .defaultRegion(Region.US_WEST_2) .customRegionalClientSupplier(supplier) .buildStrict(identifier); // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.8 // = type=test // # The input MUST be the same as the Master Key Provider Get Master Keys // # For Encryption (../master-key-provider-interface.md#get-master-keys- // # for-encryption) interface. // // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.8 // = type=test // # The output MUST be the same as the Master Key Provider Get Master // # Keys For Encryption (../master-key-provider-interface.md#get-master- // # keys-for-encryption) interface. final List<AwsKmsMrkAwareMasterKey> test = mkp.getMasterKeysForEncryption(request); // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.8 // = type=test // # If the configured mode is strict this function MUST return a // # list of master keys obtained by calling Get Master Key (aws-kms-mrk- // # aware-master-key-provider.md#get-master-key) for each AWS KMS key // # identifier in the configured key ids assertEquals(1, test.size()); assertEquals(identifier, test.get(0).getKeyId()); } @Test // = compliance/framework/aws-kms/aws-kms-mrk-aware-master-key-provider.txt#2.8 // = type=test // # If the configured mode is discovery the function MUST return an empty // # list. public void no_keys_is_empty_list() { final AwsKmsMrkAwareMasterKeyProvider mkp = AwsKmsMrkAwareMasterKeyProvider.builder().buildDiscovery(); final List<AwsKmsMrkAwareMasterKey> test = mkp.getMasterKeysForEncryption(MasterKeyRequest.newBuilder().build()); assertEquals(0, test.size()); } } }
741
0
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk/kmssdkv2/KmsMasterKeyTest.java
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package com.amazonaws.encryptionsdk.kmssdkv2; import static com.amazonaws.encryptionsdk.TestUtils.assertThrows; import static com.amazonaws.encryptionsdk.internal.RandomBytesGenerator.generate; import static org.junit.Assert.*; import static org.mockito.ArgumentMatchers.isA; import static org.mockito.Mockito.*; import com.amazonaws.encryptionsdk.*; import com.amazonaws.encryptionsdk.exception.CannotUnwrapDataKeyException; import com.amazonaws.encryptionsdk.internal.VersionInfo; import com.amazonaws.encryptionsdk.model.KeyBlob; import java.nio.charset.StandardCharsets; import java.util.*; import java.util.function.Supplier; import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec; import org.junit.Test; import org.mockito.ArgumentCaptor; import software.amazon.awssdk.awscore.AwsRequest; import software.amazon.awssdk.awscore.AwsRequestOverrideConfiguration; import software.amazon.awssdk.core.SdkBytes; import software.amazon.awssdk.services.kms.KmsClient; import software.amazon.awssdk.services.kms.model.*; public class KmsMasterKeyTest { private static final String AWS_KMS_PROVIDER_ID = "aws-kms"; private static final String OTHER_PROVIDER_ID = "not-aws-kms"; private static final CryptoAlgorithm ALGORITHM_SUITE = CryptoAlgorithm.ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA256; private static final SecretKey DATA_KEY = new SecretKeySpec( generate(ALGORITHM_SUITE.getDataKeyLength()), ALGORITHM_SUITE.getDataKeyAlgo()); private static final List<String> GRANT_TOKENS = Collections.singletonList("testGrantToken"); private static final Map<String, String> ENCRYPTION_CONTEXT = Collections.singletonMap("myKey", "myValue"); @Test public void testEncryptAndDecrypt() { KmsClient client = spy(new MockKmsClient()); Supplier supplier = mock(Supplier.class); when(supplier.get()).thenReturn(client); MasterKey otherMasterKey = mock(MasterKey.class); when(otherMasterKey.getProviderId()).thenReturn(OTHER_PROVIDER_ID); when(otherMasterKey.getKeyId()).thenReturn("someOtherId"); DataKey dataKey = new DataKey( DATA_KEY, new byte[0], OTHER_PROVIDER_ID.getBytes(StandardCharsets.UTF_8), otherMasterKey); MasterKeyProvider mkp = mock(MasterKeyProvider.class); when(mkp.getDefaultProviderId()).thenReturn(AWS_KMS_PROVIDER_ID); String keyId = client.createKey().keyMetadata().arn(); KmsMasterKey kmsMasterKey = KmsMasterKey.getInstance(supplier, keyId, mkp); kmsMasterKey.setGrantTokens(GRANT_TOKENS); DataKey<KmsMasterKey> encryptDataKeyResponse = kmsMasterKey.encryptDataKey(ALGORITHM_SUITE, ENCRYPTION_CONTEXT, dataKey); ArgumentCaptor<EncryptRequest> er = ArgumentCaptor.forClass(EncryptRequest.class); verify(client, times(1)).encrypt(er.capture()); EncryptRequest actualRequest = er.getValue(); assertEquals(keyId, actualRequest.keyId()); assertEquals(GRANT_TOKENS, actualRequest.grantTokens()); assertEquals(ENCRYPTION_CONTEXT, actualRequest.encryptionContext()); assertArrayEquals(DATA_KEY.getEncoded(), actualRequest.plaintext().asByteArray()); assertApiName(actualRequest); assertEquals(encryptDataKeyResponse.getMasterKey(), kmsMasterKey); assertEquals(AWS_KMS_PROVIDER_ID, encryptDataKeyResponse.getProviderId()); assertArrayEquals( keyId.getBytes(StandardCharsets.UTF_8), encryptDataKeyResponse.getProviderInformation()); assertNotNull(encryptDataKeyResponse.getEncryptedDataKey()); DataKey<KmsMasterKey> decryptDataKeyResponse = kmsMasterKey.decryptDataKey( ALGORITHM_SUITE, Collections.singletonList(encryptDataKeyResponse), ENCRYPTION_CONTEXT); ArgumentCaptor<DecryptRequest> decrypt = ArgumentCaptor.forClass(DecryptRequest.class); verify(client, times(1)).decrypt(decrypt.capture()); DecryptRequest actualDecryptRequest = decrypt.getValue(); assertArrayEquals( encryptDataKeyResponse.getProviderInformation(), actualDecryptRequest.keyId().getBytes(StandardCharsets.UTF_8)); assertEquals(GRANT_TOKENS, actualDecryptRequest.grantTokens()); assertEquals(ENCRYPTION_CONTEXT, actualDecryptRequest.encryptionContext()); assertArrayEquals( encryptDataKeyResponse.getEncryptedDataKey(), actualDecryptRequest.ciphertextBlob().asByteArray()); assertApiName(actualDecryptRequest); assertEquals(DATA_KEY, decryptDataKeyResponse.getKey()); assertArrayEquals( keyId.getBytes(StandardCharsets.UTF_8), decryptDataKeyResponse.getProviderInformation()); } @Test public void testGenerateAndDecrypt() { KmsClient client = spy(new MockKmsClient()); Supplier supplier = mock(Supplier.class); when(supplier.get()).thenReturn(client); MasterKeyProvider mkp = mock(MasterKeyProvider.class); when(mkp.getDefaultProviderId()).thenReturn(AWS_KMS_PROVIDER_ID); String keyId = client.createKey().keyMetadata().arn(); KmsMasterKey kmsMasterKey = KmsMasterKey.getInstance(supplier, keyId, mkp); kmsMasterKey.setGrantTokens(GRANT_TOKENS); DataKey<KmsMasterKey> generateDataKeyResponse = kmsMasterKey.generateDataKey(ALGORITHM_SUITE, ENCRYPTION_CONTEXT); ArgumentCaptor<GenerateDataKeyRequest> gr = ArgumentCaptor.forClass(GenerateDataKeyRequest.class); verify(client, times(1)).generateDataKey(gr.capture()); GenerateDataKeyRequest actualRequest = gr.getValue(); assertEquals(keyId, actualRequest.keyId()); assertEquals(GRANT_TOKENS, actualRequest.grantTokens()); assertEquals(ENCRYPTION_CONTEXT, actualRequest.encryptionContext()); assertEquals(ALGORITHM_SUITE.getDataKeyLength(), actualRequest.numberOfBytes().longValue()); assertApiName(actualRequest); assertNotNull(generateDataKeyResponse.getKey()); assertEquals( ALGORITHM_SUITE.getDataKeyLength(), generateDataKeyResponse.getKey().getEncoded().length); assertEquals(ALGORITHM_SUITE.getDataKeyAlgo(), generateDataKeyResponse.getKey().getAlgorithm()); assertNotNull(generateDataKeyResponse.getEncryptedDataKey()); DataKey<KmsMasterKey> decryptDataKeyResponse = kmsMasterKey.decryptDataKey( ALGORITHM_SUITE, Collections.singletonList(generateDataKeyResponse), ENCRYPTION_CONTEXT); ArgumentCaptor<DecryptRequest> decrypt = ArgumentCaptor.forClass(DecryptRequest.class); verify(client, times(1)).decrypt(decrypt.capture()); DecryptRequest actualDecryptRequest = decrypt.getValue(); assertArrayEquals( generateDataKeyResponse.getProviderInformation(), actualDecryptRequest.keyId().getBytes(StandardCharsets.UTF_8)); assertEquals(GRANT_TOKENS, actualDecryptRequest.grantTokens()); assertEquals(ENCRYPTION_CONTEXT, actualDecryptRequest.encryptionContext()); assertArrayEquals( generateDataKeyResponse.getEncryptedDataKey(), actualDecryptRequest.ciphertextBlob().asByteArray()); assertApiName(actualDecryptRequest); assertEquals(generateDataKeyResponse.getKey(), decryptDataKeyResponse.getKey()); assertArrayEquals( keyId.getBytes(StandardCharsets.UTF_8), decryptDataKeyResponse.getProviderInformation()); } @Test public void testEncryptWithRawKeyId() { KmsClient client = spy(new MockKmsClient()); Supplier supplier = mock(Supplier.class); when(supplier.get()).thenReturn(client); MasterKey otherMasterKey = mock(MasterKey.class); when(otherMasterKey.getProviderId()).thenReturn(OTHER_PROVIDER_ID); when(otherMasterKey.getKeyId()).thenReturn("someOtherId"); DataKey dataKey = new DataKey( DATA_KEY, new byte[0], OTHER_PROVIDER_ID.getBytes(StandardCharsets.UTF_8), otherMasterKey); MasterKeyProvider mkp = mock(MasterKeyProvider.class); when(mkp.getDefaultProviderId()).thenReturn(AWS_KMS_PROVIDER_ID); String keyId = client.createKey().keyMetadata().arn(); String rawKeyId = keyId.split("/")[1]; KmsMasterKey kmsMasterKey = KmsMasterKey.getInstance(supplier, rawKeyId, mkp); kmsMasterKey.setGrantTokens(GRANT_TOKENS); DataKey<KmsMasterKey> encryptDataKeyResponse = kmsMasterKey.encryptDataKey(ALGORITHM_SUITE, ENCRYPTION_CONTEXT, dataKey); ArgumentCaptor<EncryptRequest> er = ArgumentCaptor.forClass(EncryptRequest.class); verify(client, times(1)).encrypt(er.capture()); EncryptRequest actualRequest = er.getValue(); assertEquals(rawKeyId, actualRequest.keyId()); assertEquals(GRANT_TOKENS, actualRequest.grantTokens()); assertEquals(ENCRYPTION_CONTEXT, actualRequest.encryptionContext()); assertArrayEquals(DATA_KEY.getEncoded(), actualRequest.plaintext().asByteArray()); assertApiName(actualRequest); assertEquals(AWS_KMS_PROVIDER_ID, encryptDataKeyResponse.getProviderId()); assertArrayEquals( keyId.getBytes(StandardCharsets.UTF_8), encryptDataKeyResponse.getProviderInformation()); assertNotNull(encryptDataKeyResponse.getEncryptedDataKey()); } @Test public void testEncryptWrongKeyFormat() { SecretKey key = mock(SecretKey.class); when(key.getFormat()).thenReturn("BadFormat"); KmsClient client = spy(new MockKmsClient()); Supplier supplier = mock(Supplier.class); when(supplier.get()).thenReturn(client); MasterKey otherMasterKey = mock(MasterKey.class); when(otherMasterKey.getProviderId()).thenReturn(OTHER_PROVIDER_ID); when(otherMasterKey.getKeyId()).thenReturn("someOtherId"); DataKey dataKey = new DataKey( key, new byte[0], OTHER_PROVIDER_ID.getBytes(StandardCharsets.UTF_8), otherMasterKey); MasterKeyProvider mkp = mock(MasterKeyProvider.class); when(mkp.getDefaultProviderId()).thenReturn(AWS_KMS_PROVIDER_ID); String keyId = client.createKey().keyMetadata().arn(); KmsMasterKey kmsMasterKey = KmsMasterKey.getInstance(supplier, keyId, mkp); assertThrows( IllegalArgumentException.class, () -> kmsMasterKey.encryptDataKey(ALGORITHM_SUITE, ENCRYPTION_CONTEXT, dataKey)); } @Test public void testGenerateBadKmsKeyLength() { KmsClient client = spy(new MockKmsClient()); Supplier supplier = mock(Supplier.class); when(supplier.get()).thenReturn(client); MasterKeyProvider mkp = mock(MasterKeyProvider.class); when(mkp.getDefaultProviderId()).thenReturn(AWS_KMS_PROVIDER_ID); String keyId = client.createKey().keyMetadata().arn(); KmsMasterKey kmsMasterKey = KmsMasterKey.getInstance(supplier, keyId, mkp); GenerateDataKeyResponse badResponse = GenerateDataKeyResponse.builder() .keyId(keyId) .plaintext(SdkBytes.fromByteArray(new byte[ALGORITHM_SUITE.getDataKeyLength() + 1])) .build(); doReturn(badResponse).when(client).generateDataKey(isA(GenerateDataKeyRequest.class)); assertThrows( IllegalStateException.class, () -> kmsMasterKey.generateDataKey(ALGORITHM_SUITE, ENCRYPTION_CONTEXT)); } @Test public void testDecryptBadKmsKeyLength() { KmsClient client = spy(new MockKmsClient()); Supplier supplier = mock(Supplier.class); when(supplier.get()).thenReturn(client); MasterKeyProvider mkp = mock(MasterKeyProvider.class); when(mkp.getDefaultProviderId()).thenReturn(AWS_KMS_PROVIDER_ID); String keyId = client.createKey().keyMetadata().arn(); KmsMasterKey kmsMasterKey = KmsMasterKey.getInstance(supplier, keyId, mkp); DecryptResponse badResponse = DecryptResponse.builder() .keyId(keyId) .plaintext(SdkBytes.fromByteArray(new byte[ALGORITHM_SUITE.getDataKeyLength() + 1])) .build(); doReturn(badResponse).when(client).decrypt(isA(DecryptRequest.class)); EncryptedDataKey edk = new KeyBlob( AWS_KMS_PROVIDER_ID, keyId.getBytes(StandardCharsets.UTF_8), generate(ALGORITHM_SUITE.getDataKeyLength())); assertThrows( IllegalStateException.class, () -> kmsMasterKey.decryptDataKey( ALGORITHM_SUITE, Collections.singletonList(edk), ENCRYPTION_CONTEXT)); } @Test public void testDecryptMissingKmsKeyId() { KmsClient client = spy(new MockKmsClient()); Supplier supplier = mock(Supplier.class); when(supplier.get()).thenReturn(client); MasterKeyProvider mkp = mock(MasterKeyProvider.class); when(mkp.getDefaultProviderId()).thenReturn(AWS_KMS_PROVIDER_ID); String keyId = client.createKey().keyMetadata().arn(); KmsMasterKey kmsMasterKey = KmsMasterKey.getInstance(supplier, keyId, mkp); DecryptResponse badResponse = DecryptResponse.builder() .plaintext(SdkBytes.fromByteArray(new byte[ALGORITHM_SUITE.getDataKeyLength()])) .build(); doReturn(badResponse).when(client).decrypt(isA(DecryptRequest.class)); EncryptedDataKey edk = new KeyBlob( AWS_KMS_PROVIDER_ID, keyId.getBytes(StandardCharsets.UTF_8), generate(ALGORITHM_SUITE.getDataKeyLength())); assertThrows( IllegalStateException.class, "Received an empty keyId from KMS", () -> kmsMasterKey.decryptDataKey( ALGORITHM_SUITE, Collections.singletonList(edk), ENCRYPTION_CONTEXT)); } @Test public void testDecryptMismatchedKmsKeyId() { KmsClient client = spy(new MockKmsClient()); Supplier supplier = mock(Supplier.class); when(supplier.get()).thenReturn(client); MasterKeyProvider mkp = mock(MasterKeyProvider.class); when(mkp.getDefaultProviderId()).thenReturn(AWS_KMS_PROVIDER_ID); String keyId = client.createKey().keyMetadata().arn(); KmsMasterKey kmsMasterKey = KmsMasterKey.getInstance(supplier, keyId, mkp); DecryptResponse badResponse = DecryptResponse.builder() .keyId("mismatchedID") .plaintext(SdkBytes.fromByteArray(new byte[ALGORITHM_SUITE.getDataKeyLength()])) .build(); doReturn(badResponse).when(client).decrypt(isA(DecryptRequest.class)); EncryptedDataKey edk = new KeyBlob( AWS_KMS_PROVIDER_ID, keyId.getBytes(StandardCharsets.UTF_8), generate(ALGORITHM_SUITE.getDataKeyLength())); assertThrows( CannotUnwrapDataKeyException.class, () -> kmsMasterKey.decryptDataKey( ALGORITHM_SUITE, Collections.singletonList(edk), ENCRYPTION_CONTEXT)); } @Test public void testDecryptSkipsMismatchedIdEDK() { KmsClient client = spy(new MockKmsClient()); Supplier supplier = mock(Supplier.class); when(supplier.get()).thenReturn(client); MasterKeyProvider mkp = mock(MasterKeyProvider.class); when(mkp.getDefaultProviderId()).thenReturn(AWS_KMS_PROVIDER_ID); String keyId = client.createKey().keyMetadata().arn(); KmsMasterKey kmsMasterKey = KmsMasterKey.getInstance(supplier, keyId, mkp); // Mock expected KMS response to verify success if second EDK is ok, // and the mismatched EDK is skipped vs failing outright DecryptResponse kmsResponse = DecryptResponse.builder() .keyId(keyId) .plaintext(SdkBytes.fromByteArray(new byte[ALGORITHM_SUITE.getDataKeyLength()])) .build(); doReturn(kmsResponse).when(client).decrypt(isA(DecryptRequest.class)); EncryptedDataKey edk = new KeyBlob( AWS_KMS_PROVIDER_ID, keyId.getBytes(StandardCharsets.UTF_8), generate(ALGORITHM_SUITE.getDataKeyLength())); EncryptedDataKey mismatchedEDK = new KeyBlob( AWS_KMS_PROVIDER_ID, "mismatchedID".getBytes(StandardCharsets.UTF_8), generate(ALGORITHM_SUITE.getDataKeyLength())); DataKey<KmsMasterKey> decryptDataKeyResponse = kmsMasterKey.decryptDataKey( ALGORITHM_SUITE, Arrays.asList(mismatchedEDK, edk), ENCRYPTION_CONTEXT); ArgumentCaptor<DecryptRequest> decrypt = ArgumentCaptor.forClass(DecryptRequest.class); verify(client, times(1)).decrypt(decrypt.capture()); DecryptRequest actualDecryptRequest = decrypt.getValue(); assertArrayEquals( edk.getProviderInformation(), actualDecryptRequest.keyId().getBytes(StandardCharsets.UTF_8)); } private void assertApiName(AwsRequest request) { Optional<AwsRequestOverrideConfiguration> overrideConfig = request.overrideConfiguration(); assertTrue(overrideConfig.isPresent()); assertTrue( overrideConfig.get().apiNames().stream() .anyMatch( api -> api.name().equals(VersionInfo.apiName()) && api.version().equals(VersionInfo.versionNumber()))); } }
742
0
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk/kmssdkv2/KmsMasterKeyProviderTest.java
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package com.amazonaws.encryptionsdk.kmssdkv2; import static com.amazonaws.encryptionsdk.TestUtils.assertThrows; import static com.amazonaws.encryptionsdk.internal.RandomBytesGenerator.generate; import static org.junit.Assert.*; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.*; import com.amazonaws.encryptionsdk.CryptoAlgorithm; import com.amazonaws.encryptionsdk.DataKey; import com.amazonaws.encryptionsdk.EncryptedDataKey; import com.amazonaws.encryptionsdk.exception.CannotUnwrapDataKeyException; import com.amazonaws.encryptionsdk.internal.VersionInfo; import com.amazonaws.encryptionsdk.kms.DiscoveryFilter; import com.amazonaws.encryptionsdk.model.KeyBlob; import java.nio.charset.StandardCharsets; import java.util.*; import org.junit.Test; import org.junit.experimental.runners.Enclosed; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.mockito.ArgumentCaptor; import software.amazon.awssdk.awscore.AwsRequest; import software.amazon.awssdk.awscore.AwsRequestOverrideConfiguration; import software.amazon.awssdk.awscore.exception.AwsServiceException; import software.amazon.awssdk.core.SdkBytes; import software.amazon.awssdk.services.kms.model.DecryptRequest; import software.amazon.awssdk.services.kms.model.DecryptResponse; @RunWith(Enclosed.class) public class KmsMasterKeyProviderTest { private static final String AWS_PARTITION = "aws"; private static final String AWS_KMS_PROVIDER_ID = "aws-kms"; private static final String OTHER_PARTITION = "not-aws"; private static final String OTHER_PROVIDER_ID = "not-aws-kms"; private static final String ACCOUNT_ID = "999999999999"; private static final String OTHER_ACCOUNT_ID = "000000000000"; private static final String KEY_ID_1 = "arn:" + AWS_PARTITION + ":kms:us-east-1:" + ACCOUNT_ID + ":key/01234567-89ab-cdef-fedc-ba9876543210"; private static final String KEY_ID_2 = "arn:" + AWS_PARTITION + ":kms:us-east-1:" + ACCOUNT_ID + ":key/01234567-89ab-cdef-fedc-ba9876543211"; private static final String KEY_ID_3 = "arn:" + AWS_PARTITION + ":kms:us-east-1:" + ACCOUNT_ID + ":key/01234567-89ab-cdef-fedc-ba9876543212"; private static final String KEY_ID_4 = "arn:" + AWS_PARTITION + ":kms:us-east-1:" + OTHER_ACCOUNT_ID + ":key/01234567-89ab-cdef-fedc-ba9876543210"; private static final String KEY_ID_5 = "arn:" + OTHER_PARTITION + ":kms:us-east-1:" + ACCOUNT_ID + ":key/01234567-89ab-cdef-fedc-ba9876543210"; private static final CryptoAlgorithm ALGORITHM_SUITE = CryptoAlgorithm.ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA256; private static final Map<String, String> ENCRYPTION_CONTEXT = Collections.singletonMap("myKey", "myValue"); private static final EncryptedDataKey EDK_ID_1 = new KeyBlob( AWS_KMS_PROVIDER_ID, KEY_ID_1.getBytes(StandardCharsets.UTF_8), generate(ALGORITHM_SUITE.getDataKeyLength())); private static final EncryptedDataKey EDK_ID_1_OTHER_CIPHERTEXT = new KeyBlob( AWS_KMS_PROVIDER_ID, KEY_ID_1.getBytes(StandardCharsets.UTF_8), generate(ALGORITHM_SUITE.getDataKeyLength())); private static final EncryptedDataKey EDK_ID_2 = new KeyBlob( AWS_KMS_PROVIDER_ID, KEY_ID_2.getBytes(StandardCharsets.UTF_8), generate(ALGORITHM_SUITE.getDataKeyLength())); private static final EncryptedDataKey EDK_ID_3 = new KeyBlob( AWS_KMS_PROVIDER_ID, KEY_ID_3.getBytes(StandardCharsets.UTF_8), generate(ALGORITHM_SUITE.getDataKeyLength())); private static final EncryptedDataKey EDK_NON_ARN = new KeyBlob( AWS_KMS_PROVIDER_ID, "someAlias".getBytes(StandardCharsets.UTF_8), generate(ALGORITHM_SUITE.getDataKeyLength())); private static final EncryptedDataKey EDK_EMPTY_PROVIDER = new KeyBlob( "", "someId".getBytes(StandardCharsets.UTF_8), generate(ALGORITHM_SUITE.getDataKeyLength())); private static final EncryptedDataKey EDK_OTHER_PROVIDER = new KeyBlob( OTHER_PROVIDER_ID, "someId".getBytes(StandardCharsets.UTF_8), generate(ALGORITHM_SUITE.getDataKeyLength())); private static final EncryptedDataKey EDK_OTHER_ACCOUNT = new KeyBlob( AWS_KMS_PROVIDER_ID, KEY_ID_4.getBytes(StandardCharsets.UTF_8), generate(ALGORITHM_SUITE.getDataKeyLength())); private static final EncryptedDataKey EDK_OTHER_PARTITION = new KeyBlob( AWS_KMS_PROVIDER_ID, KEY_ID_5.getBytes(StandardCharsets.UTF_8), generate(ALGORITHM_SUITE.getDataKeyLength())); @RunWith(Parameterized.class) public static class ParameterizedDecryptTest { MKPTestConfiguration mkpConfig; List<EncryptedDataKey> inputEDKs; List<EncryptedDataKey> decryptableEDKs; private static class MKPTestConfiguration { // instance vars are public for easier access during testing public boolean isDiscovery; public DiscoveryFilter discoveryFilter; public List<String> keyIds; public MKPTestConfiguration( boolean isDiscovery, DiscoveryFilter discoveryFilter, List<String> keyIds) { this.isDiscovery = isDiscovery; this.discoveryFilter = discoveryFilter; this.keyIds = keyIds; } } public ParameterizedDecryptTest( MKPTestConfiguration mkpConfig, List<EncryptedDataKey> inputEDKs, List<EncryptedDataKey> decryptableEDKs) { this.mkpConfig = mkpConfig; this.inputEDKs = inputEDKs; this.decryptableEDKs = decryptableEDKs; } @Parameterized.Parameters(name = "{index}: mkpConfig={0}, inputEDKs={1}, decryptableEDKs={2}") public static Collection<Object[]> testCases() { // Create MKP configuration options to test against MKPTestConfiguration strict_oneCMK = new MKPTestConfiguration(false, null, Arrays.asList(KEY_ID_1)); MKPTestConfiguration strict_twoCMKs = new MKPTestConfiguration(false, null, Arrays.asList(KEY_ID_1, KEY_ID_2)); MKPTestConfiguration explicitDiscovery = new MKPTestConfiguration(true, null, null); MKPTestConfiguration explicitDiscovery_filter = new MKPTestConfiguration( true, new DiscoveryFilter(AWS_PARTITION, Arrays.asList(ACCOUNT_ID)), null); // Define all test cases Collection<Object[]> testCases = Arrays.asList( new Object[][] { // Test cases where no EDKs are expected to be decrypted {strict_oneCMK, Collections.emptyList(), Collections.emptyList()}, {strict_oneCMK, Arrays.asList(EDK_ID_2), Collections.emptyList()}, {strict_oneCMK, Arrays.asList(EDK_ID_2, EDK_ID_3), Collections.emptyList()}, {strict_twoCMKs, Collections.emptyList(), Collections.emptyList()}, {strict_twoCMKs, Arrays.asList(EDK_ID_3), Collections.emptyList()}, { strict_twoCMKs, Arrays.asList(EDK_ID_3, EDK_OTHER_PROVIDER), Collections.emptyList() }, {explicitDiscovery, Collections.emptyList(), Collections.emptyList()}, {explicitDiscovery, Arrays.asList(EDK_OTHER_PROVIDER), Collections.emptyList()}, {explicitDiscovery, Arrays.asList(EDK_EMPTY_PROVIDER), Collections.emptyList()}, { explicitDiscovery, Arrays.asList(EDK_OTHER_PROVIDER, EDK_EMPTY_PROVIDER), Collections.emptyList() }, {explicitDiscovery_filter, Collections.emptyList(), Collections.emptyList()}, { explicitDiscovery_filter, Arrays.asList(EDK_OTHER_PROVIDER), Collections.emptyList() }, { explicitDiscovery_filter, Arrays.asList(EDK_EMPTY_PROVIDER), Collections.emptyList() }, {explicitDiscovery_filter, Arrays.asList(EDK_NON_ARN), Collections.emptyList()}, { explicitDiscovery_filter, Arrays.asList(EDK_OTHER_PARTITION), Collections.emptyList() }, { explicitDiscovery_filter, Arrays.asList(EDK_OTHER_ACCOUNT), Collections.emptyList() }, { explicitDiscovery_filter, Arrays.asList(EDK_OTHER_PROVIDER, EDK_EMPTY_PROVIDER), Collections.emptyList() }, // Test cases where one EDK is expected to be decryptable {strict_oneCMK, Arrays.asList(EDK_ID_1), Arrays.asList(EDK_ID_1)}, {strict_oneCMK, Arrays.asList(EDK_ID_2, EDK_ID_1), Arrays.asList(EDK_ID_1)}, {strict_oneCMK, Arrays.asList(EDK_ID_1, EDK_ID_2), Arrays.asList(EDK_ID_1)}, {strict_twoCMKs, Arrays.asList(EDK_ID_1), Arrays.asList(EDK_ID_1)}, {strict_twoCMKs, Arrays.asList(EDK_ID_2), Arrays.asList(EDK_ID_2)}, {strict_twoCMKs, Arrays.asList(EDK_ID_3, EDK_ID_1), Arrays.asList(EDK_ID_1)}, {strict_twoCMKs, Arrays.asList(EDK_ID_1, EDK_ID_3), Arrays.asList(EDK_ID_1)}, {explicitDiscovery, Arrays.asList(EDK_ID_1), Arrays.asList(EDK_ID_1)}, { explicitDiscovery, Arrays.asList(EDK_OTHER_PROVIDER, EDK_ID_1), Arrays.asList(EDK_ID_1) }, { explicitDiscovery, Arrays.asList(EDK_ID_1, EDK_OTHER_PROVIDER), Arrays.asList(EDK_ID_1) }, {explicitDiscovery_filter, Arrays.asList(EDK_ID_1), Arrays.asList(EDK_ID_1)}, { explicitDiscovery_filter, Arrays.asList(EDK_OTHER_ACCOUNT, EDK_ID_1), Arrays.asList(EDK_ID_1) }, { explicitDiscovery_filter, Arrays.asList(EDK_ID_1, EDK_OTHER_ACCOUNT), Arrays.asList(EDK_ID_1) }, // Test cases where multiple EDKs are expected to be decryptable { strict_oneCMK, Arrays.asList(EDK_ID_1, EDK_ID_1_OTHER_CIPHERTEXT), Arrays.asList(EDK_ID_1, EDK_ID_1_OTHER_CIPHERTEXT) }, { strict_twoCMKs, Arrays.asList(EDK_ID_1, EDK_ID_2), Arrays.asList(EDK_ID_1, EDK_ID_2) }, { explicitDiscovery, Arrays.asList(EDK_ID_1, EDK_ID_2), Arrays.asList(EDK_ID_1, EDK_ID_2) }, { explicitDiscovery_filter, Arrays.asList(EDK_ID_1, EDK_ID_2), Arrays.asList(EDK_ID_1, EDK_ID_2) }, }); return testCases; } @SuppressWarnings("deprecation") private KmsMasterKeyProvider constructMKPForTest( MKPTestConfiguration mkpConfig, RegionalClientSupplier supplier) { KmsMasterKeyProvider.Builder builder = KmsMasterKeyProvider.builder().customRegionalClientSupplier(supplier); KmsMasterKeyProvider mkp; if (mkpConfig.isDiscovery && mkpConfig.discoveryFilter == null) { mkp = builder.buildDiscovery(); } else if (mkpConfig.isDiscovery) { mkp = builder.buildDiscovery(mkpConfig.discoveryFilter); } else { mkp = builder.buildStrict(mkpConfig.keyIds); } return mkp; } @Test public void testDecrypt() throws Exception { MockKmsClient client = spy(new MockKmsClient()); RegionalClientSupplier supplier = mock(RegionalClientSupplier.class); when(supplier.getClient(any())).thenReturn(client); // create MKP to test KmsMasterKeyProvider mkp = constructMKPForTest(mkpConfig, supplier); // if we expect none of them to decrypt, just test that we get the correct // failure and KMS was not called if (decryptableEDKs.size() <= 0) { assertThrows( CannotUnwrapDataKeyException.class, () -> mkp.decryptDataKey(ALGORITHM_SUITE, inputEDKs, ENCRYPTION_CONTEXT)); ArgumentCaptor<DecryptRequest> decrypt = ArgumentCaptor.forClass(DecryptRequest.class); verifyNoInteractions(client); return; } // Test that the mkp calls KMS for the first expected EDK EncryptedDataKey expectedEDK = decryptableEDKs.get(0); // mock KMS to return the KeyId for the expected EDK, // we verify that we call KMS with this KeyId, so this is ok DecryptResponse decryptResponse = DecryptResponse.builder() .keyId(new String(expectedEDK.getProviderInformation(), StandardCharsets.UTF_8)) .plaintext(SdkBytes.fromByteArray(new byte[ALGORITHM_SUITE.getDataKeyLength()])) .build(); doReturn(decryptResponse).when(client).decrypt(isA(DecryptRequest.class)); DataKey<KmsMasterKey> dataKeyResult = mkp.decryptDataKey(ALGORITHM_SUITE, inputEDKs, ENCRYPTION_CONTEXT); ArgumentCaptor<DecryptRequest> decrypt = ArgumentCaptor.forClass(DecryptRequest.class); verify(client, times(1)).decrypt(decrypt.capture()); verifyNoMoreInteractions(client); DecryptRequest actualRequest = decrypt.getValue(); assertArrayEquals( expectedEDK.getProviderInformation(), actualRequest.keyId().getBytes(StandardCharsets.UTF_8)); assertEquals(ENCRYPTION_CONTEXT, actualRequest.encryptionContext()); assertArrayEquals( expectedEDK.getEncryptedDataKey(), actualRequest.ciphertextBlob().asByteArray()); assertApiName(actualRequest); assertArrayEquals( expectedEDK.getProviderInformation(), dataKeyResult.getProviderInformation()); assertArrayEquals(expectedEDK.getEncryptedDataKey(), dataKeyResult.getEncryptedDataKey()); } @Test public void testDecryptKMSFailsOnce() throws Exception { MockKmsClient client = spy(new MockKmsClient()); RegionalClientSupplier supplier = mock(RegionalClientSupplier.class); when(supplier.getClient(any())).thenReturn(client); // create MKP to test KmsMasterKeyProvider mkp = constructMKPForTest(mkpConfig, supplier); // if we expect one or less KMS call, just test that we get the correct // failure and KMS was called the expected number of times if (decryptableEDKs.size() <= 1) { // Mock KMS to fail doThrow(AwsServiceException.builder().message("fail").build()) .when(client) .decrypt(isA(DecryptRequest.class)); assertThrows( CannotUnwrapDataKeyException.class, () -> mkp.decryptDataKey(ALGORITHM_SUITE, inputEDKs, ENCRYPTION_CONTEXT)); ArgumentCaptor<DecryptRequest> decrypt = ArgumentCaptor.forClass(DecryptRequest.class); verify(client, times(decryptableEDKs.size())).decrypt(decrypt.capture()); return; } EncryptedDataKey expectedFailedEDK = decryptableEDKs.get(0); EncryptedDataKey expectedSuccessfulEDK = decryptableEDKs.get(1); // Mock KMS to fail the first call then succeed for the second call DecryptResponse decryptResponse = DecryptResponse.builder() .keyId( new String( expectedSuccessfulEDK.getProviderInformation(), StandardCharsets.UTF_8)) .plaintext(SdkBytes.fromByteArray(new byte[ALGORITHM_SUITE.getDataKeyLength()])) .build(); doThrow(AwsServiceException.builder().message("fail").build()) .doReturn(decryptResponse) .when(client) .decrypt(isA(DecryptRequest.class)); DataKey<KmsMasterKey> dataKeyResult = mkp.decryptDataKey(ALGORITHM_SUITE, inputEDKs, ENCRYPTION_CONTEXT); ArgumentCaptor<DecryptRequest> decrypt = ArgumentCaptor.forClass(DecryptRequest.class); verify(client, times(2)).decrypt(decrypt.capture()); verifyNoMoreInteractions(client); List<DecryptRequest> actualRequests = decrypt.getAllValues(); DecryptRequest failedRequest = actualRequests.get(0); assertArrayEquals( expectedFailedEDK.getProviderInformation(), failedRequest.keyId().getBytes(StandardCharsets.UTF_8)); assertEquals(ENCRYPTION_CONTEXT, failedRequest.encryptionContext()); assertArrayEquals( expectedFailedEDK.getEncryptedDataKey(), failedRequest.ciphertextBlob().asByteArray()); assertApiName(failedRequest); DecryptRequest successfulRequest = actualRequests.get(1); assertArrayEquals( expectedSuccessfulEDK.getProviderInformation(), successfulRequest.keyId().getBytes(StandardCharsets.UTF_8)); assertEquals(ENCRYPTION_CONTEXT, successfulRequest.encryptionContext()); assertArrayEquals( expectedSuccessfulEDK.getEncryptedDataKey(), successfulRequest.ciphertextBlob().asByteArray()); assertApiName(successfulRequest); assertArrayEquals( expectedSuccessfulEDK.getProviderInformation(), dataKeyResult.getProviderInformation()); assertArrayEquals( expectedSuccessfulEDK.getEncryptedDataKey(), dataKeyResult.getEncryptedDataKey()); } private void assertApiName(AwsRequest request) { Optional<AwsRequestOverrideConfiguration> overrideConfig = request.overrideConfiguration(); assertTrue(overrideConfig.isPresent()); assertTrue( overrideConfig.get().apiNames().stream() .anyMatch( api -> api.name().equals(VersionInfo.apiName()) && api.version().equals(VersionInfo.versionNumber()))); } } public static class NonParameterized { @Test public void testBuildStrictWithNoCMKs() throws Exception { RegionalClientSupplier supplier = mock(RegionalClientSupplier.class); assertThrows( IllegalArgumentException.class, () -> KmsMasterKeyProvider.builder().customRegionalClientSupplier(supplier).buildStrict()); assertThrows( IllegalArgumentException.class, () -> KmsMasterKeyProvider.builder() .customRegionalClientSupplier(supplier) .buildStrict(Collections.emptyList())); assertThrows( IllegalArgumentException.class, () -> KmsMasterKeyProvider.builder() .customRegionalClientSupplier(supplier) .buildStrict((List<String>) null)); } @Test public void testBuildStrictWithNullCMK() throws Exception { RegionalClientSupplier supplier = mock(RegionalClientSupplier.class); assertThrows( IllegalArgumentException.class, () -> KmsMasterKeyProvider.builder() .customRegionalClientSupplier(supplier) .buildStrict((String) null)); assertThrows( IllegalArgumentException.class, () -> KmsMasterKeyProvider.builder() .customRegionalClientSupplier(supplier) .buildStrict(Arrays.asList((String) null))); } @Test public void testBuildDiscoveryWithFilter() throws Exception { RegionalClientSupplier supplier = mock(RegionalClientSupplier.class); KmsMasterKeyProvider mkp1 = KmsMasterKeyProvider.builder() .customRegionalClientSupplier(supplier) .buildDiscovery(new DiscoveryFilter("aws", Arrays.asList("accountId"))); assertNotNull(mkp1); } @Test public void testBuildDiscoveryWithNullFilter() throws Exception { RegionalClientSupplier supplier = mock(RegionalClientSupplier.class); assertThrows( IllegalArgumentException.class, () -> KmsMasterKeyProvider.builder() .customRegionalClientSupplier(supplier) .buildDiscovery(null)); } @Test public void testDecryptMismatchedKMSKeyIdResponse() throws Exception { MockKmsClient client = spy(new MockKmsClient()); RegionalClientSupplier supplier = mock(RegionalClientSupplier.class); when(supplier.getClient(any())).thenReturn(client); DecryptResponse badResponse = DecryptResponse.builder() .keyId(KEY_ID_2) .plaintext(SdkBytes.fromByteArray(new byte[ALGORITHM_SUITE.getDataKeyLength()])) .build(); doReturn(badResponse).when(client).decrypt(isA(DecryptRequest.class)); KmsMasterKeyProvider mkp = KmsMasterKeyProvider.builder().customRegionalClientSupplier(supplier).buildDiscovery(); assertThrows( CannotUnwrapDataKeyException.class, () -> mkp.decryptDataKey(ALGORITHM_SUITE, Arrays.asList(EDK_ID_1), ENCRYPTION_CONTEXT)); } } }
743
0
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk/multi/MultipleMasterKeyTest.java
package com.amazonaws.encryptionsdk.multi; import static com.amazonaws.encryptionsdk.internal.RandomBytesGenerator.generate; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import com.amazonaws.encryptionsdk.AwsCrypto; import com.amazonaws.encryptionsdk.CryptoResult; import com.amazonaws.encryptionsdk.MasterKey; import com.amazonaws.encryptionsdk.MasterKeyProvider; import com.amazonaws.encryptionsdk.internal.StaticMasterKey; import com.amazonaws.encryptionsdk.jce.JceMasterKey; import javax.crypto.spec.SecretKeySpec; import org.junit.Test; public class MultipleMasterKeyTest { private static final String WRAPPING_ALG = "AES/GCM/NoPadding"; private static final byte[] PLAINTEXT = generate(1024); @Test public void testMultipleJceKeys() { final SecretKeySpec k1 = new SecretKeySpec(generate(32), "AES"); final JceMasterKey mk1 = JceMasterKey.getInstance(k1, "jce", "1", WRAPPING_ALG); final SecretKeySpec k2 = new SecretKeySpec(generate(32), "AES"); final JceMasterKey mk2 = JceMasterKey.getInstance(k2, "jce", "2", WRAPPING_ALG); final MasterKeyProvider<JceMasterKey> mkp = MultipleProviderFactory.buildMultiProvider(JceMasterKey.class, mk1, mk2); AwsCrypto crypto = AwsCrypto.standard(); CryptoResult<byte[], JceMasterKey> ct = crypto.encryptData(mkp, PLAINTEXT); assertEquals(2, ct.getMasterKeyIds().size()); CryptoResult<byte[], JceMasterKey> result = crypto.decryptData(mkp, ct.getResult()); assertArrayEquals(PLAINTEXT, result.getResult()); // Only the first found key should be used assertEquals(1, result.getMasterKeys().size()); assertEquals(mk1, result.getMasterKeys().get(0)); assertMultiReturnsKeys(mkp, mk1, mk2); } @Test public void testMultipleJceKeysSingleDecrypt() { final SecretKeySpec k1 = new SecretKeySpec(generate(32), "AES"); final JceMasterKey mk1 = JceMasterKey.getInstance(k1, "jce", "1", WRAPPING_ALG); final SecretKeySpec k2 = new SecretKeySpec(generate(32), "AES"); final JceMasterKey mk2 = JceMasterKey.getInstance(k2, "jce", "2", WRAPPING_ALG); final MasterKeyProvider<JceMasterKey> mkp = MultipleProviderFactory.buildMultiProvider(JceMasterKey.class, mk1, mk2); AwsCrypto crypto = AwsCrypto.standard(); CryptoResult<byte[], JceMasterKey> ct = crypto.encryptData(mkp, PLAINTEXT); assertEquals(2, ct.getMasterKeyIds().size()); CryptoResult<byte[], JceMasterKey> result = crypto.decryptData(mk1, ct.getResult()); assertArrayEquals(PLAINTEXT, result.getResult()); // Only the first found key should be used assertEquals(1, result.getMasterKeys().size()); assertEquals(mk1, result.getMasterKeys().get(0)); result = crypto.decryptData(mk2, ct.getResult()); assertArrayEquals(PLAINTEXT, result.getResult()); // Only the first found key should be used assertEquals(1, result.getMasterKeys().size()); assertEquals(mk2, result.getMasterKeys().get(0)); } @Test public void testMixedKeys() { final SecretKeySpec k1 = new SecretKeySpec(generate(32), "AES"); final JceMasterKey mk1 = JceMasterKey.getInstance(k1, "jce", "1", WRAPPING_ALG); StaticMasterKey mk2 = new StaticMasterKey("mock1"); final MasterKeyProvider<?> mkp = MultipleProviderFactory.buildMultiProvider(mk1, mk2); AwsCrypto crypto = AwsCrypto.standard(); CryptoResult<byte[], ?> ct = crypto.encryptData(mkp, PLAINTEXT); assertEquals(2, ct.getMasterKeyIds().size()); CryptoResult<byte[], ?> result = crypto.decryptData(mkp, ct.getResult()); assertArrayEquals(PLAINTEXT, result.getResult()); // Only the first found key should be used assertEquals(1, result.getMasterKeys().size()); assertEquals(mk1, result.getMasterKeys().get(0)); assertMultiReturnsKeys(mkp, mk1, mk2); } @Test public void testMixedKeysSingleDecrypt() { final SecretKeySpec k1 = new SecretKeySpec(generate(32), "AES"); final JceMasterKey mk1 = JceMasterKey.getInstance(k1, "jce", "1", WRAPPING_ALG); StaticMasterKey mk2 = new StaticMasterKey("mock1"); final MasterKeyProvider<?> mkp = MultipleProviderFactory.buildMultiProvider(mk1, mk2); AwsCrypto crypto = AwsCrypto.standard(); CryptoResult<byte[], ?> ct = crypto.encryptData(mkp, PLAINTEXT); assertEquals(2, ct.getMasterKeyIds().size()); CryptoResult<byte[], ?> result = crypto.decryptData(mk1, ct.getResult()); assertArrayEquals(PLAINTEXT, result.getResult()); // Only the first found key should be used assertEquals(1, result.getMasterKeys().size()); assertEquals(mk1, result.getMasterKeys().get(0)); result = crypto.decryptData(mk2, ct.getResult()); assertArrayEquals(PLAINTEXT, result.getResult()); // Only the first found key should be used assertEquals(1, result.getMasterKeys().size()); assertEquals(mk2, result.getMasterKeys().get(0)); } private void assertMultiReturnsKeys(MasterKeyProvider<?> mkp, MasterKey<?>... mks) { for (MasterKey<?> mk : mks) { assertEquals(mk, mkp.getMasterKey(mk.getKeyId())); assertEquals(mk, mkp.getMasterKey(mk.getProviderId(), mk.getKeyId())); } } }
744
0
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk/internal/RandomBytesGenerator.java
/* * Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except * in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.amazonaws.encryptionsdk.internal; import java.security.SecureRandom; public class RandomBytesGenerator { private static final SecureRandom RND = new SecureRandom(); /* Some Providers (such as the FIPS certified Bouncy Castle) enforce a * maximum number of bytes that may be requested from SecureRandom. If * the requested len is larger than this value, the Secure Random will * be called multiple times to achieve the requested total length. */ private static final int MAX_BYTES = 1 << 15; /** * Generates a byte array of random data of the given length. * * @param len The length of the byte array. * @return The byte array. */ public static byte[] generate(final int len) { final byte[] result = new byte[len]; int bytesGenerated = 0; while (bytesGenerated < len) { final int requestSize = Math.min(MAX_BYTES, len - bytesGenerated); final byte[] request = new byte[requestSize]; RND.nextBytes(request); System.arraycopy(request, 0, result, bytesGenerated, requestSize); bytesGenerated += requestSize; } return result; } }
745
0
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk/internal/StaticMasterKey.java
package com.amazonaws.encryptionsdk.internal; import com.amazonaws.encryptionsdk.CryptoAlgorithm; import com.amazonaws.encryptionsdk.DataKey; import com.amazonaws.encryptionsdk.EncryptedDataKey; import com.amazonaws.encryptionsdk.MasterKey; import com.amazonaws.encryptionsdk.exception.AwsCryptoException; import com.amazonaws.encryptionsdk.exception.UnsupportedProviderException; import java.nio.charset.StandardCharsets; import java.security.GeneralSecurityException; import java.security.KeyFactory; import java.security.PrivateKey; import java.security.PublicKey; import java.security.SecureRandom; import java.security.spec.KeySpec; import java.security.spec.PKCS8EncodedKeySpec; import java.security.spec.X509EncodedKeySpec; import java.util.Collection; import java.util.Map; import java.util.Objects; import javax.annotation.Nonnull; import javax.annotation.concurrent.NotThreadSafe; import javax.crypto.Cipher; import javax.crypto.KeyGenerator; import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec; /** * Static implementation of the {@link MasterKey} interface that should only used for unit-tests. * * <p>Contains a statically defined asymmetric master key-pair that can be used to encrypt and * decrypt (randomly generated) symmetric data key. * * <p> * * @author patye */ @NotThreadSafe public class StaticMasterKey extends MasterKey<StaticMasterKey> { private static final String PROVIDER_ID = "static_provider"; /** Generates random strings that can be used to create data keys. */ private static final SecureRandom SRAND = new SecureRandom(); /** Encryption algorithm for the master key-pair */ private static final String MASTER_KEY_ENCRYPTION_ALGORITHM = "RSA/ECB/PKCS1Padding"; /** Encryption algorithm for the KeyFactory */ private static final String MASTER_KEY_ALGORITHM = "RSA"; /** Encryption algorithm for the randomly generated data key */ private static final String DATA_KEY_ENCRYPTION_ALGORITHM = "AES"; /** The ID of the master key */ @Nonnull private String keyId_; /** * The {@link Cipher} object created with the public part of the master-key. It's used to encrypt * data keys. */ @Nonnull private final Cipher masterKeyEncryptionCipher_; /** * The {@link Cipher} object created with the private part of the master-key. It's used to decrypt * encrypted data keys. */ @Nonnull private final Cipher masterKeyDecryptionCipher_; /** Generates random data keys. */ @Nonnull private KeyGenerator keyGenerator_; /** * Creates a new object that encrypts the data key with a master key whose id is {@code keyId}. * * <p>The value of {@code keyId} does not affect how the data key will be generated or encrypted. * The {@code keyId} forms part of the header of the encrypted data, and is used to ensure that * the header cannot be tempered with. */ public StaticMasterKey(@Nonnull final String keyId) { this.keyId_ = Objects.requireNonNull(keyId); try { KeyFactory keyFactory = KeyFactory.getInstance(MASTER_KEY_ALGORITHM); KeySpec publicKeySpec = new X509EncodedKeySpec(publicKey_v1); PublicKey pubKey = keyFactory.generatePublic(publicKeySpec); KeySpec privateKeySpec = new PKCS8EncodedKeySpec(privateKey_v1); PrivateKey privKey = keyFactory.generatePrivate(privateKeySpec); masterKeyEncryptionCipher_ = Cipher.getInstance(MASTER_KEY_ENCRYPTION_ALGORITHM); masterKeyEncryptionCipher_.init(Cipher.ENCRYPT_MODE, pubKey); masterKeyDecryptionCipher_ = Cipher.getInstance(MASTER_KEY_ENCRYPTION_ALGORITHM); masterKeyDecryptionCipher_.init(Cipher.DECRYPT_MODE, privKey); } catch (GeneralSecurityException ex) { throw new RuntimeException(ex); } } /** * Changes the {@link #keyId_}. This method is expected to be used to test that header of an * encrypted message cannot be tempered with. */ public void setKeyId(@Nonnull String keyId) { this.keyId_ = Objects.requireNonNull(keyId); } @Override public String getProviderId() { return PROVIDER_ID; } @Override public String getKeyId() { return keyId_; } @Override public DataKey<StaticMasterKey> generateDataKey( CryptoAlgorithm algorithm, Map<String, String> encryptionContext) { try { this.keyGenerator_ = KeyGenerator.getInstance(DATA_KEY_ENCRYPTION_ALGORITHM); this.keyGenerator_.init(algorithm.getDataKeyLength() * 8, SRAND); SecretKey key = new SecretKeySpec(keyGenerator_.generateKey().getEncoded(), algorithm.getDataKeyAlgo()); byte[] encryptedKey = masterKeyEncryptionCipher_.doFinal(key.getEncoded()); return new DataKey<>(key, encryptedKey, keyId_.getBytes(StandardCharsets.UTF_8), this); } catch (GeneralSecurityException ex) { throw new RuntimeException(ex); } } @Override public DataKey<StaticMasterKey> encryptDataKey( CryptoAlgorithm algorithm, Map<String, String> encryptionContext, DataKey<?> dataKey) { try { byte[] unencryptedKey = dataKey.getKey().getEncoded(); byte[] encryptedKey = masterKeyEncryptionCipher_.doFinal(unencryptedKey); SecretKey newKey = new SecretKeySpec(dataKey.getKey().getEncoded(), algorithm.getDataKeyAlgo()); return new DataKey<>(newKey, encryptedKey, keyId_.getBytes(StandardCharsets.UTF_8), this); } catch (GeneralSecurityException ex) { throw new RuntimeException(ex); } } @Override public DataKey<StaticMasterKey> decryptDataKey( CryptoAlgorithm algorithm, Collection<? extends EncryptedDataKey> encryptedDataKeys, Map<String, String> encryptionContext) throws UnsupportedProviderException, AwsCryptoException { try { for (EncryptedDataKey edk : encryptedDataKeys) { if (keyId_.equals(new String(edk.getProviderInformation(), StandardCharsets.UTF_8))) { byte[] unencryptedDataKey = masterKeyDecryptionCipher_.doFinal(edk.getEncryptedDataKey()); SecretKey key = new SecretKeySpec(unencryptedDataKey, algorithm.getDataKeyAlgo()); return new DataKey<>(key, edk.getEncryptedDataKey(), edk.getProviderInformation(), this); } } } catch (GeneralSecurityException ex) { throw new RuntimeException(ex); } return null; } /** Statically configured private key. */ private static final byte[] privateKey_v1 = Utils.decodeBase64String( "MIICdQIBADANBgkqhkiG9w0BAQEFAASCAl8wggJbAgEAAoGBAKLpwqjYtYExVilW/Hg0ogWv9xZ+" + "THj4IzvISLlPtK8W6KXMcqukfuxdYmndPv8UD1DbdHFYSSistdqoBN32vVQOQnJZyYm45i2TDOV0" + "M2DtHtR6aMMlBLGtdPeeaT88nQfI1ORjRDyR1byMwomvmKifZYga6FjLt/sgqfSE9BUnAgMBAAEC" + "gYAqnewGL2qLuVRIzDCPYXVg938zqyZmHsNYyDP+BhPGGcASX0FAFW/+dQ9hkjcAk0bOaBo17Fp3" + "AXcxE/Lx/bHY+GWZ0wOJfl3aJBVJOpW8J6kwu68BUCmuFtRgbLSFu5+fbey3pKafYSptbX1fAI+z" + "hTx+a9B8pnn79ad4ziJ2QQJBAM+YHPGAEbr5qcNkwyy0xZgR/TLlcW2NQUt8HZpmErdX6d328iBC" + "SPb8+whXxCXZC3Mr+35IZ1pxxf0go/zGQv0CQQDI5oH0z1CKxoT6ErswNzB0oHxq/wD5mhutyqHa" + "mxbG5G3fN7I2IclwaXEA2eutIKxFMQNZYsX5mNYsrveSKivzAkABiujUJpZ7JDXNvObyYxmAyslt" + "4mSYYs9UZ0S1DAMhl6amPpqIANYX98NJyZUsjtNV9MK2qoUSF/xXqDFvxG1lAkBhP5Ow2Zn3U1mT" + "Y/XQxSZjjjwr3vyt1neHjQsEMwa3iGPXJbLSmVBVZfUZoGOBDsvVQoCIiFOlGuKyBpA45MkZAkAH" + "ksUrS9xLrDIUOI2BzMNRsK0bH7KJ+PFxm2SBgJOF9+Uf2A9LIP4IvESZq+ufp6c8YaqgR6Id1vws" + "7rUyGoa5"); /** Statically configured public key. */ private static final byte[] publicKey_v1 = Utils.decodeBase64String( "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCi6cKo2LWBMVYpVvx4NKIFr/cWfkx4+CM7yEi5" + "T7SvFuilzHKrpH7sXWJp3T7/FA9Q23RxWEkorLXaqATd9r1UDkJyWcmJuOYtkwzldDNg7R7UemjD" + "JQSxrXT3nmk/PJ0HyNTkY0Q8kdW8jMKJr5ion2WIGuhYy7f7IKn0hPQVJwIDAQAB"); }
746
0
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk/internal/VersionInfoTest.java
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package com.amazonaws.encryptionsdk.internal; import static org.junit.Assert.assertTrue; import org.junit.Test; public class VersionInfoTest { @Test public void basic_use() { final String userAgent = VersionInfo.loadUserAgent(); assertTrue(userAgent.startsWith(VersionInfo.USER_AGENT_PREFIX)); assertTrue(!userAgent.equals(VersionInfo.USER_AGENT_PREFIX + VersionInfo.UNKNOWN_VERSION)); } }
747
0
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk/internal/CommittedKeyTest.java
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package com.amazonaws.encryptionsdk.internal; import static com.amazonaws.encryptionsdk.TestUtils.assertThrows; import static com.amazonaws.encryptionsdk.TestUtils.insecureRandomBytes; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import com.amazonaws.encryptionsdk.CryptoAlgorithm; import com.amazonaws.encryptionsdk.TestUtils; import java.io.ByteArrayOutputStream; import java.io.DataOutputStream; import java.nio.charset.StandardCharsets; import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec; import org.bouncycastle.util.Arrays; import org.junit.Test; public class CommittedKeyTest { @Test public void testGenerate() { final CryptoAlgorithm algorithm = TestUtils.messageWithCommitKeyCryptoAlgorithm; SecretKeySpec secretKey = new SecretKeySpec( Utils.decodeBase64String(TestUtils.messageWithCommitKeyDEKBase64), algorithm.getDataKeyAlgo()); CommittedKey committedKey = CommittedKey.generate( algorithm, secretKey, Utils.decodeBase64String(TestUtils.messageWithCommitKeyMessageIdBase64)); assertNotNull(committedKey); assertEquals( TestUtils.messageWithCommitKeyCryptoAlgorithm.getKeyAlgo(), committedKey.getKey().getAlgorithm()); assertArrayEquals( Utils.decodeBase64String(TestUtils.messageWithCommitKeyCommitmentBase64), committedKey.getCommitment()); } @Test public void testGenerateBadNonceLen() { final CryptoAlgorithm algorithm = TestUtils.messageWithCommitKeyCryptoAlgorithm; SecretKeySpec secretKey = new SecretKeySpec( Utils.decodeBase64String(TestUtils.messageWithCommitKeyDEKBase64), algorithm.getDataKeyAlgo()); assertThrows( IllegalArgumentException.class, "Invalid nonce size", () -> CommittedKey.generate( algorithm, secretKey, new byte[algorithm.getCommitmentNonceLength() + 1])); } @Test public void testGenerateIncorrectMismatchedKeySpecAlgorithm() { final CryptoAlgorithm algorithm = TestUtils.messageWithCommitKeyCryptoAlgorithm; SecretKeySpec secretKey = new SecretKeySpec(new byte[algorithm.getDataKeyLength()], "incorrectAlgorithm"); assertThrows( IllegalArgumentException.class, "DataKey of incorrect algorithm.", () -> CommittedKey.generate( algorithm, secretKey, new byte[algorithm.getCommitmentNonceLength()])); } @Test public void testGenerateIncorrectDataKeyLenForAlgorithm() { final CryptoAlgorithm algorithm = TestUtils.messageWithCommitKeyCryptoAlgorithm; SecretKeySpec secretKey = new SecretKeySpec(new byte[algorithm.getDataKeyLength() + 1], algorithm.getDataKeyAlgo()); assertThrows( IllegalArgumentException.class, "DataKey of incorrect length.", () -> CommittedKey.generate( algorithm, secretKey, new byte[algorithm.getCommitmentNonceLength()])); } @Test public void testGenerateNonCommittingAlgorithm() { final CryptoAlgorithm algorithm = CryptoAlgorithm.ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA256; SecretKeySpec secretKey = new SecretKeySpec(new byte[algorithm.getDataKeyLength()], algorithm.getDataKeyAlgo()); assertThrows( IllegalArgumentException.class, "Algorithm does not support key commitment.", () -> CommittedKey.generate( algorithm, secretKey, new byte[algorithm.getCommitmentNonceLength()])); } @Test public void testGenerateCommittedKeySmokeTest() throws Exception { // This test intentionally using different techniques // to assemble the labels and constants. // Commitment Nonce N1 is equal to the Message Id which is a 32 byte random value. // Normally this needs to be cryptographically secure, but we can relax this for improved // performance in testing. final byte[] n1 = insecureRandomBytes(32); // Hash for HKDF is SHA-512 final HmacKeyDerivationFunction hkdf = HmacKeyDerivationFunction.getInstance("HmacSHA512"); // K_R (Raw keying material, a.k.a. data key) is 256 bits (32 bytes) // Normally this needs to be cryptographically secure, but we can relax this for improved // performance in testing. final byte[] k_r = insecureRandomBytes(32); final SecretKey k_rKey = new SecretKeySpec(k_r, "HkdfSHA512"); // We also need K_R in this format for later use // Output key size for Encryption Key is 256 bits (32 bytes) final int l_e = 32; // Output key size for Commitment Value is 256 bits (32 bytes) final int l_c = 32; // KeyLabel is "DERIVEKEY" as UTF-8 encoded bytes final byte[] keyLabel = "DERIVEKEY".getBytes(StandardCharsets.UTF_8); // CommitLabel is "COMMITKEY" as UTF-8 encoded bytes final byte[] commitLabel = "COMMITKEY".getBytes(StandardCharsets.UTF_8); // PRK is HKDF-Extract(salt=N_1, initialKeyingMaterial=K_R) hkdf.init(k_r /* IKM */, n1 /* Salt */); // Not final because we'll rerun this with the other algorithm CryptoAlgorithm alg = CryptoAlgorithm.ALG_AES_256_GCM_HKDF_SHA512_COMMIT_KEY; // Info for K_E is Algorithm ID || KeyLabel. // We intentionally construct this in a different manner from the tested implemention. // This technique is harder to get wrong but less performant. ByteArrayOutputStream baos = new ByteArrayOutputStream(); DataOutputStream out = new DataOutputStream(baos); out.writeShort(alg.getValue()); out.write(keyLabel); out.close(); // K_E := HKDF-Expand(prk=PRK, info=Algorithm ID || KeyLabel, L=L_E) byte[] k_e = hkdf.deriveKey(baos.toByteArray(), l_e); // K_C = HKDF-Expand(prk=PRK, info=CommitLabel, L=LC) final byte[] k_c = hkdf.deriveKey(commitLabel, l_c); // Now that we have the expected values, test reality CommittedKey committedKey = CommittedKey.generate(alg, k_rKey, n1); assertArrayEquals("K_C for " + alg, k_c, committedKey.getCommitment()); assertArrayEquals("K_E for " + alg, k_e, committedKey.getKey().getEncoded()); // Now test it with the second algorithm. // Since the commitment value doesn't include the algorithm Id, // K_C should remain unchanged and only K_E should vary. alg = CryptoAlgorithm.ALG_AES_256_GCM_HKDF_SHA512_COMMIT_KEY_ECDSA_P384; baos = new ByteArrayOutputStream(); out = new DataOutputStream(baos); out.writeShort(alg.getValue()); out.write(keyLabel); out.close(); final byte[] k_e2 = hkdf.deriveKey(baos.toByteArray(), l_e); // Now that we have the expected values, test reality committedKey = CommittedKey.generate(alg, k_rKey, n1); assertArrayEquals("K_C for " + alg, k_c, committedKey.getCommitment()); assertArrayEquals("K_E for " + alg, k_e2, committedKey.getKey().getEncoded()); assertFalse("K_E must be different for different algorithms", Arrays.areEqual(k_e, k_e2)); } }
748
0
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk/internal/UtilsTest.java
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package com.amazonaws.encryptionsdk.internal; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertTrue; import java.math.BigInteger; import java.nio.charset.StandardCharsets; import org.junit.Test; /** Unit tests for {@link Utils} */ public class UtilsTest { @Test public void compareObjectIdentityTest() { assertNotEquals(0, Utils.compareObjectIdentity(null, new Object())); assertNotEquals(0, Utils.compareObjectIdentity(new Object(), null)); assertEquals(0, Utils.compareObjectIdentity(Utils.class, Utils.class)); assertNotEquals(0, Utils.compareObjectIdentity(new Object(), new Object())); } @Test public void compareObjectIdentity_handlesHashCodeCollisions() { // With this large of an array, it is overwhelmingly likely that we will see two objects with // identical // identity hash codes. Object[] testArray = new Object[512_000]; for (int i = 0; i < testArray.length; i++) { testArray[i] = new Object(); } java.util.Arrays.sort(testArray, Utils::compareObjectIdentity); // Verify that we do not have any objects that are equal (compare to zero) in the array. // We know the primary sort is by hashcode, so we'll just do exhaustive comparison within each // hashcode. boolean sawCollison = false; for (int i = 0; i < testArray.length; i++) { int hashCode = System.identityHashCode(testArray[i]); int endOfHashGroup = i; while (endOfHashGroup + 1 < testArray.length && System.identityHashCode(testArray[endOfHashGroup + 1]) == hashCode) { endOfHashGroup++; } if (i != endOfHashGroup) { sawCollison = true; } for (int a = i; a <= endOfHashGroup; a++) { for (int b = a + 1; b <= endOfHashGroup; b++) { if (a != b) { assertNotEquals(0, Utils.compareObjectIdentity(a, b)); } } } } assertTrue(sawCollison); } @Test public void testSaturatingAdd() { assertEquals(0, Utils.saturatingAdd(0, 0)); assertEquals(2, Utils.saturatingAdd(1, 1)); assertEquals(-2, Utils.saturatingAdd(-1, -1)); assertEquals(0, Utils.saturatingAdd(-1, +1)); assertEquals(0, Utils.saturatingAdd(+1, -1)); assertEquals(Long.MIN_VALUE, Utils.saturatingAdd(Long.MIN_VALUE + 1, -2)); assertEquals(Long.MAX_VALUE, Utils.saturatingAdd(Long.MAX_VALUE - 1, +2)); assertEquals(Long.MAX_VALUE, Utils.saturatingAdd(Long.MAX_VALUE, Long.MAX_VALUE)); assertEquals(Long.MIN_VALUE, Utils.saturatingAdd(Long.MIN_VALUE, Long.MIN_VALUE)); } /** Basic sanity check for our Base64 helper methods. */ @Test public void base64empty() { assertEquals("", Utils.encodeBase64String(new byte[] {})); assertArrayEquals(new byte[] {}, Utils.decodeBase64String("")); } /** Basic sanity check for our Base64 helper methods. */ @Test public void base64something() { byte[] data = "Lorem ipsum dolor sit amet".getBytes(StandardCharsets.UTF_8); String encoded = "TG9yZW0gaXBzdW0gZG9sb3Igc2l0IGFtZXQ="; assertEquals(encoded, Utils.encodeBase64String(data)); assertArrayEquals(data, Utils.decodeBase64String(encoded)); } @Test public void testBigIntegerToByteArray() { byte[] bytes = new byte[] {23, 47, 126, -42, 34}; assertArrayEquals( new byte[] {0, 0, 0, 23, 47, 126, -42, 34}, Utils.bigIntegerToByteArray(new BigInteger(bytes), 8)); assertArrayEquals( new byte[] {23, 47, 126, -42, 34}, Utils.bigIntegerToByteArray(new BigInteger(bytes), 5)); bytes = new byte[] {0, -47, 126, -42, 34}; assertArrayEquals( new byte[] {-47, 126, -42, 34}, Utils.bigIntegerToByteArray(new BigInteger(bytes), 4)); } @Test(expected = IllegalArgumentException.class) public void testBigIntegerToByteArray_InvalidLength() { byte[] bytes = new byte[] {0, -47, 126, -42, 34}; assertArrayEquals(bytes, Utils.bigIntegerToByteArray(new BigInteger(bytes), 3)); } @Test public void testArrayPrefixEquals() { byte[] a = new byte[] {10, 11, 12, 13, 14, 15}; byte[] b = new byte[] {10, 11, 12, 13, 20, 21, 22}; assertFalse(Utils.arrayPrefixEquals(null, b, 4)); assertFalse(Utils.arrayPrefixEquals(a, null, 4)); assertFalse(Utils.arrayPrefixEquals(a, b, a.length + 1)); assertTrue(Utils.arrayPrefixEquals(a, b, 4)); assertFalse(Utils.arrayPrefixEquals(a, b, 5)); } }
749
0
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk/internal/PrimitivesParserTest.java
/* * Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except * in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.amazonaws.encryptionsdk.internal; import static org.junit.Assert.assertEquals; import java.io.ByteArrayOutputStream; import java.io.DataOutputStream; import java.io.IOException; import org.junit.Test; public class PrimitivesParserTest { @Test public void testParseLong() throws IOException { final long[] tests = new long[] { Long.MIN_VALUE, Long.MAX_VALUE, -1, 0, 1, Long.MIN_VALUE + 1, Long.MAX_VALUE - 1 }; for (long x : tests) { try (final ByteArrayOutputStream baos = new ByteArrayOutputStream(); final DataOutputStream dos = new DataOutputStream(baos)) { dos.writeLong(x); dos.close(); assertEquals(x, PrimitivesParser.parseLong(baos.toByteArray(), 0)); } } } @Test public void testParseInt() throws IOException { final int[] tests = new int[] { Integer.MIN_VALUE, Integer.MAX_VALUE, -1, 0, 1, Integer.MIN_VALUE + 1, Integer.MAX_VALUE - 1 }; for (int x : tests) { try (final ByteArrayOutputStream baos = new ByteArrayOutputStream(); final DataOutputStream dos = new DataOutputStream(baos)) { dos.writeInt(x); dos.close(); assertEquals(x, PrimitivesParser.parseInt(baos.toByteArray(), 0)); } } } @Test public void testParseShort() throws IOException { for (int x = Short.MIN_VALUE; x < Short.MAX_VALUE; x++) { try (final ByteArrayOutputStream baos = new ByteArrayOutputStream(); final DataOutputStream dos = new DataOutputStream(baos)) { dos.writeShort(x); dos.close(); assertEquals((short) x, PrimitivesParser.parseShort(baos.toByteArray(), 0)); } } } @Test public void testParseUnsignedShort() throws IOException { for (int x = 0; x < Constants.UNSIGNED_SHORT_MAX_VAL; x++) { try (final ByteArrayOutputStream baos = new ByteArrayOutputStream(); final DataOutputStream dos = new DataOutputStream(baos)) { PrimitivesParser.writeUnsignedShort(dos, x); assertEquals(x, PrimitivesParser.parseUnsignedShort(baos.toByteArray(), 0)); } } } @Test public void testParseByte() throws IOException { for (int x = Byte.MIN_VALUE; x < Byte.MAX_VALUE; x++) { try (final ByteArrayOutputStream baos = new ByteArrayOutputStream(); final DataOutputStream dos = new DataOutputStream(baos)) { dos.writeByte(x); dos.close(); assertEquals((byte) x, PrimitivesParser.parseByte(baos.toByteArray(), 0)); } } } }
750
0
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk/internal/TestIOUtils.java
/* * Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except * in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.amazonaws.encryptionsdk.internal; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.security.DigestInputStream; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.util.Random; public class TestIOUtils { private static final SecureRandom rng_ = new SecureRandom(); public static byte[] generateRandomPlaintext(final int size) { return RandomBytesGenerator.generate(size); } /** * Generates and returns a string of the given {@code length}. * * <p>This function can be replaced by the RandomStringUtil class from Apache Commons. * * <p>This method re-implemented here to keep this library's dependency to a minimum which would * reduce friction when it's consumed by other packages. */ public static String generateRandomString(final int size) { StringBuilder sb = new StringBuilder(); Random rand = new Random(); for (int i = 0; i < size; i++) { int c = rand.nextInt(Byte.MAX_VALUE); c = c == 0 ? (c + 1) : c; sb.append((char) c); } return sb.toString(); } public static byte[] computeFileDigest(final String fileName) throws IOException { try { final FileInputStream fis = new FileInputStream(fileName); final MessageDigest md = MessageDigest.getInstance("SHA-256"); final DigestInputStream dis = new DigestInputStream(fis, md); final int readLen = 128; final byte[] readBytes = new byte[readLen]; while (dis.read(readBytes) != -1) {} dis.close(); return md.digest(); } catch (NoSuchAlgorithmException e) { // shouldn't get here since we hardcode the algorithm. } return null; } public static byte[] getSha256Hash(final byte[] input) { MessageDigest md = null; try { md = MessageDigest.getInstance("SHA-256"); } catch (NoSuchAlgorithmException e) { // should never get here. } return md.digest(input); } public static void generateFile(final String fileName, final long fileSize) throws IOException { final FileOutputStream fs = new FileOutputStream(fileName); final byte[] fileBytes = new byte[(int) fileSize]; rng_.nextBytes(fileBytes); fs.write(fileBytes); fs.close(); } public static void copyInStreamToOutStream( final InputStream inStream, final OutputStream outStream, final int readLen) throws IOException { final byte[] readBuffer = new byte[readLen]; int actualRead = 0; while (actualRead >= 0) { outStream.write(readBuffer, 0, actualRead); actualRead = inStream.read(readBuffer); } inStream.close(); outStream.close(); } public static void deleteDir(final File filePath) { if (filePath.exists()) { File[] files = filePath.listFiles(); for (int i = 0; i < files.length; i++) { if (files[i].isFile()) { files[i].delete(); } else { deleteDir(files[i]); } } } filePath.delete(); } public static void copyInStreamToOutStream( final InputStream inStream, final OutputStream outStream) throws IOException { final int readLen = 1024; // 1KB copyInStreamToOutStream(inStream, outStream, readLen); } }
751
0
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk/internal/FrameEncryptionHandlerTest.java
/* * Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except * in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.amazonaws.encryptionsdk.internal; import static com.amazonaws.encryptionsdk.TestUtils.assertThrows; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import com.amazonaws.encryptionsdk.AwsCrypto; import com.amazonaws.encryptionsdk.CryptoAlgorithm; import com.amazonaws.encryptionsdk.TestUtils; import com.amazonaws.encryptionsdk.model.CipherFrameHeaders; import java.lang.reflect.Field; import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec; import org.bouncycastle.util.encoders.Hex; import org.junit.Before; import org.junit.Test; public class FrameEncryptionHandlerTest { private final CryptoAlgorithm cryptoAlgorithm_ = TestUtils.DEFAULT_TEST_CRYPTO_ALG; private final byte[] messageId_ = RandomBytesGenerator.generate(cryptoAlgorithm_.getMessageIdLength()); private final byte nonceLen_ = cryptoAlgorithm_.getNonceLen(); private final byte[] dataKeyBytes_ = RandomBytesGenerator.generate(cryptoAlgorithm_.getKeyLength()); private final SecretKey encryptionKey_ = new SecretKeySpec(dataKeyBytes_, "AES"); private final int frameSize_ = AwsCrypto.getDefaultFrameSize(); private FrameEncryptionHandler frameEncryptionHandler_; @Before public void setUp() throws Exception { frameEncryptionHandler_ = new FrameEncryptionHandler( encryptionKey_, nonceLen_, cryptoAlgorithm_, messageId_, frameSize_); } @Test public void emptyOutBytes() { final int outLen = 0; final byte[] out = new byte[outLen]; final int processedLen = frameEncryptionHandler_.doFinal(out, 0); assertEquals(outLen, processedLen); } @Test public void correctIVsGenerated() throws Exception { byte[] buf = new byte[frameSize_ + 1024]; for (int i = 0; i <= 254; i++) { byte[] expectedNonce = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, (byte) (i + 1) }; generateTestBlock(buf); assertHeaderNonce(expectedNonce, buf); } generateTestBlock(buf); assertHeaderNonce( new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0 }, buf); } @Test public void encryptionHandlerEnforcesFrameLimits() throws Exception { // Skip to the second-to-last frame first. Actually getting there by encrypting block would take // a very long // time, so we'll reflect in; for a test that legitimately gets there, see the // FrameEncryptionHandlerVeryLongTest. Field f = FrameEncryptionHandler.class.getDeclaredField("frameNumber_"); f.setAccessible(true); f.set(frameEncryptionHandler_, 0xFFFF_FFFEL); byte[] buf = new byte[frameSize_ + 1024]; // Writing frame 0xFFFF_FFFE should succeed. generateTestBlock(buf); assertHeaderNonce(Hex.decode("0000000000000000FFFFFFFE"), buf); byte[] oldBuf = buf.clone(); // Writing the next frame must fail assertThrows(() -> generateTestBlock(buf)); // ... and must not produce any output assertArrayEquals(oldBuf, buf); // However we can still finish the encryption frameEncryptionHandler_.doFinal(buf, 0); assertHeaderNonce(Hex.decode("0000000000000000FFFFFFFF"), buf); } private void assertHeaderNonce(byte[] expectedNonce, byte[] buf) { CipherFrameHeaders headers = new CipherFrameHeaders(); headers.setNonceLength(cryptoAlgorithm_.getNonceLen()); headers.deserialize(buf, 0); assertArrayEquals(expectedNonce, headers.getNonce()); } private void generateTestBlock(byte[] buf) { frameEncryptionHandler_.processBytes(new byte[frameSize_], 0, frameSize_, buf, 0); } }
752
0
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk/internal/FrameEncryptionHandlerVeryLongTest.java
package com.amazonaws.encryptionsdk.internal; import static org.junit.Assert.fail; import com.amazonaws.encryptionsdk.CryptoAlgorithm; import com.amazonaws.encryptionsdk.model.CipherFrameHeaders; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.util.Arrays; import javax.crypto.spec.SecretKeySpec; import org.bouncycastle.util.encoders.Hex; import org.junit.Test; /* * This test exhaustively encrypts a 2^32 frame message, which takes approximately 2-3 hours on my hardware. Because of * this long test time, this test is not run as part of the normal suites. */ public class FrameEncryptionHandlerVeryLongTest { @Test public void exhaustiveIVCheck() throws Exception { CryptoAlgorithm algorithm = CryptoAlgorithm.ALG_AES_128_GCM_IV12_TAG16_NO_KDF; FrameEncryptionHandler frameEncryptionHandler_ = new FrameEncryptionHandler( new SecretKeySpec(new byte[16], "AES"), 12, algorithm, new byte[16], 1); byte[] buf = new byte[1024]; ByteBuffer expectedNonce = ByteBuffer.allocate(12); long lastIndex = 1; // starting index for the test long lastTS = System.nanoTime(); for (long i = lastIndex; i <= Constants.MAX_FRAME_NUMBER; i++) { Utils.clear(expectedNonce); expectedNonce.order(ByteOrder.BIG_ENDIAN); expectedNonce.putInt(0); expectedNonce.putLong(i); if (i != Constants.MAX_FRAME_NUMBER) { frameEncryptionHandler_.processBytes(buf, 0, 1, buf, 0); } else { frameEncryptionHandler_.doFinal(buf, 0); } CipherFrameHeaders headers = new CipherFrameHeaders(); headers.setNonceLength(algorithm.getNonceLen()); headers.deserialize(buf, 0); byte[] nonce = headers.getNonce(); byte[] expectedArray = expectedNonce.array(); if (!Arrays.equals(nonce, expectedArray)) { fail( String.format( "Index %08x bytes %s != %s", i, new String(Hex.encode(nonce)), new String(Hex.encode(expectedArray)))); } if ((i & 0xFFFFF) == 0) { // Print progress messages, since this test takes a _very_ long time to run. System.out.print( String.format( "%05.2f%% complete", 100 * (double) i / (double) Constants.MAX_FRAME_NUMBER)); long newTS = System.nanoTime(); System.out.println( String.format( " at a rate of %f/sec\n", (i - lastIndex) / ((newTS - lastTS) / 1_000_000_000.0))); lastTS = newTS; lastIndex = i; } } } }
753
0
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk/internal/HmacKeyDerivationFunctionTest.java
/* * Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except * in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.amazonaws.encryptionsdk.internal; import static org.junit.Assert.assertArrayEquals; import com.amazonaws.util.StringUtils; import org.junit.Test; public class HmacKeyDerivationFunctionTest { private static final testCase[] testCases = new testCase[] { new testCase( "HmacSHA256", fromCHex( "\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b" + "\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b"), fromCHex("\\x00\\x01\\x02\\x03\\x04\\x05\\x06\\x07\\x08\\x09\\x0a\\x0b\\x0c"), fromCHex("\\xf0\\xf1\\xf2\\xf3\\xf4\\xf5\\xf6\\xf7\\xf8\\xf9"), fromHex( "3CB25F25FAACD57A90434F64D0362F2A2D2D0A90CF1A5A4C5DB02D56ECC4C5BF34007208D5B887185865")), new testCase( "HmacSHA256", fromCHex( "\\x00\\x01\\x02\\x03\\x04\\x05\\x06\\x07\\x08\\x09\\x0a\\x0b\\x0c\\x0d" + "\\x0e\\x0f\\x10\\x11\\x12\\x13\\x14\\x15\\x16\\x17\\x18\\x19\\x1a\\x1b" + "\\x1c\\x1d\\x1e\\x1f\\x20\\x21\\x22\\x23\\x24\\x25\\x26\\x27\\x28\\x29" + "\\x2a\\x2b\\x2c\\x2d\\x2e\\x2f\\x30\\x31\\x32\\x33\\x34\\x35\\x36\\x37" + "\\x38\\x39\\x3a\\x3b\\x3c\\x3d\\x3e\\x3f\\x40\\x41\\x42\\x43\\x44\\x45" + "\\x46\\x47\\x48\\x49\\x4a\\x4b\\x4c\\x4d\\x4e\\x4f"), fromCHex( "\\x60\\x61\\x62\\x63\\x64\\x65\\x66\\x67\\x68\\x69\\x6a\\x6b\\x6c\\x6d" + "\\x6e\\x6f\\x70\\x71\\x72\\x73\\x74\\x75\\x76\\x77\\x78\\x79\\x7a\\x7b" + "\\x7c\\x7d\\x7e\\x7f\\x80\\x81\\x82\\x83\\x84\\x85\\x86\\x87\\x88\\x89" + "\\x8a\\x8b\\x8c\\x8d\\x8e\\x8f\\x90\\x91\\x92\\x93\\x94\\x95\\x96\\x97" + "\\x98\\x99\\x9a\\x9b\\x9c\\x9d\\x9e\\x9f\\xa0\\xa1\\xa2\\xa3\\xa4\\xa5" + "\\xa6\\xa7\\xa8\\xa9\\xaa\\xab\\xac\\xad\\xae\\xaf"), fromCHex( "\\xb0\\xb1\\xb2\\xb3\\xb4\\xb5\\xb6\\xb7\\xb8\\xb9\\xba\\xbb\\xbc\\xbd" + "\\xbe\\xbf\\xc0\\xc1\\xc2\\xc3\\xc4\\xc5\\xc6\\xc7\\xc8\\xc9\\xca\\xcb" + "\\xcc\\xcd\\xce\\xcf\\xd0\\xd1\\xd2\\xd3\\xd4\\xd5\\xd6\\xd7\\xd8\\xd9" + "\\xda\\xdb\\xdc\\xdd\\xde\\xdf\\xe0\\xe1\\xe2\\xe3\\xe4\\xe5\\xe6\\xe7" + "\\xe8\\xe9\\xea\\xeb\\xec\\xed\\xee\\xef\\xf0\\xf1\\xf2\\xf3\\xf4\\xf5" + "\\xf6\\xf7\\xf8\\xf9\\xfa\\xfb\\xfc\\xfd\\xfe\\xff"), fromHex( "B11E398DC80327A1C8E7F78C596A4934" + "4F012EDA2D4EFAD8A050CC4C19AFA97C" + "59045A99CAC7827271CB41C65E590E09" + "DA3275600C2F09B8367793A9ACA3DB71" + "CC30C58179EC3E87C14C01D5C1F3434F" + "1D87")), new testCase( "HmacSHA256", fromCHex( "\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b" + "\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b"), new byte[0], new byte[0], fromHex( "8DA4E775A563C18F715F802A063C5A31" + "B8A11F5C5EE1879EC3454E5F3C738D2D" + "9D201395FAA4B61A96C8")), new testCase( "HmacSHA1", fromCHex("\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b"), fromCHex("\\x00\\x01\\x02\\x03\\x04\\x05\\x06\\x07\\x08\\x09\\x0a\\x0b\\x0c"), fromCHex("\\xf0\\xf1\\xf2\\xf3\\xf4\\xf5\\xf6\\xf7\\xf8\\xf9"), fromHex( "085A01EA1B10F36933068B56EFA5AD81" + "A4F14B822F5B091568A9CDD4F155FDA2" + "C22E422478D305F3F896")), new testCase( "HmacSHA1", fromCHex( "\\x00\\x01\\x02\\x03\\x04\\x05\\x06\\x07\\x08\\x09\\x0a\\x0b\\x0c\\x0d" + "\\x0e\\x0f\\x10\\x11\\x12\\x13\\x14\\x15\\x16\\x17\\x18\\x19\\x1a\\x1b" + "\\x1c\\x1d\\x1e\\x1f\\x20\\x21\\x22\\x23\\x24\\x25\\x26\\x27\\x28\\x29" + "\\x2a\\x2b\\x2c\\x2d\\x2e\\x2f\\x30\\x31\\x32\\x33\\x34\\x35\\x36\\x37" + "\\x38\\x39\\x3a\\x3b\\x3c\\x3d\\x3e\\x3f\\x40\\x41\\x42\\x43\\x44\\x45" + "\\x46\\x47\\x48\\x49\\x4a\\x4b\\x4c\\x4d\\x4e\\x4f"), fromCHex( "\\x60\\x61\\x62\\x63\\x64\\x65\\x66\\x67\\x68\\x69\\x6A\\x6B\\x6C\\x6D" + "\\x6E\\x6F\\x70\\x71\\x72\\x73\\x74\\x75\\x76\\x77\\x78\\x79\\x7A\\x7B" + "\\x7C\\x7D\\x7E\\x7F\\x80\\x81\\x82\\x83\\x84\\x85\\x86\\x87\\x88\\x89" + "\\x8A\\x8B\\x8C\\x8D\\x8E\\x8F\\x90\\x91\\x92\\x93\\x94\\x95\\x96\\x97" + "\\x98\\x99\\x9A\\x9B\\x9C\\x9D\\x9E\\x9F\\xA0\\xA1\\xA2\\xA3\\xA4\\xA5" + "\\xA6\\xA7\\xA8\\xA9\\xAA\\xAB\\xAC\\xAD\\xAE\\xAF"), fromCHex( "\\xB0\\xB1\\xB2\\xB3\\xB4\\xB5\\xB6\\xB7\\xB8\\xB9\\xBA\\xBB\\xBC\\xBD" + "\\xBE\\xBF\\xC0\\xC1\\xC2\\xC3\\xC4\\xC5\\xC6\\xC7\\xC8\\xC9\\xCA\\xCB" + "\\xCC\\xCD\\xCE\\xCF\\xD0\\xD1\\xD2\\xD3\\xD4\\xD5\\xD6\\xD7\\xD8\\xD9" + "\\xDA\\xDB\\xDC\\xDD\\xDE\\xDF\\xE0\\xE1\\xE2\\xE3\\xE4\\xE5\\xE6\\xE7" + "\\xE8\\xE9\\xEA\\xEB\\xEC\\xED\\xEE\\xEF\\xF0\\xF1\\xF2\\xF3\\xF4\\xF5" + "\\xF6\\xF7\\xF8\\xF9\\xFA\\xFB\\xFC\\xFD\\xFE\\xFF"), fromHex( "0BD770A74D1160F7C9F12CD5912A06EB" + "FF6ADCAE899D92191FE4305673BA2FFE" + "8FA3F1A4E5AD79F3F334B3B202B2173C" + "486EA37CE3D397ED034C7F9DFEB15C5E" + "927336D0441F4C4300E2CFF0D0900B52D3B4")), new testCase( "HmacSHA1", fromCHex( "\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b" + "\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b"), new byte[0], new byte[0], fromHex("0AC1AF7002B3D761D1E55298DA9D0506" + "B9AE52057220A306E07B6B87E8DF21D0")), new testCase( "HmacSHA1", fromCHex( "\\x0c\\x0c\\x0c\\x0c\\x0c\\x0c\\x0c\\x0c\\x0c\\x0c\\x0c\\x0c\\x0c\\x0c" + "\\x0c\\x0c\\x0c\\x0c\\x0c\\x0c\\x0c\\x0c"), null, new byte[0], fromHex( "2C91117204D745F3500D636A62F64F0A" + "B3BAE548AA53D423B0D1F27EBBA6F5E5" + "673A081D70CCE7ACFC48")) }; @Test public void rfc5869Tests() throws Exception { for (int x = 0; x < testCases.length; x++) { testCase trial = testCases[x]; System.out.println("Test case A." + (x + 1)); HmacKeyDerivationFunction kdf = HmacKeyDerivationFunction.getInstance(trial.algo); kdf.init(trial.ikm, trial.salt); byte[] result = kdf.deriveKey(trial.info, trial.expected.length); assertArrayEquals("Trial A." + x, trial.expected, result); } } @Test public void nullTests() throws Exception { testCase trial = testCases[0]; HmacKeyDerivationFunction kdf = HmacKeyDerivationFunction.getInstance(trial.algo); kdf.init(trial.ikm, trial.salt); // Just ensuring no exceptions are thrown kdf.deriveKey(null, 16); } @Test(expected = IllegalArgumentException.class) public void invalidLength() throws Exception { testCase trial = testCases[0]; HmacKeyDerivationFunction kdf = HmacKeyDerivationFunction.getInstance(trial.algo); kdf.init(trial.ikm, trial.salt); kdf.deriveKey(trial.info, -1); } @Test public void defaultSalt() throws Exception { // Tests all the different ways to get the default salt testCase trial = testCases[0]; HmacKeyDerivationFunction kdf1 = HmacKeyDerivationFunction.getInstance(trial.algo); kdf1.init(trial.ikm, null); HmacKeyDerivationFunction kdf2 = HmacKeyDerivationFunction.getInstance(trial.algo); kdf2.init(trial.ikm, new byte[0]); HmacKeyDerivationFunction kdf3 = HmacKeyDerivationFunction.getInstance(trial.algo); kdf3.init(trial.ikm); HmacKeyDerivationFunction kdf4 = HmacKeyDerivationFunction.getInstance(trial.algo); kdf4.init(trial.ikm, new byte[32]); byte[] testBytes = "Test".getBytes(StringUtils.UTF8); byte[] key1 = kdf1.deriveKey(testBytes, 16); byte[] key2 = kdf2.deriveKey(testBytes, 16); byte[] key3 = kdf3.deriveKey(testBytes, 16); byte[] key4 = kdf4.deriveKey(testBytes, 16); assertArrayEquals(key1, key2); assertArrayEquals(key1, key3); assertArrayEquals(key1, key4); } private static byte[] fromHex(String data) { byte[] result = new byte[data.length() / 2]; for (int x = 0; x < result.length; x++) { result[x] = (byte) Integer.parseInt(data.substring(2 * x, 2 * x + 2), 16); } return result; } private static byte[] fromCHex(String data) { byte[] result = new byte[data.length() / 4]; for (int x = 0; x < result.length; x++) { result[x] = (byte) Integer.parseInt(data.substring(4 * x + 2, 4 * x + 4), 16); } return result; } private static class testCase { public final String algo; public final byte[] ikm; public final byte[] salt; public final byte[] info; public final byte[] expected; testCase(String algo, byte[] ikm, byte[] salt, byte[] info, byte[] expected) { super(); this.algo = algo; this.ikm = ikm; this.salt = salt; this.info = info; this.expected = expected; } } }
754
0
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk/internal/AwsKmsCmkArnInfoTest.java
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package com.amazonaws.encryptionsdk.internal; import static com.amazonaws.encryptionsdk.TestUtils.assertThrows; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import org.junit.Test; import org.junit.experimental.runners.Enclosed; import org.junit.jupiter.api.DisplayName; import org.junit.runner.RunWith; @RunWith(Enclosed.class) public class AwsKmsCmkArnInfoTest { public static class splitArn { @Test public void basic_use() { String[] test = AwsKmsCmkArnInfo.AwsKmsArnParts.splitArn( "arn:aws:kms:us-west-2:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574"); assertEquals(test.length, 6); } @Test public void with_fewer_elements() { String[] test = AwsKmsCmkArnInfo.AwsKmsArnParts.splitArn("arn:aws:kms:us-west-2"); assertEquals(test.length, 4); } @Test public void with_valid_arn_but_not_kms_valid() { String[] test = AwsKmsCmkArnInfo.AwsKmsArnParts.splitArn( "arn:aws:kms:us-west-2:111122223333:key:mrk-edb7fe6942894d32ac46dbb1c922d574"); assertEquals(test.length, 6); } } public static class splitResourceParts { @Test public void basic_use() { String[] test = AwsKmsCmkArnInfo.AwsKmsArnParts.Resource.splitResourceParts( "key/mrk-edb7fe6942894d32ac46dbb1c922d574"); assertEquals(test.length, 2); } } public static class parseInfoFromKeyArn { @Test public void basic_use() { AwsKmsCmkArnInfo test = AwsKmsCmkArnInfo.parseInfoFromKeyArn( "arn:aws:kms:us-west-2:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574"); assertNotNull(test); assertEquals(test.getPartition(), "aws"); assertEquals(test.getRegion(), "us-west-2"); assertEquals(test.getAccountId(), "111122223333"); assertEquals(test.getAccountId(), "111122223333"); assertEquals(test.getResourceType(), "key"); assertEquals(test.getResource(), "mrk-edb7fe6942894d32ac46dbb1c922d574"); } @Test @DisplayName("Precondition: keyArn must be a string.") public void keyArn_must_be_string_with_content() { assertEquals(AwsKmsCmkArnInfo.parseInfoFromKeyArn(""), null); assertEquals(AwsKmsCmkArnInfo.parseInfoFromKeyArn(null), null); } @Test // = compliance/framework/aws-kms/aws-kms-key-arn.txt#2.5 // = type=test // # MUST start with string "arn" public void not_well_formed() { assertEquals( AwsKmsCmkArnInfo.parseInfoFromKeyArn("key/mrk-edb7fe6942894d32ac46dbb1c922d574"), null); assertEquals(AwsKmsCmkArnInfo.parseInfoFromKeyArn("alias/my-key"), null); assertEquals( AwsKmsCmkArnInfo.parseInfoFromKeyArn( "not-an-arn:aws:kms:us-west-2:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574"), null); } @Test // = compliance/framework/aws-kms/aws-kms-key-arn.txt#2.5 // = type=test // # The service MUST be the string "kms" public void not_kms_service() { assertEquals( AwsKmsCmkArnInfo.parseInfoFromKeyArn("arn:aws:sqs:us-east-2:444455556666:queue1"), null); } @Test // = compliance/framework/aws-kms/aws-kms-key-arn.txt#2.5 // = type=test // # The partition MUST be a non-empty public void partition_non_empty() { assertEquals( AwsKmsCmkArnInfo.parseInfoFromKeyArn( "arn::kms:us-west-2:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574"), null); } @Test // = compliance/framework/aws-kms/aws-kms-key-arn.txt#2.5 // = type=test // # The region MUST be a non-empty string public void region_non_empty() { assertEquals( AwsKmsCmkArnInfo.parseInfoFromKeyArn( "arn:aws:kms::111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574"), null); } @Test // = compliance/framework/aws-kms/aws-kms-key-arn.txt#2.5 // = type=test // # The account MUST be a non-empty string public void account_non_empty() { assertEquals( AwsKmsCmkArnInfo.parseInfoFromKeyArn( "arn:aws:kms:us-west-2::key/mrk-edb7fe6942894d32ac46dbb1c922d574"), null); } @Test // = compliance/framework/aws-kms/aws-kms-key-arn.txt#2.5 // = type=test // # The resource section MUST be non-empty and MUST be split by a // # single "/" any additional "/" are included in the resource id public void resource_non_empty() { // = compliance/framework/aws-kms/aws-kms-key-arn.txt#2.5 // = type=test // # The resource id MUST be a non-empty string assertEquals( AwsKmsCmkArnInfo.parseInfoFromKeyArn("arn:aws:kms:us-west-2:111122223333:"), null); assertEquals( // This is a valid ARN but not valid for AWS KMS AwsKmsCmkArnInfo.parseInfoFromKeyArn( "arn:aws:kms:us-west-2:111122223333:key:mrk-edb7fe6942894d32ac46dbb1c922d574"), null); final AwsKmsCmkArnInfo arn = AwsKmsCmkArnInfo.parseInfoFromKeyArn( "arn:aws:kms:us-west-2:111122223333:alias/has/slashes"); assertNotNull(arn); assertEquals(arn.getResource(), "has/slashes"); } // = compliance/framework/aws-kms/aws-kms-key-arn.txt#2.5 // = type=test // # The resource type MUST be either "alias" or "key" public void resource_type_key_or_alias() { assertEquals( AwsKmsCmkArnInfo.parseInfoFromKeyArn( "arn:aws:kms:us-west-2:111122223333:not-key/mrk-edb7fe6942894d32ac46dbb1c922d574"), null); } } public static class validAwsKmsIdentifier { @Test public void basic_use() { AwsKmsCmkArnInfo.validAwsKmsIdentifier("mrk-edb7fe6942894d32ac46dbb1c922d574"); AwsKmsCmkArnInfo.validAwsKmsIdentifier("alias/my-alias"); AwsKmsCmkArnInfo.validAwsKmsIdentifier( "arn:aws:kms:us-west-2:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574"); AwsKmsCmkArnInfo.validAwsKmsIdentifier("arn:aws:kms:us-west-2:111122223333:alias/my-alias"); } @Test @DisplayName("Exceptional Postcondition: Null or empty string is not a valid identifier.") public void must_have_content() { assertThrows( IllegalArgumentException.class, "Null or empty string is not a valid Aws KMS identifier.", () -> AwsKmsCmkArnInfo.validAwsKmsIdentifier("")); assertThrows( IllegalArgumentException.class, "Null or empty string is not a valid Aws KMS identifier.", () -> AwsKmsCmkArnInfo.validAwsKmsIdentifier(null)); } @Test @DisplayName("Exceptional Postcondition: Things that start with `arn:` MUST be ARNs.") public void arn_must_be_arn() { assertThrows( IllegalArgumentException.class, "Invalid ARN used as an identifier.", () -> AwsKmsCmkArnInfo.validAwsKmsIdentifier( "arn:aws:dynamodb:us-east-2:123456789012:table/myDynamoDBTable")); } @Test @DisplayName("Postcondition: Raw alias starts with `alias/`.") public void alias_is_valid() { AwsKmsCmkArnInfo.validAwsKmsIdentifier("alias/some/kind/of/alias"); } @Test @DisplayName("Postcondition: There are no requirements on key ids.") public void anything_else_is_key_id() { AwsKmsCmkArnInfo.validAwsKmsIdentifier("mrk-edb7fe6942894d32ac46dbb1c922d574"); AwsKmsCmkArnInfo.validAwsKmsIdentifier("b3537ef1-d8dc-4780-9f5a-55776cbb2f7f"); } } public static class isMRK { @Test // = compliance/framework/aws-kms/aws-kms-key-arn.txt#2.9 // = type=test // # This function MUST take a single AWS KMS identifier public void basic_use() { // = compliance/framework/aws-kms/aws-kms-key-arn.txt#2.9 // = type=test // # If the input starts // # with "mrk-", this is a multi-Region key id and MUST return true. assertEquals(AwsKmsCmkArnInfo.isMRK("mrk-edb7fe6942894d32ac46dbb1c922d574"), true); // = compliance/framework/aws-kms/aws-kms-key-arn.txt#2.9 // = type=test // # If the input starts with "alias/", this an AWS KMS alias and // # not a multi-Region key id and MUST return false. assertEquals(AwsKmsCmkArnInfo.isMRK("alias/mrk-1234"), false); // = compliance/framework/aws-kms/aws-kms-key-arn.txt#2.9 // = type=test // # If // # the input does not start with any of the above, this is not a multi- // # Region key id and MUST return false. assertEquals(AwsKmsCmkArnInfo.isMRK("64339c87-2ae4-42b1-8875-c83fc47acc97"), false); // = compliance/framework/aws-kms/aws-kms-key-arn.txt#2.9 // = type=test // # If the input starts with "arn:", this MUST return the output of // # identifying an an AWS KMS multi-Region ARN (aws-kms-key- // # arn.md#identifying-an-an-aws-kms-multi-region-arn) called with this // # input. assertEquals( AwsKmsCmkArnInfo.isMRK( "arn:aws:kms:us-west-2:111122223333:alias/mrk-edb7fe6942894d32ac46dbb1c922d574"), false); } @Test // = compliance/framework/aws-kms/aws-kms-key-arn.txt#2.8 // = type=test // # If the input is an invalid AWS KMS ARN this function MUST error. public void invalid_arn() { assertThrows( () -> AwsKmsCmkArnInfo.isMRK( AwsKmsCmkArnInfo.parseInfoFromKeyArn( "arn:aws:kms:us-west-2:111122223333:not-key/mrk-edb7fe6942894d32ac46dbb1c922d574"))); } @Test // = compliance/framework/aws-kms/aws-kms-key-arn.txt#2.8 // = type=test // # If resource type is "alias", this is an AWS KMS alias ARN and MUST // # return false. public void with_an_alias_AwsKmsCmkArnInfo() { assertEquals( AwsKmsCmkArnInfo.isMRK( AwsKmsCmkArnInfo.parseInfoFromKeyArn( "arn:aws:kms:us-west-2:111122223333:alias/mrk-edb7fe6942894d32ac46dbb1c922d574")), false); } @Test // = compliance/framework/aws-kms/aws-kms-key-arn.txt#2.8 // = type=test // # This function MUST take a single AWS KMS ARN public void with_an_mrk_AwsKmsCmkArnInfo() { // = compliance/framework/aws-kms/aws-kms-key-arn.txt#2.8 // = type=test // # If resource type is "key" and resource ID starts with // # "mrk-", this is a AWS KMS multi-Region key ARN and MUST return true. assertEquals( AwsKmsCmkArnInfo.isMRK( AwsKmsCmkArnInfo.parseInfoFromKeyArn( "arn:aws:kms:us-west-2:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574")), true); } @Test // = compliance/framework/aws-kms/aws-kms-key-arn.txt#2.8 // = type=test // # If resource type is "key" and resource ID does not start with "mrk-", // # this is a (single-region) AWS KMS key ARN and MUST return false. public void with_an_srk_AwsKmsCmkArnInfo() { assertEquals( AwsKmsCmkArnInfo.isMRK( AwsKmsCmkArnInfo.parseInfoFromKeyArn( "arn:aws:kms:us-west-2:111122223333:key/b3537ef1-d8dc-4780-9f5a-55776cbb2f7f")), false); } } public static class awsKmsArnMatchForDecrypt { @Test // = compliance/framework/aws-kms/aws-kms-mrk-match-for-decrypt.txt#2.5 // = type=test // # The caller MUST provide: public void basic_use() { assertEquals( AwsKmsCmkArnInfo.awsKmsArnMatchForDecrypt( "arn:aws:kms:us-west-2:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574", "arn:aws:kms:us-west-2:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574"), true); assertEquals( AwsKmsCmkArnInfo.awsKmsArnMatchForDecrypt( "arn:aws:kms:us-east-1:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574", "arn:aws:kms:us-west-2:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574"), true); } @Test // = compliance/framework/aws-kms/aws-kms-mrk-match-for-decrypt.txt#2.5 // = type=test // # If both identifiers are identical, this function MUST return "true". public void string_match_cases() { assertEquals( AwsKmsCmkArnInfo.awsKmsArnMatchForDecrypt( "arn:aws:kms:us-west-2:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574", "arn:aws:kms:us-west-2:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574"), true); assertEquals( AwsKmsCmkArnInfo.awsKmsArnMatchForDecrypt( "arn:aws:kms:us-west-2:111122223333:key/64339c87-2ae4-42b1-8875-c83fc47acc97", "arn:aws:kms:us-west-2:111122223333:key/64339c87-2ae4-42b1-8875-c83fc47acc97"), true); assertEquals( AwsKmsCmkArnInfo.awsKmsArnMatchForDecrypt( "arn:aws:kms:us-west-2:111122223333:alias/my-name", "arn:aws:kms:us-west-2:111122223333:alias/my-name"), true); assertEquals( AwsKmsCmkArnInfo.awsKmsArnMatchForDecrypt("alias/my-raw-alias", "alias/my-raw-alias"), true); assertEquals( AwsKmsCmkArnInfo.awsKmsArnMatchForDecrypt( "64339c87-2ae4-42b1-8875-c83fc47acc97", "64339c87-2ae4-42b1-8875-c83fc47acc97"), true); assertEquals( AwsKmsCmkArnInfo.awsKmsArnMatchForDecrypt( "c83fc47acc97", "64339c87-2ae4-42b1-8875-c83fc47acc97"), false); } @Test @DisplayName( "Check for early return (Postcondition): Both identifiers are not ARNs and not equal, therefore they can not match.") public void flexibility_for_only_arns() { assertEquals( AwsKmsCmkArnInfo.awsKmsArnMatchForDecrypt( "arn:aws:kms:us-west-2:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574", "mrk-edb7fe6942894d32ac46dbb1c922d574"), false); assertEquals( AwsKmsCmkArnInfo.awsKmsArnMatchForDecrypt( "mrk-edb7fe6942894d32ac46dbb1c922d574", "arn:aws:kms:us-west-2:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574"), false); } @Test // = compliance/framework/aws-kms/aws-kms-mrk-match-for-decrypt.txt#2.5 // = type=test // # Otherwise if either input is not identified as a multi-Region key // # (aws-kms-key-arn.md#identifying-an-aws-kms-multi-region-key), then // # this function MUST return "false". public void no_flexibility_for_non_mrks() { assertEquals( AwsKmsCmkArnInfo.awsKmsArnMatchForDecrypt( "arn:aws:kms:us-west-2:111122223333:key/64339c87-2ae4-42b1-8875-c83fc47acc97", "arn:aws:kms:us-east-1:111122223333:key/64339c87-2ae4-42b1-8875-c83fc47acc97"), false); assertEquals( AwsKmsCmkArnInfo.awsKmsArnMatchForDecrypt( "arn:aws:kms:us-west-2:111122223333:alias/mrk-someOtherName", "arn:aws:kms:us-east-1:111122223333:alias/mrk-someOtherName"), false); } @Test // = compliance/framework/aws-kms/aws-kms-mrk-match-for-decrypt.txt#2.5 // = type=test // # Otherwise if both inputs are // # identified as a multi-Region keys (aws-kms-key-arn.md#identifying-an- // # aws-kms-multi-region-key), this function MUST return the result of // # comparing the "partition", "service", "accountId", "resourceType", // # and "resource" parts of both ARN inputs. public void all_elements_must_match() { // Different partition assertEquals( AwsKmsCmkArnInfo.awsKmsArnMatchForDecrypt( "arn:not-aws:kms:us-east-1:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574", "arn:aws:kms:us-west-2:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574"), false); // Different account assertEquals( AwsKmsCmkArnInfo.awsKmsArnMatchForDecrypt( "arn:aws:kms:us-east-1:333322221111:key/mrk-edb7fe6942894d32ac46dbb1c922d574", "arn:aws:kms:us-west-2:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574"), false); // Different resource type assertEquals( AwsKmsCmkArnInfo.awsKmsArnMatchForDecrypt( "arn:not-aws:kms:us-east-1:111122223333:not-key/mrk-edb7fe6942894d32ac46dbb1c922d574", "arn:aws:kms:us-west-2:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574"), false); // Different resource assertEquals( AwsKmsCmkArnInfo.awsKmsArnMatchForDecrypt( "arn:aws:kms:us-east-1:111122223333:key/mrk-475d229c1bbd64ca23d4982496ef7bde", "arn:aws:kms:us-west-2:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574"), false); } } public static class to_string_tests { @Test public void basic_use() { final String arn = "arn:aws:kms:us-west-2:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574"; final String region = "us-east-1"; final AwsKmsCmkArnInfo test = AwsKmsCmkArnInfo.parseInfoFromKeyArn(arn); assertEquals(arn, test.toString()); assertEquals( "arn:aws:kms:us-east-1:111122223333:key/mrk-edb7fe6942894d32ac46dbb1c922d574", test.toString("us-east-1")); } } }
755
0
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk/internal/CipherHandlerTest.java
/* * Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except * in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.amazonaws.encryptionsdk.internal; import static org.junit.Assert.assertTrue; import com.amazonaws.encryptionsdk.CryptoAlgorithm; import com.amazonaws.encryptionsdk.TestUtils; import com.amazonaws.encryptionsdk.exception.BadCiphertextException; import java.util.Arrays; import java.util.EnumSet; import javax.crypto.Cipher; import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec; import org.junit.Test; public class CipherHandlerTest { private final int contentLen_ = 1024; // 1KB private final byte[] contentAad_ = "Test string AAD".getBytes(); @Test public void encryptDecryptWithAllAlgos() { for (final CryptoAlgorithm cryptoAlg : EnumSet.allOf(CryptoAlgorithm.class)) { assertTrue(encryptDecryptContent(cryptoAlg)); assertTrue(encryptDecryptEmptyContent(cryptoAlg)); } } @Test(expected = BadCiphertextException.class) public void tamperCiphertext() { final CryptoAlgorithm cryptoAlgorithm = TestUtils.DEFAULT_TEST_CRYPTO_ALG; final byte[] content = RandomBytesGenerator.generate(contentLen_); final byte[] keyBytes = RandomBytesGenerator.generate(cryptoAlgorithm.getKeyLength()); final byte[] nonce = RandomBytesGenerator.generate(cryptoAlgorithm.getNonceLen()); final SecretKey key = new SecretKeySpec(keyBytes, cryptoAlgorithm.getKeyAlgo()); CipherHandler cipherHandler = createCipherHandler(key, cryptoAlgorithm, Cipher.ENCRYPT_MODE); final byte[] encryptedBytes = cipherHandler.cipherData(nonce, contentAad_, content, 0, content.length); encryptedBytes[0] += 1; // tamper the first byte in ciphertext cipherHandler = createCipherHandler(key, cryptoAlgorithm, Cipher.DECRYPT_MODE); cipherHandler.cipherData(nonce, contentAad_, encryptedBytes, 0, encryptedBytes.length); } private boolean encryptDecryptContent(final CryptoAlgorithm cryptoAlgorithm) { final byte[] content = RandomBytesGenerator.generate(contentLen_); final byte[] result = encryptDecrypt(content, cryptoAlgorithm); return Arrays.equals(content, result) ? true : false; } private boolean encryptDecryptEmptyContent(final CryptoAlgorithm cryptoAlgorithm) { final byte[] result = encryptDecrypt(new byte[0], cryptoAlgorithm); return (result.length == 0) ? true : false; } private byte[] encryptDecrypt(final byte[] content, final CryptoAlgorithm cryptoAlgorithm) { final byte[] keyBytes = RandomBytesGenerator.generate(cryptoAlgorithm.getKeyLength()); final byte[] nonce = RandomBytesGenerator.generate(cryptoAlgorithm.getNonceLen()); final SecretKey key = new SecretKeySpec(keyBytes, cryptoAlgorithm.getKeyAlgo()); CipherHandler cipherHandler = createCipherHandler(key, cryptoAlgorithm, Cipher.ENCRYPT_MODE); final byte[] encryptedBytes = cipherHandler.cipherData(nonce, contentAad_, content, 0, content.length); cipherHandler = createCipherHandler(key, cryptoAlgorithm, Cipher.DECRYPT_MODE); final byte[] decryptedBytes = cipherHandler.cipherData(nonce, contentAad_, encryptedBytes, 0, encryptedBytes.length); return decryptedBytes; } private CipherHandler createCipherHandler( final SecretKey key, final CryptoAlgorithm cryptoAlgorithm, final int mode) { return new CipherHandler(key, mode, cryptoAlgorithm); } }
756
0
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk/internal/BlockDecryptionHandlerTest.java
/* * Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except * in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.amazonaws.encryptionsdk.internal; import static org.junit.Assert.assertTrue; import com.amazonaws.encryptionsdk.CryptoAlgorithm; import com.amazonaws.encryptionsdk.TestUtils; import com.amazonaws.encryptionsdk.exception.AwsCryptoException; import com.amazonaws.encryptionsdk.exception.BadCiphertextException; import java.nio.ByteBuffer; import java.security.SecureRandom; import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec; import org.junit.Before; import org.junit.Test; public class BlockDecryptionHandlerTest { private static final SecureRandom RND = new SecureRandom(); private final CryptoAlgorithm cryptoAlgorithm_ = TestUtils.DEFAULT_TEST_CRYPTO_ALG; private final byte[] messageId_ = new byte[cryptoAlgorithm_.getMessageIdLength()]; private final byte nonceLen_ = cryptoAlgorithm_.getNonceLen(); private final byte[] dataKeyBytes_ = new byte[cryptoAlgorithm_.getKeyLength()]; private final SecretKey dataKey_ = new SecretKeySpec(dataKeyBytes_, "AES"); private final BlockDecryptionHandler blockDecryptionHandler_ = new BlockDecryptionHandler(dataKey_, nonceLen_, cryptoAlgorithm_, messageId_); @Before public void setup() { RND.nextBytes(messageId_); RND.nextBytes(dataKeyBytes_); } @Test public void estimateOutputSize() { final int inLen = 1; final int outSize = blockDecryptionHandler_.estimateOutputSize(inLen); // the estimated output size must at least be equal to inLen. assertTrue(outSize >= inLen); } @Test(expected = BadCiphertextException.class) public void doFinalCalledWhileNotComplete() { blockDecryptionHandler_.doFinal(new byte[1], 0); } @Test(expected = AwsCryptoException.class) public void decryptMaxContentLength() { final BlockEncryptionHandler blockEncryptionHandler = new BlockEncryptionHandler(dataKey_, nonceLen_, cryptoAlgorithm_, messageId_); final byte[] in = new byte[0]; final int outLen = blockEncryptionHandler.estimateOutputSize(in.length); final byte[] out = new byte[outLen]; blockEncryptionHandler.processBytes(in, 0, in.length, out, 0); blockEncryptionHandler.doFinal(out, 0); final ByteBuffer outBuff = ByteBuffer.wrap(out); // pull out nonce to get to content length. final byte[] nonce = new byte[nonceLen_]; outBuff.get(nonce); // set content length to integer max value + 1. outBuff.putLong(Integer.MAX_VALUE + 1L); final int decryptedOutLen = blockDecryptionHandler_.estimateOutputSize(outLen); final byte[] decryptedOut = new byte[decryptedOutLen]; blockDecryptionHandler_.processBytes( outBuff.array(), 0, outBuff.array().length, decryptedOut, 0); } @Test(expected = AwsCryptoException.class) public void processBytesCalledWhileComplete() { final BlockEncryptionHandler blockEncryptionHandler = new BlockEncryptionHandler(dataKey_, nonceLen_, cryptoAlgorithm_, messageId_); final byte[] in = new byte[0]; final int outLen = blockEncryptionHandler.estimateOutputSize(in.length); final byte[] out = new byte[outLen]; blockEncryptionHandler.processBytes(in, 0, in.length, out, 0); blockEncryptionHandler.doFinal(out, 0); final byte[] decryptedOut = new byte[outLen]; blockDecryptionHandler_.processBytes(out, 0, outLen, decryptedOut, 0); blockDecryptionHandler_.processBytes(out, 0, outLen, decryptedOut, 0); } }
757
0
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk/internal/EncryptionHandlerTest.java
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package com.amazonaws.encryptionsdk.internal; import static com.amazonaws.encryptionsdk.TestUtils.assertThrows; import static java.util.Collections.emptyList; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import com.amazonaws.encryptionsdk.AwsCrypto; import com.amazonaws.encryptionsdk.CommitmentPolicy; import com.amazonaws.encryptionsdk.CryptoAlgorithm; import com.amazonaws.encryptionsdk.DefaultCryptoMaterialsManager; import com.amazonaws.encryptionsdk.TestUtils; import com.amazonaws.encryptionsdk.exception.AwsCryptoException; import com.amazonaws.encryptionsdk.model.EncryptionMaterials; import com.amazonaws.encryptionsdk.model.EncryptionMaterialsRequest; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Map; import org.junit.Test; public class EncryptionHandlerTest { private final CryptoAlgorithm cryptoAlgorithm_ = TestUtils.DEFAULT_TEST_CRYPTO_ALG; private final int frameSize_ = AwsCrypto.getDefaultFrameSize(); private final Map<String, String> encryptionContext_ = Collections.<String, String>emptyMap(); private StaticMasterKey masterKeyProvider = new StaticMasterKey("mock"); private final List<StaticMasterKey> cmks_ = Collections.singletonList(masterKeyProvider); private final CommitmentPolicy commitmentPolicy = TestUtils.DEFAULT_TEST_COMMITMENT_POLICY; private EncryptionMaterialsRequest testRequest = EncryptionMaterialsRequest.newBuilder() .setContext(encryptionContext_) .setRequestedAlgorithm(cryptoAlgorithm_) .setCommitmentPolicy(commitmentPolicy) .build(); private EncryptionMaterials testResult = new DefaultCryptoMaterialsManager(masterKeyProvider).getMaterialsForEncrypt(testRequest); @Test public void badArguments() { assertThrows( () -> new EncryptionHandler( frameSize_, testResult.toBuilder().setAlgorithm(null).build(), commitmentPolicy)); assertThrows( () -> new EncryptionHandler( frameSize_, testResult.toBuilder().setEncryptionContext(null).build(), commitmentPolicy)); assertThrows( () -> new EncryptionHandler( frameSize_, testResult.toBuilder().setEncryptedDataKeys(null).build(), commitmentPolicy)); assertThrows( () -> new EncryptionHandler( frameSize_, testResult.toBuilder().setEncryptedDataKeys(emptyList()).build(), commitmentPolicy)); assertThrows( () -> new EncryptionHandler( frameSize_, testResult.toBuilder().setCleartextDataKey(null).build(), commitmentPolicy)); assertThrows( () -> new EncryptionHandler( frameSize_, testResult.toBuilder().setMasterKeys(null).build(), commitmentPolicy)); assertThrows(() -> new EncryptionHandler(-1, testResult, commitmentPolicy)); assertThrows(() -> new EncryptionHandler(frameSize_, testResult, null)); } @Test(expected = AwsCryptoException.class) public void invalidLenProcessBytes() { final EncryptionHandler encryptionHandler = new EncryptionHandler(frameSize_, testResult, commitmentPolicy); final byte[] in = new byte[1]; final byte[] out = new byte[1]; encryptionHandler.processBytes(in, 0, -1, out, 0); } @Test(expected = AwsCryptoException.class) public void invalidOffsetProcessBytes() { final EncryptionHandler encryptionHandler = new EncryptionHandler(frameSize_, testResult, commitmentPolicy); final byte[] in = new byte[1]; final byte[] out = new byte[1]; encryptionHandler.processBytes(in, -1, in.length, out, 0); } @Test public void whenEncrypting_headerIVIsZero() throws Exception { final EncryptionHandler encryptionHandler = new EncryptionHandler(frameSize_, testResult, commitmentPolicy); assertArrayEquals( new byte[encryptionHandler.getHeaders().getCryptoAlgoId().getNonceLen()], encryptionHandler.getHeaders().getHeaderNonce()); } @Test public void whenConstructWithForbidPolicyAndCommittingAlg_fails() throws Exception { final EncryptionMaterials resultWithV2Alg = testResult.toBuilder().setAlgorithm(TestUtils.DEFAULT_TEST_CRYPTO_ALG).build(); assertThrows( AwsCryptoException.class, () -> new EncryptionHandler( frameSize_, resultWithV2Alg, CommitmentPolicy.ForbidEncryptAllowDecrypt)); } @Test public void whenConstructWithForbidPolicyAndNonCommittingAlg_succeeds() throws Exception { final CryptoAlgorithm algorithm = CryptoAlgorithm.ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA384_ECDSA_P384; final EncryptionMaterialsRequest requestForMaterialsWithoutCommitment = EncryptionMaterialsRequest.newBuilder() .setContext(encryptionContext_) .setRequestedAlgorithm(algorithm) .setCommitmentPolicy(CommitmentPolicy.ForbidEncryptAllowDecrypt) .build(); final EncryptionMaterials materials = new DefaultCryptoMaterialsManager(masterKeyProvider) .getMaterialsForEncrypt(requestForMaterialsWithoutCommitment); EncryptionHandler handler = new EncryptionHandler(frameSize_, materials, CommitmentPolicy.ForbidEncryptAllowDecrypt); assertNotNull(handler); assertEquals(algorithm, handler.getHeaders().getCryptoAlgoId()); } @Test public void whenConstructWithRequirePolicyAndNonCommittingAlg_fails() throws Exception { final EncryptionMaterials resultWithV1Alg = testResult.toBuilder() .setAlgorithm(CryptoAlgorithm.ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA384_ECDSA_P384) .build(); assertThrows( AwsCryptoException.class, () -> new EncryptionHandler( frameSize_, resultWithV1Alg, CommitmentPolicy.RequireEncryptRequireDecrypt)); assertThrows( AwsCryptoException.class, () -> new EncryptionHandler( frameSize_, resultWithV1Alg, CommitmentPolicy.RequireEncryptAllowDecrypt)); } @Test public void whenConstructWithRequirePolicyAndCommittingAlg_succeeds() throws Exception { final CryptoAlgorithm algorithm = CryptoAlgorithm.ALG_AES_256_GCM_HKDF_SHA512_COMMIT_KEY; final EncryptionMaterialsRequest requestForMaterialsWithCommitment = EncryptionMaterialsRequest.newBuilder() .setContext(encryptionContext_) .setRequestedAlgorithm(algorithm) .setCommitmentPolicy(CommitmentPolicy.RequireEncryptRequireDecrypt) .build(); final EncryptionMaterials materials = new DefaultCryptoMaterialsManager(masterKeyProvider) .getMaterialsForEncrypt(requestForMaterialsWithCommitment); final List<CommitmentPolicy> requireWritePolicies = Arrays.asList( CommitmentPolicy.RequireEncryptAllowDecrypt, CommitmentPolicy.RequireEncryptRequireDecrypt); for (CommitmentPolicy policy : requireWritePolicies) { EncryptionHandler handler = new EncryptionHandler(frameSize_, materials, policy); assertNotNull(handler); assertEquals(algorithm, handler.getHeaders().getCryptoAlgoId()); } } @Test public void setMaxInputLength() { byte[] plaintext = "Don't warn the tadpoles".getBytes(); final EncryptionHandler encryptionHandler = new EncryptionHandler(frameSize_, testResult, commitmentPolicy); encryptionHandler.setMaxInputLength(plaintext.length - 1); assertEquals(encryptionHandler.getMaxInputLength(), (long) plaintext.length - 1); final byte[] out = new byte[1]; assertThrows( IllegalStateException.class, "Plaintext size exceeds max input size limit", () -> encryptionHandler.processBytes(plaintext, 0, plaintext.length, out, 0)); } @Test public void setMaxInputLengthThrowsIfAlreadyOver() { byte[] plaintext = "Don't warn the tadpoles".getBytes(); final EncryptionHandler encryptionHandler = new EncryptionHandler(frameSize_, testResult, commitmentPolicy); final byte[] out = new byte[1024]; encryptionHandler.processBytes(plaintext, 0, plaintext.length - 1, out, 0); assertFalse(encryptionHandler.isComplete()); assertThrows( IllegalStateException.class, "Plaintext size exceeds max input size limit", () -> encryptionHandler.setMaxInputLength(plaintext.length - 2)); } @Test public void setMaxInputLengthAcceptsSmallerValue() { final EncryptionHandler encryptionHandler = new EncryptionHandler(frameSize_, testResult, commitmentPolicy); encryptionHandler.setMaxInputLength(100); assertEquals(encryptionHandler.getMaxInputLength(), 100); encryptionHandler.setMaxInputLength(10); assertEquals(encryptionHandler.getMaxInputLength(), 10); } @Test public void setMaxInputLengthIgnoresLargerValue() { final EncryptionHandler encryptionHandler = new EncryptionHandler(frameSize_, testResult, commitmentPolicy); encryptionHandler.setMaxInputLength(10); assertEquals(encryptionHandler.getMaxInputLength(), 10); encryptionHandler.setMaxInputLength(100); assertEquals(encryptionHandler.getMaxInputLength(), 10); } }
758
0
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk/internal/FrameDecryptionHandlerTest.java
/* * Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except * in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.amazonaws.encryptionsdk.internal; import static org.junit.Assert.assertTrue; import com.amazonaws.encryptionsdk.AwsCrypto; import com.amazonaws.encryptionsdk.CryptoAlgorithm; import com.amazonaws.encryptionsdk.TestUtils; import com.amazonaws.encryptionsdk.exception.AwsCryptoException; import com.amazonaws.encryptionsdk.exception.BadCiphertextException; import java.nio.ByteBuffer; import java.security.SecureRandom; import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec; import org.junit.Before; import org.junit.Test; public class FrameDecryptionHandlerTest { private static final SecureRandom RND = new SecureRandom(); private final CryptoAlgorithm cryptoAlgorithm_ = TestUtils.DEFAULT_TEST_CRYPTO_ALG; private final byte[] messageId_ = new byte[cryptoAlgorithm_.getMessageIdLength()]; private final byte nonceLen_ = cryptoAlgorithm_.getNonceLen(); private final byte[] dataKeyBytes_ = new byte[cryptoAlgorithm_.getKeyLength()]; private final SecretKey dataKey_ = new SecretKeySpec(dataKeyBytes_, "AES"); private final int frameSize_ = AwsCrypto.getDefaultFrameSize(); private final FrameDecryptionHandler frameDecryptionHandler_ = new FrameDecryptionHandler(dataKey_, nonceLen_, cryptoAlgorithm_, messageId_, frameSize_); @Before public void setup() { RND.nextBytes(messageId_); RND.nextBytes(dataKeyBytes_); } @Test public void estimateOutputSize() { final int inLen = 1; final int outSize = frameDecryptionHandler_.estimateOutputSize(inLen); // the estimated output size must at least be equal to inLen. assertTrue(outSize >= inLen); } @Test(expected = AwsCryptoException.class) public void decryptMaxContentLength() { // Create input of size 1 byte: 1 byte of the sequence number, // Only 1 byte of the sequence number is provided because this // forces the frame decryption handler to buffer that 1 byte while // waiting for the remaining bytes of the sequence number. We do this so // we can specify an input of max value and the total bytes to parse // will become max value + 1. final byte[] in = new byte[1]; final byte[] out = new byte[1]; frameDecryptionHandler_.processBytes(in, 0, in.length, out, 0); frameDecryptionHandler_.processBytes(in, 0, Integer.MAX_VALUE, out, 0); } @Test(expected = BadCiphertextException.class) public void finalFrameLengthTooLarge() { final ByteBuffer byteBuffer = ByteBuffer.allocate(25); byteBuffer.put( TestUtils.unsignedBytesToSignedBytes( new int[] {255, 255, 255, 255, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1})); byteBuffer.putInt(AwsCrypto.getDefaultFrameSize() + 1); final byte[] in = byteBuffer.array(); final byte[] out = new byte[in.length]; frameDecryptionHandler_.processBytes(in, 0, in.length, out, 0); } @Test(expected = BadCiphertextException.class) public void doFinalCalledWhileNotComplete() { frameDecryptionHandler_.doFinal(new byte[1], 0); } @Test(expected = AwsCryptoException.class) public void processBytesCalledWhileComplete() { final FrameEncryptionHandler frameEncryptionHandler = new FrameEncryptionHandler(dataKey_, nonceLen_, cryptoAlgorithm_, messageId_, frameSize_); final byte[] in = new byte[0]; final int outLen = frameEncryptionHandler.estimateOutputSize(in.length); final byte[] out = new byte[outLen]; frameEncryptionHandler.processBytes(in, 0, in.length, out, 0); frameEncryptionHandler.doFinal(out, 0); final byte[] decryptedOut = new byte[outLen]; frameDecryptionHandler_.processBytes(out, 0, out.length, decryptedOut, 0); frameDecryptionHandler_.processBytes(out, 0, out.length, decryptedOut, 0); } }
759
0
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk/internal/EncContextSerializerTest.java
/* * Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except * in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.amazonaws.encryptionsdk.internal; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import com.amazonaws.encryptionsdk.exception.AwsCryptoException; import java.nio.ByteBuffer; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.UUID; import org.junit.Test; public class EncContextSerializerTest { @Test public void nullContext() { final byte[] ctxBytes = EncryptionContextSerializer.serialize(null); final Map<String, String> result = EncryptionContextSerializer.deserialize(ctxBytes); assertEquals(null, result); } @Test public void emptyContext() { testMap(Collections.<String, String>emptyMap()); } @Test public void singletonContext() { testMap(Collections.singletonMap("Alice:", "trusts Bob")); } @Test public void contextOrdering() throws Exception { // Context keys should be sorted by unsigned byte order Map<String, String> map = new HashMap<>(); map.put("\0", "\0"); map.put("\u0081", "\u0081"); // 0xC2 0x81 in UTF8 assertArrayEquals( new byte[] { 0, 2, // "\0" 0, 1, (byte) '\0', // "\0" 0, 1, (byte) '\0', // "\u0081" 0, 2, (byte) 0xC2, (byte) 0x81, // "\u0081" 0, 2, (byte) 0xC2, (byte) 0x81, }, EncryptionContextSerializer.serialize(map)); } @Test public void smallContext() { final Map<String, String> map = new HashMap<String, String>(); map.put("Alice:", "trusts Bob"); map.put("Bob:", "trusts Trent"); testMap(map); } @Test public void largeContext() { final int size = 100; final Map<String, String> ctx = new HashMap<String, String>(size); for (int x = 0; x < size; x++) { ctx.put(UUID.randomUUID().toString(), UUID.randomUUID().toString()); } testMap(ctx); } @Test(expected = AwsCryptoException.class) public void overlyLargeContext() { final int size = Short.MAX_VALUE; final Map<String, String> ctx = new HashMap<String, String>(size); // we want to be at least 1 over the (max) size. for (int x = 0; x <= size; x++) { ctx.put(UUID.randomUUID().toString(), UUID.randomUUID().toString()); } testMap(ctx); } @Test(expected = AwsCryptoException.class) public void overlyLargeKey() { final int size = 10; final Map<String, String> ctx = new HashMap<String, String>(size); final char[] keyChars = new char[Short.MAX_VALUE + 1]; final String key = new String(keyChars); for (int x = 0; x < size; x++) { ctx.put(key, UUID.randomUUID().toString()); } testMap(ctx); } @Test(expected = AwsCryptoException.class) public void overlyLargeValue() { final int size = 10; final Map<String, String> ctx = new HashMap<String, String>(size); final char[] valueChars = new char[Short.MAX_VALUE + 1]; final String value = new String(valueChars); for (int x = 0; x < size; x++) { ctx.put(UUID.randomUUID().toString(), value); } testMap(ctx); } @Test(expected = AwsCryptoException.class) public void overlyLargeContextBytes() { final char[] keyChars = new char[Short.MAX_VALUE]; final String key = new String(keyChars); final char[] valueChars = new char[Short.MAX_VALUE]; final String value = new String(valueChars); testMap(Collections.singletonMap(key, value)); } @Test(expected = IllegalArgumentException.class) public void contextWithBadUnicodeKey() { final StringBuilder invalidString = new StringBuilder("Valid text"); // Loop over invalid unicode codepoints for (int x = 0xd800; x <= 0xdfff; x++) { invalidString.appendCodePoint(x); } testMap(Collections.singletonMap(invalidString.toString(), "Valid value")); } @Test(expected = IllegalArgumentException.class) public void contextWithBadUnicodeValue() { final StringBuilder invalidString = new StringBuilder("Base valid text"); for (int x = 0xd800; x <= 0xdfff; x++) { // Invalid unicode codepoints invalidString.appendCodePoint(x); } testMap(Collections.singletonMap("Valid key", invalidString.toString())); } @Test(expected = AwsCryptoException.class) public void contextWithEmptyKey() { testMap(Collections.singletonMap("", "Value for empty key")); } @Test(expected = AwsCryptoException.class) public void contextWithEmptyValue() { testMap(Collections.singletonMap("Key for empty value", "")); } @Test(expected = AwsCryptoException.class) public void contextWithEmptyKeyAndValue() { testMap(Collections.singletonMap("", "")); } @Test(expected = AwsCryptoException.class) public void contextWithNullKey() { testMap(Collections.singletonMap((String) null, "value for null key")); } @Test(expected = AwsCryptoException.class) public void contextWithNullValue() { testMap(Collections.singletonMap("Key for null value", (String) null)); } @Test(expected = AwsCryptoException.class) public void contextWithNullKeyAndValue() { testMap(Collections.singletonMap((String) null, (String) null)); } @Test(expected = AwsCryptoException.class) public void contextWithLargeKey() { final Map<String, String> ctx = new HashMap<String, String>(); ctx.put("Alice:", "trusts Bob"); final byte[] ctxBytes = EncryptionContextSerializer.serialize(Collections.unmodifiableMap(ctx)); final ByteBuffer ctxBuff = ByteBuffer.wrap(ctxBytes); // Pull out entry count to move to key pos ctxBuff.getShort(); // Overwrite key length ctxBuff.putShort((short) Constants.UNSIGNED_SHORT_MAX_VAL); // The actual call which should fail EncryptionContextSerializer.deserialize(ctxBuff.array()); } @Test(expected = AwsCryptoException.class) public void contextWithShortKey() { final Map<String, String> ctx = new HashMap<String, String>(); ctx.put("Alice:", "trusts Bob"); final byte[] ctxBytes = EncryptionContextSerializer.serialize(Collections.unmodifiableMap(ctx)); final ByteBuffer ctxBuff = ByteBuffer.wrap(ctxBytes); // Pull out entry count to move to key pos ctxBuff.getShort(); // Overwrite key length with 0 ctxBuff.putShort((short) 0); // The actual call which should fail EncryptionContextSerializer.deserialize(ctxBuff.array()); } @Test(expected = AwsCryptoException.class) public void contextWithNegativeKey() { final Map<String, String> ctx = new HashMap<String, String>(); ctx.put("Alice:", "trusts Bob"); final byte[] ctxBytes = EncryptionContextSerializer.serialize(Collections.unmodifiableMap(ctx)); final ByteBuffer ctxBuff = ByteBuffer.wrap(ctxBytes); // Pull out entry count to move to key pos ctxBuff.getShort(); // Overwrite key length with -1. ctxBuff.putShort((short) -1); // The actual call which should fail EncryptionContextSerializer.deserialize(ctxBuff.array()); } @Test(expected = AwsCryptoException.class) public void contextWithLargeValue() { final Map<String, String> ctx = new HashMap<String, String>(); ctx.put("Alice:", "trusts Bob"); final byte[] ctxBytes = EncryptionContextSerializer.serialize(Collections.unmodifiableMap(ctx)); final ByteBuffer ctxBuff = ByteBuffer.wrap(ctxBytes); // Pull out entry count to move to key pos ctxBuff.getShort(); // Pull out key length and bytes. final short keyLen = ctxBuff.getShort(); final byte[] key = new byte[keyLen]; ctxBuff.get(key); // Overwrite value length ctxBuff.putShort((short) Constants.UNSIGNED_SHORT_MAX_VAL); // The actual call which should fail EncryptionContextSerializer.deserialize(ctxBuff.array()); } @Test(expected = AwsCryptoException.class) public void contextWithShortValue() { final Map<String, String> ctx = new HashMap<String, String>(); ctx.put("Alice:", "trusts Bob"); final byte[] ctxBytes = EncryptionContextSerializer.serialize(Collections.unmodifiableMap(ctx)); final ByteBuffer ctxBuff = ByteBuffer.wrap(ctxBytes); // Pull out entry count to move to key pos ctxBuff.getShort(); // Pull out key length and bytes. final short keyLen = ctxBuff.getShort(); final byte[] key = new byte[keyLen]; ctxBuff.get(key); // Overwrite value length ctxBuff.putShort((short) 0); // The actual call which should fail EncryptionContextSerializer.deserialize(ctxBuff.array()); } @Test(expected = AwsCryptoException.class) public void contextWithNegativeValue() { final Map<String, String> ctx = new HashMap<String, String>(); ctx.put("Alice:", "trusts Bob"); final byte[] ctxBytes = EncryptionContextSerializer.serialize(Collections.unmodifiableMap(ctx)); final ByteBuffer ctxBuff = ByteBuffer.wrap(ctxBytes); // Pull out entry count to move to key pos ctxBuff.getShort(); // Pull out key length and bytes. final short keyLen = ctxBuff.getShort(); final byte[] key = new byte[keyLen]; ctxBuff.get(key); // Overwrite value length ctxBuff.putShort((short) -1); // The actual call which should fail EncryptionContextSerializer.deserialize(ctxBuff.array()); } @Test(expected = AwsCryptoException.class) public void contextWithNegativeCount() { final Map<String, String> ctx = new HashMap<String, String>(); ctx.put("Alice:", "trusts Bob"); ctx.put("Bob:", "trusts Trent"); final byte[] ctxBytes = EncryptionContextSerializer.serialize(Collections.unmodifiableMap(ctx)); final ByteBuffer ctxBuff = ByteBuffer.wrap(ctxBytes); // Overwrite entry count ctxBuff.putShort((short) -1); EncryptionContextSerializer.deserialize(ctxBuff.array()); } @Test(expected = AwsCryptoException.class) public void contextWithZeroCount() { final Map<String, String> ctx = new HashMap<String, String>(); ctx.put("Alice:", "trusts Bob"); ctx.put("Bob:", "trusts Trent"); final byte[] ctxBytes = EncryptionContextSerializer.serialize(Collections.unmodifiableMap(ctx)); final ByteBuffer ctxBuff = ByteBuffer.wrap(ctxBytes); // Overwrite entry count ctxBuff.putShort((short) 0); EncryptionContextSerializer.deserialize(ctxBuff.array()); } @Test(expected = AwsCryptoException.class) public void contextWithInvalidCount() { final Map<String, String> ctx = new HashMap<String, String>(); ctx.put("Alice:", "trusts Bob"); ctx.put("Bob:", "trusts Trent"); final byte[] ctxBytes = EncryptionContextSerializer.serialize(Collections.unmodifiableMap(ctx)); final ByteBuffer ctxBuff = ByteBuffer.wrap(ctxBytes); // Overwrite count with more than what we have ctxBuff.putShort((short) 100); // The actual call which should fail EncryptionContextSerializer.deserialize(ctxBuff.array()); } @Test(expected = IllegalArgumentException.class) public void contextWithInvalidCharacters() { final Map<String, String> ctx = new HashMap<String, String>(); ctx.put("Alice:", "trusts Bob"); final byte[] ctxBytes = EncryptionContextSerializer.serialize(Collections.unmodifiableMap(ctx)); final ByteBuffer ctxBuff = ByteBuffer.wrap(ctxBytes); // Pull out entry count to move to key pos ctxBuff.getShort(); // Pull out key length and bytes. final short keyLen = ctxBuff.getShort(); ctxBuff.mark(); final byte[] key = new byte[keyLen]; ctxBuff.get(key); // set the first two bytes of the key to an invalid // unicode character: 0xd800. key[0] = 0x0; key[1] = (byte) 0xd8; ctxBuff.reset(); ctxBuff.put(key); // The actual call which should fail EncryptionContextSerializer.deserialize(ctxBuff.array()); } @Test(expected = AwsCryptoException.class) public void contextWithDuplicateEntries() { final Map<String, String> ctx = Collections.singletonMap("Alice:", "trusts Bob"); final byte[] ctxBytes = EncryptionContextSerializer.serialize(Collections.unmodifiableMap(ctx)); final ByteBuffer ctxBuff = ByteBuffer.wrap(ctxBytes); // Don't duplicate the entry count final ByteBuffer dupCtxBuff = ByteBuffer.allocate((2 * ctxBytes.length) - 2); // Set to 2 entries dupCtxBuff.putShort((short) 2); // Pull out entry count to move to key pos ctxBuff.getShort(); // From here to the end is a single entry, copy it final byte[] entry = new byte[ctxBuff.remaining()]; ctxBuff.get(entry); dupCtxBuff.put(entry); dupCtxBuff.put(entry); EncryptionContextSerializer.deserialize(dupCtxBuff.array()); } private void testMap(final Map<String, String> ctx) { final byte[] ctxBytes = EncryptionContextSerializer.serialize(Collections.unmodifiableMap(ctx)); final Map<String, String> result = EncryptionContextSerializer.deserialize(ctxBytes); assertEquals(ctx, result); } }
760
0
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk/internal/BlockEncryptionHandlerTest.java
/* * Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except * in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.amazonaws.encryptionsdk.internal; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import com.amazonaws.encryptionsdk.CryptoAlgorithm; import com.amazonaws.encryptionsdk.TestUtils; import com.amazonaws.encryptionsdk.model.CipherBlockHeaders; import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec; import org.junit.Before; import org.junit.Test; public class BlockEncryptionHandlerTest { private final CryptoAlgorithm cryptoAlgorithm_ = TestUtils.DEFAULT_TEST_CRYPTO_ALG; private final byte[] messageId_ = RandomBytesGenerator.generate(cryptoAlgorithm_.getMessageIdLength()); private final byte nonceLen_ = cryptoAlgorithm_.getNonceLen(); private final byte[] dataKeyBytes_ = RandomBytesGenerator.generate(cryptoAlgorithm_.getKeyLength()); private final SecretKey encryptionKey_ = new SecretKeySpec(dataKeyBytes_, "AES"); private BlockEncryptionHandler blockEncryptionHandler_; @Before public void setUp() throws Exception { blockEncryptionHandler_ = new BlockEncryptionHandler(encryptionKey_, nonceLen_, cryptoAlgorithm_, messageId_); } @Test public void emptyOutBytes() { final int outLen = 0; final byte[] out = new byte[outLen]; final int processedLen = blockEncryptionHandler_.doFinal(out, 0); assertEquals(outLen, processedLen); } @Test public void correctIVGenerated() throws Exception { final byte[] out = new byte[1024]; int outOff = blockEncryptionHandler_.processBytes(new byte[1], 0, 1, out, 0).getBytesWritten(); final int processedLen = blockEncryptionHandler_.doFinal(out, outOff); CipherBlockHeaders headers = new CipherBlockHeaders(); headers.setNonceLength(cryptoAlgorithm_.getNonceLen()); headers.deserialize(out, 0); assertArrayEquals( new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 }, headers.getNonce()); } }
761
0
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk/internal/DecryptionHandlerTest.java
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package com.amazonaws.encryptionsdk.internal; import static com.amazonaws.encryptionsdk.TestUtils.assertThrows; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import com.amazonaws.encryptionsdk.AwsCrypto; import com.amazonaws.encryptionsdk.CommitmentPolicy; import com.amazonaws.encryptionsdk.CryptoAlgorithm; import com.amazonaws.encryptionsdk.DefaultCryptoMaterialsManager; import com.amazonaws.encryptionsdk.MasterKey; import com.amazonaws.encryptionsdk.MasterKeyProvider; import com.amazonaws.encryptionsdk.ParsedCiphertext; import com.amazonaws.encryptionsdk.TestUtils; import com.amazonaws.encryptionsdk.exception.AwsCryptoException; import com.amazonaws.encryptionsdk.exception.BadCiphertextException; import com.amazonaws.encryptionsdk.jce.JceMasterKey; import com.amazonaws.encryptionsdk.model.CiphertextHeaders; import com.amazonaws.encryptionsdk.model.CiphertextType; import com.amazonaws.encryptionsdk.model.EncryptionMaterials; import com.amazonaws.encryptionsdk.model.EncryptionMaterialsRequest; import com.amazonaws.encryptionsdk.multi.MultipleProviderFactory; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Map; import org.junit.Before; import org.junit.Test; public class DecryptionHandlerTest { private StaticMasterKey masterKeyProvider_; private final CommitmentPolicy commitmentPolicy = TestUtils.DEFAULT_TEST_COMMITMENT_POLICY; private final CommitmentPolicy requireReadPolicy = CommitmentPolicy.RequireEncryptRequireDecrypt; private final List<CommitmentPolicy> allowReadPolicies = Arrays.asList( CommitmentPolicy.RequireEncryptAllowDecrypt, CommitmentPolicy.ForbidEncryptAllowDecrypt); private final SignaturePolicy signaturePolicy = SignaturePolicy.AllowEncryptAllowDecrypt; @Before public void init() { masterKeyProvider_ = new StaticMasterKey("testmaterial"); } @Test(expected = NullPointerException.class) public void nullMasterKey() { DecryptionHandler.create( (MasterKey) null, commitmentPolicy, signaturePolicy, CiphertextHeaders.NO_MAX_ENCRYPTED_DATA_KEYS); } @Test public void nullCommitment() { final byte[] ciphertext = getTestHeaders( CryptoAlgorithm.ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA384_ECDSA_P384, CommitmentPolicy.ForbidEncryptAllowDecrypt); assertThrows( NullPointerException.class, () -> DecryptionHandler.create( masterKeyProvider_, new ParsedCiphertext(ciphertext), null, signaturePolicy, CiphertextHeaders.NO_MAX_ENCRYPTED_DATA_KEYS)); assertThrows( NullPointerException.class, () -> DecryptionHandler.create( masterKeyProvider_, null, signaturePolicy, CiphertextHeaders.NO_MAX_ENCRYPTED_DATA_KEYS)); } @Test public void nullSignaturePolicy() { final byte[] ciphertext = getTestHeaders( CryptoAlgorithm.ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA384_ECDSA_P384, CommitmentPolicy.ForbidEncryptAllowDecrypt); assertThrows( NullPointerException.class, () -> DecryptionHandler.create( masterKeyProvider_, new ParsedCiphertext(ciphertext), commitmentPolicy, null, CiphertextHeaders.NO_MAX_ENCRYPTED_DATA_KEYS)); assertThrows( NullPointerException.class, () -> DecryptionHandler.create( masterKeyProvider_, commitmentPolicy, null, CiphertextHeaders.NO_MAX_ENCRYPTED_DATA_KEYS)); } @Test(expected = AwsCryptoException.class) public void invalidLenProcessBytes() { final DecryptionHandler<StaticMasterKey> decryptionHandler = DecryptionHandler.create( masterKeyProvider_, commitmentPolicy, signaturePolicy, CiphertextHeaders.NO_MAX_ENCRYPTED_DATA_KEYS); final byte[] in = new byte[1]; final byte[] out = new byte[1]; decryptionHandler.processBytes(in, 0, -1, out, 0); } @Test(expected = AwsCryptoException.class) public void maxLenProcessBytes() { final DecryptionHandler<StaticMasterKey> decryptionHandler = DecryptionHandler.create( masterKeyProvider_, commitmentPolicy, signaturePolicy, CiphertextHeaders.NO_MAX_ENCRYPTED_DATA_KEYS); // Create input of size 3 bytes: 1 byte containing version, 1 byte // containing type, and 1 byte containing half of the algoId short // primitive. Only 1 byte of the algoId is provided because this // forces the decryption handler to buffer that 1 byte while waiting for // the other byte. We do this so we can specify an input of max // value and the total bytes to parse will become max value + 1. final byte[] in = new byte[3]; final byte[] out = new byte[3]; in[1] = CiphertextType.CUSTOMER_AUTHENTICATED_ENCRYPTED_DATA.getValue(); decryptionHandler.processBytes(in, 0, in.length, out, 0); decryptionHandler.processBytes(in, 0, Integer.MAX_VALUE, out, 0); } @Test public void maxInputLength() { final byte[] testMessage = getTestMessage( TestUtils.DEFAULT_TEST_CRYPTO_ALG, CommitmentPolicy.RequireEncryptRequireDecrypt); final byte[] out = new byte[100]; final DecryptionHandler<StaticMasterKey> decryptionHandler = DecryptionHandler.create( masterKeyProvider_, commitmentPolicy, signaturePolicy, CiphertextHeaders.NO_MAX_ENCRYPTED_DATA_KEYS); decryptionHandler.setMaxInputLength(testMessage.length - 1); assertThrows( IllegalStateException.class, () -> decryptionHandler.processBytes(testMessage, 0, testMessage.length, out, 0)); } @Test public void maxInputLengthIncludingParsedCiphertext() { final byte[] testMessage = getTestMessage( TestUtils.DEFAULT_TEST_CRYPTO_ALG, CommitmentPolicy.RequireEncryptRequireDecrypt); final byte[] out = new byte[100]; ParsedCiphertext parsedHeaders = new ParsedCiphertext(testMessage); final DecryptionHandler<StaticMasterKey> decryptionHandler = DecryptionHandler.create( masterKeyProvider_, parsedHeaders, commitmentPolicy, signaturePolicy, CiphertextHeaders.NO_MAX_ENCRYPTED_DATA_KEYS); decryptionHandler.setMaxInputLength(testMessage.length - 1); assertThrows( IllegalStateException.class, () -> decryptionHandler.processBytes( testMessage, parsedHeaders.getOffset(), testMessage.length - parsedHeaders.getOffset(), out, 0)); } @Test public void maxInputLengthIncludingCiphertextHeaders() { final byte[] testMessage = getTestMessage( TestUtils.DEFAULT_TEST_CRYPTO_ALG, CommitmentPolicy.RequireEncryptRequireDecrypt); final byte[] out = new byte[100]; ParsedCiphertext parsedHeaders = new ParsedCiphertext(testMessage); CiphertextHeaders headers = new CiphertextHeaders(); headers.deserialize( parsedHeaders.getCiphertext(), 0, CiphertextHeaders.NO_MAX_ENCRYPTED_DATA_KEYS); final DecryptionHandler<StaticMasterKey> decryptionHandler = DecryptionHandler.create( masterKeyProvider_, headers, commitmentPolicy, signaturePolicy, CiphertextHeaders.NO_MAX_ENCRYPTED_DATA_KEYS); decryptionHandler.setMaxInputLength(testMessage.length - 1); assertThrows( IllegalStateException.class, () -> decryptionHandler.processBytes( testMessage, parsedHeaders.getOffset(), testMessage.length - parsedHeaders.getOffset(), out, 0)); } @Test(expected = BadCiphertextException.class) public void headerIntegrityFailure() { byte[] ciphertext = getTestHeaders(); // tamper the fifth byte in the header which corresponds to the first // byte of the message identifier. We do this because tampering the // first four bytes will be detected as invalid values during parsing. ciphertext[5] += 1; // attempt to decrypt with the tampered header. final DecryptionHandler<StaticMasterKey> decryptionHandler = DecryptionHandler.create( masterKeyProvider_, commitmentPolicy, signaturePolicy, CiphertextHeaders.NO_MAX_ENCRYPTED_DATA_KEYS); final int plaintextLen = decryptionHandler.estimateOutputSize(ciphertext.length); final byte[] plaintext = new byte[plaintextLen]; decryptionHandler.processBytes(ciphertext, 0, ciphertext.length, plaintext, 0); } @Test(expected = BadCiphertextException.class) public void invalidVersion() { byte[] ciphertext = getTestHeaders(); // set byte containing version to invalid value. ciphertext[0] = 0; // NOTE: This will need to be updated should 0 ever be a valid version // attempt to decrypt with the tampered header. final DecryptionHandler<StaticMasterKey> decryptionHandler = DecryptionHandler.create( masterKeyProvider_, commitmentPolicy, signaturePolicy, CiphertextHeaders.NO_MAX_ENCRYPTED_DATA_KEYS); final int plaintextLen = decryptionHandler.estimateOutputSize(ciphertext.length); final byte[] plaintext = new byte[plaintextLen]; decryptionHandler.processBytes(ciphertext, 0, ciphertext.length, plaintext, 0); } @Test(expected = AwsCryptoException.class) public void invalidCMK() { final byte[] ciphertext = getTestHeaders(); masterKeyProvider_.setKeyId(masterKeyProvider_.getKeyId() + "nonsense"); // attempt to decrypt with the tampered header. final DecryptionHandler<StaticMasterKey> decryptionHandler = DecryptionHandler.create( masterKeyProvider_, commitmentPolicy, signaturePolicy, CiphertextHeaders.NO_MAX_ENCRYPTED_DATA_KEYS); final int plaintextLen = decryptionHandler.estimateOutputSize(ciphertext.length); final byte[] plaintext = new byte[plaintextLen]; decryptionHandler.processBytes(ciphertext, 0, ciphertext.length, plaintext, 0); } @Test public void validAlgForCommitmentPolicyCreate() { // ensure we can decrypt non-committing algs with the policies that allow it final CryptoAlgorithm nonCommittingAlg = CryptoAlgorithm.ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA256; for (CommitmentPolicy policy : allowReadPolicies) { final byte[] ciphertext = getTestHeaders(nonCommittingAlg, CommitmentPolicy.ForbidEncryptAllowDecrypt); final DecryptionHandler<StaticMasterKey> decryptionHandler = DecryptionHandler.create( masterKeyProvider_, policy, signaturePolicy, CiphertextHeaders.NO_MAX_ENCRYPTED_DATA_KEYS); // expected plaintext is zero length final byte[] plaintext = new byte[0]; ProcessingSummary processingSummary = decryptionHandler.processBytes(ciphertext, 0, ciphertext.length, plaintext, 0); assertEquals(ciphertext.length, processingSummary.getBytesProcessed()); assertArrayEquals(new byte[0], plaintext); } // ensure we can decrypt committing algs with all policies final CryptoAlgorithm committingAlg = CryptoAlgorithm.ALG_AES_256_GCM_HKDF_SHA512_COMMIT_KEY; for (CommitmentPolicy policy : CommitmentPolicy.values()) { final byte[] ciphertext = getTestHeaders(committingAlg, CommitmentPolicy.RequireEncryptRequireDecrypt); final DecryptionHandler<StaticMasterKey> decryptionHandler = DecryptionHandler.create( masterKeyProvider_, policy, signaturePolicy, CiphertextHeaders.NO_MAX_ENCRYPTED_DATA_KEYS); // expected plaintext is zero length final byte[] plaintext = new byte[0]; ProcessingSummary processingSummary = decryptionHandler.processBytes(ciphertext, 0, ciphertext.length, plaintext, 0); assertEquals(ciphertext.length, processingSummary.getBytesProcessed()); assertArrayEquals(new byte[0], plaintext); } } @Test public void invalidAlgForCommitmentPolicyCreateWithoutHeaders() { final CryptoAlgorithm nonCommittingAlg = CryptoAlgorithm.ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA384_ECDSA_P384; final byte[] ciphertext = getTestHeaders(nonCommittingAlg, CommitmentPolicy.ForbidEncryptAllowDecrypt); final DecryptionHandler<StaticMasterKey> decryptionHandler = DecryptionHandler.create( masterKeyProvider_, requireReadPolicy, signaturePolicy, CiphertextHeaders.NO_MAX_ENCRYPTED_DATA_KEYS); final int plaintextLen = decryptionHandler.estimateOutputSize(ciphertext.length); final byte[] plaintext = new byte[plaintextLen]; assertThrows( AwsCryptoException.class, () -> decryptionHandler.processBytes(ciphertext, 0, ciphertext.length, plaintext, 0)); } @Test public void invalidAlgForCommitmentPolicyCreateWithHeaders() { final CryptoAlgorithm nonCommittingAlg = CryptoAlgorithm.ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA384_ECDSA_P384; final byte[] ciphertext = getTestHeaders(nonCommittingAlg, CommitmentPolicy.ForbidEncryptAllowDecrypt); assertThrows( AwsCryptoException.class, () -> DecryptionHandler.create( masterKeyProvider_, new ParsedCiphertext(ciphertext), requireReadPolicy, signaturePolicy, CiphertextHeaders.NO_MAX_ENCRYPTED_DATA_KEYS)); } @Test public void validAlgForSignaturePolicyCreate() { // ensure we can decrypt non-signing algs with the policy that allows it final CryptoAlgorithm nonSigningAlg = CryptoAlgorithm.ALG_AES_256_GCM_HKDF_SHA512_COMMIT_KEY; final byte[] ciphertext = getTestHeaders(nonSigningAlg, commitmentPolicy); final DecryptionHandler<StaticMasterKey> decryptionHandler = DecryptionHandler.create( masterKeyProvider_, commitmentPolicy, SignaturePolicy.AllowEncryptAllowDecrypt, CiphertextHeaders.NO_MAX_ENCRYPTED_DATA_KEYS); // expected plaintext is zero length final byte[] plaintext = new byte[0]; ProcessingSummary processingSummary = decryptionHandler.processBytes(ciphertext, 0, ciphertext.length, plaintext, 0); assertEquals(ciphertext.length, processingSummary.getBytesProcessed()); assertArrayEquals(new byte[0], plaintext); } @Test public void invalidAlgForSignaturePolicyCreateWithoutHeaders() { final CryptoAlgorithm signingAlg = CryptoAlgorithm.ALG_AES_256_GCM_HKDF_SHA512_COMMIT_KEY_ECDSA_P384; final byte[] ciphertext = getTestHeaders(signingAlg, commitmentPolicy); final DecryptionHandler<StaticMasterKey> decryptionHandler = DecryptionHandler.create( masterKeyProvider_, commitmentPolicy, SignaturePolicy.AllowEncryptForbidDecrypt, CiphertextHeaders.NO_MAX_ENCRYPTED_DATA_KEYS); final int plaintextLen = decryptionHandler.estimateOutputSize(ciphertext.length); final byte[] plaintext = new byte[plaintextLen]; assertThrows( AwsCryptoException.class, () -> decryptionHandler.processBytes(ciphertext, 0, ciphertext.length, plaintext, 0)); } @Test public void invalidAlgForSignaturePolicyCreateWithHeaders() { final CryptoAlgorithm signingAlg = CryptoAlgorithm.ALG_AES_256_GCM_HKDF_SHA512_COMMIT_KEY_ECDSA_P384; final byte[] ciphertext = getTestHeaders(signingAlg, commitmentPolicy); assertThrows( AwsCryptoException.class, () -> DecryptionHandler.create( masterKeyProvider_, new ParsedCiphertext(ciphertext), commitmentPolicy, SignaturePolicy.AllowEncryptForbidDecrypt, CiphertextHeaders.NO_MAX_ENCRYPTED_DATA_KEYS)); } private byte[] getTestHeaders() { return getTestHeaders( TestUtils.DEFAULT_TEST_CRYPTO_ALG, TestUtils.DEFAULT_TEST_COMMITMENT_POLICY, 1); } private byte[] getTestHeaders(CryptoAlgorithm cryptoAlgorithm, CommitmentPolicy policy) { return getTestHeaders(cryptoAlgorithm, policy, 1); } private byte[] getTestHeaders(int numEdks) { return getTestHeaders( TestUtils.DEFAULT_TEST_CRYPTO_ALG, TestUtils.DEFAULT_TEST_COMMITMENT_POLICY, numEdks); } private byte[] getTestHeaders( CryptoAlgorithm cryptoAlgorithm, CommitmentPolicy policy, int numEdks) { // Note that it's questionable to assume that failing to call doFinal() on the encryption // handler // always results in only outputting the header! return getTestMessage(cryptoAlgorithm, policy, numEdks, false); } private byte[] getTestMessage(CryptoAlgorithm cryptoAlgorithm, CommitmentPolicy policy) { return getTestMessage(cryptoAlgorithm, policy, 1, true); } private byte[] getTestMessage( CryptoAlgorithm cryptoAlgorithm, CommitmentPolicy policy, int numEdks, boolean doFinal) { final int frameSize_ = AwsCrypto.getDefaultFrameSize(); final Map<String, String> encryptionContext = Collections.<String, String>emptyMap(); final EncryptionMaterialsRequest encryptionMaterialsRequest = EncryptionMaterialsRequest.newBuilder() .setContext(encryptionContext) .setRequestedAlgorithm(cryptoAlgorithm) .setCommitmentPolicy(policy) .build(); List<MasterKeyProvider<?>> providers = new ArrayList<>(); for (int i = 0; i < numEdks; i++) { providers.add(masterKeyProvider_); } MasterKeyProvider<?> provider = MultipleProviderFactory.buildMultiProvider(providers); final EncryptionMaterials encryptionMaterials = new DefaultCryptoMaterialsManager(provider) .getMaterialsForEncrypt(encryptionMaterialsRequest); final EncryptionHandler encryptionHandler = new EncryptionHandler(frameSize_, encryptionMaterials, policy); // create the ciphertext headers by calling encryption handler. final byte[] in = new byte[0]; final int ciphertextLen = encryptionHandler.estimateOutputSize(in.length); final byte[] ciphertext = new byte[ciphertextLen]; ProcessingSummary summary = encryptionHandler.processBytes(in, 0, in.length, ciphertext, 0); if (doFinal) { encryptionHandler.doFinal(ciphertext, summary.getBytesWritten()); } return ciphertext; } @Test(expected = AwsCryptoException.class) public void invalidOffsetProcessBytes() { final DecryptionHandler<StaticMasterKey> decryptionHandler = DecryptionHandler.create( masterKeyProvider_, commitmentPolicy, signaturePolicy, CiphertextHeaders.NO_MAX_ENCRYPTED_DATA_KEYS); final byte[] in = new byte[1]; final byte[] out = new byte[1]; decryptionHandler.processBytes(in, -1, in.length, out, 0); } @Test(expected = BadCiphertextException.class) public void incompleteCiphertext() { byte[] ciphertext = getTestHeaders(); CiphertextHeaders h = new CiphertextHeaders(); h.deserialize(ciphertext, 0, CiphertextHeaders.NO_MAX_ENCRYPTED_DATA_KEYS); final DecryptionHandler<StaticMasterKey> decryptionHandler = DecryptionHandler.create( masterKeyProvider_, commitmentPolicy, signaturePolicy, CiphertextHeaders.NO_MAX_ENCRYPTED_DATA_KEYS); final byte[] out = new byte[1]; // Note the " - 1" is a bit deceptive: the ciphertext SHOULD already be incomplete because we // called getTestHeaders() above, so the whole body is missing! decryptionHandler.processBytes(ciphertext, 0, ciphertext.length - 1, out, 0); decryptionHandler.doFinal(out, 0); } @Test public void incompleteCiphertextV2() { byte[] ciphertext = Utils.decodeBase64String(TestUtils.messageWithCommitKeyBase64); final DecryptionHandler<JceMasterKey> decryptionHandler = DecryptionHandler.create( TestUtils.messageWithCommitKeyMasterKey, CommitmentPolicy.RequireEncryptRequireDecrypt, signaturePolicy, CiphertextHeaders.NO_MAX_ENCRYPTED_DATA_KEYS); final byte[] out = new byte[1]; decryptionHandler.processBytes(ciphertext, 0, ciphertext.length - 1, out, 0); assertThrows( BadCiphertextException.class, "Unable to process entire ciphertext.", () -> decryptionHandler.doFinal(out, 0)); } @Test public void incompleteCiphertextSigned() { byte[] ciphertext = getTestMessage( CryptoAlgorithm.ALG_AES_256_GCM_HKDF_SHA512_COMMIT_KEY_ECDSA_P384, CommitmentPolicy.RequireEncryptRequireDecrypt); final DecryptionHandler<StaticMasterKey> decryptionHandler = DecryptionHandler.create( masterKeyProvider_, CommitmentPolicy.RequireEncryptRequireDecrypt, signaturePolicy, CiphertextHeaders.NO_MAX_ENCRYPTED_DATA_KEYS); final byte[] out = new byte[1]; decryptionHandler.processBytes(ciphertext, 0, ciphertext.length - 1, out, 0); assertThrows( BadCiphertextException.class, "Unable to process entire ciphertext.", () -> decryptionHandler.doFinal(out, 0)); } @Test public void headerV2HeaderIntegrityFailure() { byte[] ciphertext = Utils.decodeBase64String(TestUtils.messageWithCommitKeyBase64); // Tamper the bytes that corresponds to the frame length. // This is the only reasonable way to tamper with this handcrafted message's // header which can still be successfully parsed. ciphertext[134] += 1; // attempt to decrypt with the tampered header. final DecryptionHandler<JceMasterKey> decryptionHandler = DecryptionHandler.create( TestUtils.messageWithCommitKeyMasterKey, CommitmentPolicy.RequireEncryptRequireDecrypt, signaturePolicy, CiphertextHeaders.NO_MAX_ENCRYPTED_DATA_KEYS); final int plaintextLen = decryptionHandler.estimateOutputSize(ciphertext.length); final byte[] plaintext = new byte[plaintextLen]; assertThrows( BadCiphertextException.class, "Header integrity check failed", () -> decryptionHandler.processBytes(ciphertext, 0, ciphertext.length, plaintext, 0)); } @Test public void headerV2BodyIntegrityFailure() { byte[] ciphertext = Utils.decodeBase64String(TestUtils.messageWithCommitKeyBase64); // Tamper the bytes that corresponds to the body auth ciphertext[ciphertext.length - 1] += 1; // attempt to decrypt with the tampered header. final DecryptionHandler<JceMasterKey> decryptionHandler = DecryptionHandler.create( TestUtils.messageWithCommitKeyMasterKey, CommitmentPolicy.RequireEncryptRequireDecrypt, signaturePolicy, CiphertextHeaders.NO_MAX_ENCRYPTED_DATA_KEYS); final int plaintextLen = decryptionHandler.estimateOutputSize(ciphertext.length); final byte[] plaintext = new byte[plaintextLen]; assertThrows( BadCiphertextException.class, "Tag mismatch", () -> decryptionHandler.processBytes(ciphertext, 0, ciphertext.length, plaintext, 0)); } @Test public void withLessThanMaxEdks() { byte[] header = getTestHeaders(2); final DecryptionHandler<StaticMasterKey> decryptionHandler = DecryptionHandler.create( masterKeyProvider_, CommitmentPolicy.RequireEncryptAllowDecrypt, signaturePolicy, 3); final int plaintextLen = decryptionHandler.estimateOutputSize(header.length); final byte[] plaintext = new byte[plaintextLen]; decryptionHandler.processBytes(header, 0, header.length, plaintext, 0); } @Test public void withMaxEdks() { byte[] header = getTestHeaders(3); final DecryptionHandler<StaticMasterKey> decryptionHandler = DecryptionHandler.create( masterKeyProvider_, CommitmentPolicy.RequireEncryptAllowDecrypt, signaturePolicy, 3); final int plaintextLen = decryptionHandler.estimateOutputSize(header.length); final byte[] plaintext = new byte[plaintextLen]; decryptionHandler.processBytes(header, 0, header.length, plaintext, 0); } @Test public void withMoreThanMaxEdks() { byte[] header = getTestHeaders(4); final DecryptionHandler<StaticMasterKey> decryptionHandler = DecryptionHandler.create( masterKeyProvider_, CommitmentPolicy.RequireEncryptAllowDecrypt, signaturePolicy, 3); final int plaintextLen = decryptionHandler.estimateOutputSize(header.length); final byte[] plaintext = new byte[plaintextLen]; assertThrows( AwsCryptoException.class, "Ciphertext encrypted data keys exceed maxEncryptedDataKeys", () -> decryptionHandler.processBytes(header, 0, header.length, plaintext, 0)); } @Test public void withNoMaxEdks() { byte[] header = getTestHeaders(1 << 16 - 1); final DecryptionHandler<StaticMasterKey> decryptionHandler = DecryptionHandler.create( masterKeyProvider_, CommitmentPolicy.RequireEncryptAllowDecrypt, signaturePolicy, CiphertextHeaders.NO_MAX_ENCRYPTED_DATA_KEYS); final int plaintextLen = decryptionHandler.estimateOutputSize(header.length); final byte[] plaintext = new byte[plaintextLen]; decryptionHandler.processBytes(header, 0, header.length, plaintext, 0); } @Test public void validSignatureAcrossMultipleBlocks() { byte[] ciphertext = getTestMessage( CryptoAlgorithm.ALG_AES_256_GCM_HKDF_SHA512_COMMIT_KEY_ECDSA_P384, CommitmentPolicy.RequireEncryptRequireDecrypt); final DecryptionHandler<StaticMasterKey> decryptionHandler = DecryptionHandler.create( masterKeyProvider_, CommitmentPolicy.RequireEncryptRequireDecrypt, signaturePolicy, CiphertextHeaders.NO_MAX_ENCRYPTED_DATA_KEYS); final byte[] out = new byte[1]; // Parse the header and body final int headerLength = 388; decryptionHandler.processBytes(ciphertext, 0, headerLength, out, 0); // Parse the footer across two calls // This used to fail to verify the signature because partial bytes were dropped instead. // The overall decryption would still succeed because the completeness check in doFinal // used to not include the footer. // The number of bytes read in the first chunk is completely arbitrary. The // parameterized CryptoOutputStreamTest tests covers lots of possible chunk // sizes much more thoroughly. This is just a very explicit regression unit test for a known // issue that is now fixed. final int firstChunkLength = 12; final int firstChunkOffset = headerLength; final int secondChunkOffset = headerLength + firstChunkLength; final int secondChunkLength = ciphertext.length - secondChunkOffset; decryptionHandler.processBytes(ciphertext, firstChunkOffset, firstChunkLength, out, 0); decryptionHandler.processBytes(ciphertext, secondChunkOffset, secondChunkLength, out, 0); decryptionHandler.doFinal(out, 0); } @Test public void invalidSignatureAcrossMultipleBlocks() { byte[] ciphertext = getTestMessage( CryptoAlgorithm.ALG_AES_256_GCM_HKDF_SHA512_COMMIT_KEY_ECDSA_P384, CommitmentPolicy.RequireEncryptRequireDecrypt); final DecryptionHandler<StaticMasterKey> decryptionHandler = DecryptionHandler.create( masterKeyProvider_, CommitmentPolicy.RequireEncryptRequireDecrypt, signaturePolicy, CiphertextHeaders.NO_MAX_ENCRYPTED_DATA_KEYS); final byte[] out = new byte[1]; // Parse the header and body decryptionHandler.processBytes(ciphertext, 0, 388, out, 0); // Process extra bytes before processing the actual signature bytes. // This used to actually work because the handler failed to buffer the unparsed bytes // across calls. To regression test this properly we have to parse the two bytes for the // length... decryptionHandler.processBytes(ciphertext, 388, 2, out, 0); // ...and after that any bytes fewer than that length would previously be dropped. decryptionHandler.processBytes(new byte[10], 0, 10, out, 0); assertThrows( BadCiphertextException.class, "Bad trailing signature", () -> decryptionHandler.processBytes(ciphertext, 390, ciphertext.length - 390, out, 0)); } @Test public void setMaxInputLength() { byte[] ciphertext = getTestMessage( CryptoAlgorithm.ALG_AES_256_GCM_HKDF_SHA512_COMMIT_KEY_ECDSA_P384, CommitmentPolicy.RequireEncryptRequireDecrypt); final DecryptionHandler<StaticMasterKey> decryptionHandler = DecryptionHandler.create( masterKeyProvider_, CommitmentPolicy.RequireEncryptRequireDecrypt, signaturePolicy, CiphertextHeaders.NO_MAX_ENCRYPTED_DATA_KEYS); decryptionHandler.setMaxInputLength(ciphertext.length - 1); assertEquals(decryptionHandler.getMaxInputLength(), (long) ciphertext.length - 1); final byte[] out = new byte[1]; assertThrows( IllegalStateException.class, "Ciphertext size exceeds size bound", () -> decryptionHandler.processBytes(ciphertext, 0, ciphertext.length, out, 0)); } @Test public void setMaxInputLengthThrowsIfAlreadyOver() { byte[] ciphertext = getTestMessage( CryptoAlgorithm.ALG_AES_256_GCM_HKDF_SHA512_COMMIT_KEY_ECDSA_P384, CommitmentPolicy.RequireEncryptRequireDecrypt); final DecryptionHandler<StaticMasterKey> decryptionHandler = DecryptionHandler.create( masterKeyProvider_, CommitmentPolicy.RequireEncryptRequireDecrypt, signaturePolicy, CiphertextHeaders.NO_MAX_ENCRYPTED_DATA_KEYS); final byte[] out = new byte[1]; decryptionHandler.processBytes(ciphertext, 0, ciphertext.length - 1, out, 0); assertFalse(decryptionHandler.isComplete()); assertThrows( IllegalStateException.class, "Ciphertext size exceeds size bound", () -> decryptionHandler.setMaxInputLength(ciphertext.length - 2)); } @Test public void setMaxInputLengthAcceptsSmallerValue() { final DecryptionHandler<StaticMasterKey> decryptionHandler = DecryptionHandler.create( masterKeyProvider_, CommitmentPolicy.RequireEncryptRequireDecrypt, signaturePolicy, CiphertextHeaders.NO_MAX_ENCRYPTED_DATA_KEYS); decryptionHandler.setMaxInputLength(100); assertEquals(decryptionHandler.getMaxInputLength(), 100); decryptionHandler.setMaxInputLength(10); assertEquals(decryptionHandler.getMaxInputLength(), 10); } @Test public void setMaxInputLengthIgnoresLargerValue() { final DecryptionHandler<StaticMasterKey> decryptionHandler = DecryptionHandler.create( masterKeyProvider_, CommitmentPolicy.RequireEncryptRequireDecrypt, signaturePolicy, CiphertextHeaders.NO_MAX_ENCRYPTED_DATA_KEYS); decryptionHandler.setMaxInputLength(10); assertEquals(decryptionHandler.getMaxInputLength(), 10); decryptionHandler.setMaxInputLength(100); assertEquals(decryptionHandler.getMaxInputLength(), 10); } }
762
0
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk/internal/TrailingSignatureAlgorithmTest.java
/* * Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except * in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.amazonaws.encryptionsdk.internal; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import com.amazonaws.encryptionsdk.CryptoAlgorithm; import com.amazonaws.encryptionsdk.TestUtils; import java.math.BigInteger; import java.security.AlgorithmParameters; import java.security.KeyFactory; import java.security.PublicKey; import java.security.interfaces.ECPublicKey; import java.security.spec.ECGenParameterSpec; import java.security.spec.ECParameterSpec; import java.security.spec.ECPoint; import java.security.spec.ECPublicKeySpec; import org.junit.Test; public class TrailingSignatureAlgorithmTest { private static final int[] secp256r1PublicFixture_X = new int[] { 163, 132, 202, 41, 50, 135, 193, 159, 67, 19, 186, 212, 0, 129, 16, 182, 186, 176, 124, 94, 242, 139, 48, 143, 158, 96, 51, 133, 188, 144, 137, 148 }; private static final int[] secp256r1PublicFixture_Y = new int[] { 71, 234, 253, 112, 131, 106, 243, 169, 143, 58, 39, 222, 47, 211, 230, 90, 139, 163, 54, 249, 187, 115, 209, 203, 239, 98, 26, 47, 101, 213, 140, 212 }; private static final int[] secp2561CompressedFixture = new int[] { 2, 163, 132, 202, 41, 50, 135, 193, 159, 67, 19, 186, 212, 0, 129, 16, 182, 186, 176, 124, 94, 242, 139, 48, 143, 158, 96, 51, 133, 188, 144, 137, 148 }; private static final int[] secp384r1PublicFixture_X = new int[] { 207, 62, 215, 143, 116, 128, 174, 103, 1, 81, 127, 212, 163, 19, 165, 220, 74, 144, 26, 59, 87, 0, 214, 47, 66, 73, 152, 227, 196, 81, 14, 28, 58, 221, 178, 63, 150, 119, 62, 195, 99, 63, 60, 42, 223, 207, 28, 65 }; private static final int[] secp384r1PublicFixture_Y = new int[] { 180, 143, 190, 5, 150, 247, 225, 240, 153, 150, 119, 109, 210, 243, 151, 206, 217, 120, 2, 171, 75, 180, 31, 4, 91, 78, 206, 217, 241, 119, 55, 230, 216, 23, 237, 101, 21, 89, 132, 84, 100, 3, 255, 90, 197, 237, 139, 209 }; private static final int[] secp384r1CompressedFixture = new int[] { 3, 207, 62, 215, 143, 116, 128, 174, 103, 1, 81, 127, 212, 163, 19, 165, 220, 74, 144, 26, 59, 87, 0, 214, 47, 66, 73, 152, 227, 196, 81, 14, 28, 58, 221, 178, 63, 150, 119, 62, 195, 99, 63, 60, 42, 223, 207, 28, 65 }; @Test public void serializationEquality() throws Exception { CryptoAlgorithm algorithm = CryptoAlgorithm.ALG_AES_128_GCM_IV12_TAG16_HKDF_SHA256_ECDSA_P256; PublicKey publicKey = TrailingSignatureAlgorithm.forCryptoAlgorithm(algorithm).generateKey().getPublic(); String serializedPublicKey = TrailingSignatureAlgorithm.forCryptoAlgorithm(algorithm).serializePublicKey(publicKey); PublicKey deserializedPublicKey = TrailingSignatureAlgorithm.forCryptoAlgorithm(algorithm) .deserializePublicKey(serializedPublicKey); assertEquals(publicKey, deserializedPublicKey); algorithm = CryptoAlgorithm.ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA384_ECDSA_P384; publicKey = TrailingSignatureAlgorithm.forCryptoAlgorithm(algorithm).generateKey().getPublic(); serializedPublicKey = TrailingSignatureAlgorithm.forCryptoAlgorithm(algorithm).serializePublicKey(publicKey); deserializedPublicKey = TrailingSignatureAlgorithm.forCryptoAlgorithm(algorithm) .deserializePublicKey(serializedPublicKey); assertEquals(publicKey, deserializedPublicKey); } @Test public void deserializeSecp384() { testDeserialization( CryptoAlgorithm.ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA384_ECDSA_P384, secp384r1CompressedFixture, secp384r1PublicFixture_X, secp384r1PublicFixture_Y); } @Test public void serializeSecp384() throws Exception { testSerialization( CryptoAlgorithm.ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA384_ECDSA_P384, "secp384r1", secp384r1PublicFixture_X, secp384r1PublicFixture_Y, secp384r1CompressedFixture); } @Test public void deserializeSecp256() { testDeserialization( CryptoAlgorithm.ALG_AES_128_GCM_IV12_TAG16_HKDF_SHA256_ECDSA_P256, secp2561CompressedFixture, secp256r1PublicFixture_X, secp256r1PublicFixture_Y); } @Test public void serializeSecp256() throws Exception { testSerialization( CryptoAlgorithm.ALG_AES_128_GCM_IV12_TAG16_HKDF_SHA256_ECDSA_P256, "secp256r1", secp256r1PublicFixture_X, secp256r1PublicFixture_Y, secp2561CompressedFixture); } @Test(expected = IllegalArgumentException.class) public void testBadPoint() { byte[] bytes = TestUtils.unsignedBytesToSignedBytes(secp384r1CompressedFixture); bytes[20]++; String publicKey = Utils.encodeBase64String(bytes); TrailingSignatureAlgorithm.forCryptoAlgorithm( CryptoAlgorithm.ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA384_ECDSA_P384) .deserializePublicKey(publicKey); } private void testSerialization( CryptoAlgorithm algorithm, String curveName, int[] x, int[] y, int[] expected) throws Exception { byte[] xBytes = TestUtils.unsignedBytesToSignedBytes(x); byte[] yBytes = TestUtils.unsignedBytesToSignedBytes(y); final AlgorithmParameters parameters = AlgorithmParameters.getInstance("EC"); parameters.init(new ECGenParameterSpec(curveName)); ECParameterSpec ecParameterSpec = parameters.getParameterSpec(ECParameterSpec.class); PublicKey publicKey = KeyFactory.getInstance("EC") .generatePublic( new ECPublicKeySpec( new ECPoint(new BigInteger(1, xBytes), new BigInteger(1, yBytes)), ecParameterSpec)); int[] result = TestUtils.signedBytesToUnsignedBytes( Utils.decodeBase64String( TrailingSignatureAlgorithm.forCryptoAlgorithm(algorithm) .serializePublicKey(publicKey))); assertArrayEquals(expected, result); } private void testDeserialization( CryptoAlgorithm algorithm, int[] compressedKey, int[] expectedX, int[] expectedY) { byte[] bytes = TestUtils.unsignedBytesToSignedBytes(compressedKey); String publicKey = Utils.encodeBase64String(bytes); PublicKey publicKeyDeserialized = TrailingSignatureAlgorithm.forCryptoAlgorithm(algorithm).deserializePublicKey(publicKey); ECPublicKey desKey = (ECPublicKey) publicKeyDeserialized; BigInteger x = desKey.getW().getAffineX(); BigInteger y = desKey.getW().getAffineY(); BigInteger expectedXBigInteger = new BigInteger(1, TestUtils.unsignedBytesToSignedBytes(expectedX)); BigInteger expectedYBigInteger = new BigInteger(1, TestUtils.unsignedBytesToSignedBytes(expectedY)); assertEquals(expectedXBigInteger, x); assertEquals(expectedYBigInteger, y); } }
763
0
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk/model/CiphertextHeadersTest.java
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package com.amazonaws.encryptionsdk.model; import static com.amazonaws.encryptionsdk.TestUtils.assertThrows; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import com.amazonaws.encryptionsdk.AwsCrypto; import com.amazonaws.encryptionsdk.CryptoAlgorithm; import com.amazonaws.encryptionsdk.exception.AwsCryptoException; import com.amazonaws.encryptionsdk.exception.BadCiphertextException; import com.amazonaws.encryptionsdk.internal.Constants; import com.amazonaws.encryptionsdk.internal.EncryptionContextSerializer; import com.amazonaws.encryptionsdk.internal.RandomBytesGenerator; import java.nio.ByteBuffer; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import org.junit.Test; public class CiphertextHeadersTest { final CryptoAlgorithm cryptoAlgo_ = CryptoAlgorithm.ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA384_ECDSA_P384; final String keyProviderId_ = "None"; final byte[] keyProviderInfo_ = "TestKeyID".getBytes(); final byte version_ = cryptoAlgo_.getMessageFormatVersion(); final byte invalidVersion_ = 0x00; final CiphertextType type_ = CiphertextType.CUSTOMER_AUTHENTICATED_ENCRYPTED_DATA; final int nonceLen_ = cryptoAlgo_.getNonceLen(); final int tagLenBytes_ = cryptoAlgo_.getTagLen(); final ContentType contentType_ = ContentType.FRAME; final int frameSize_ = AwsCrypto.getDefaultFrameSize(); // A set of crypto algs that are representative of the different ciphertext header formats final List<CryptoAlgorithm> testAlgs = Arrays.asList( CryptoAlgorithm.ALG_AES_256_GCM_HKDF_SHA512_COMMIT_KEY, CryptoAlgorithm.ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA256); byte[] encryptedKey_ = RandomBytesGenerator.generate(cryptoAlgo_.getKeyLength()); final KeyBlob keyBlob_ = new KeyBlob(keyProviderId_, keyProviderInfo_, encryptedKey_); byte[] headerNonce_ = RandomBytesGenerator.generate(nonceLen_); byte[] headerTag_ = RandomBytesGenerator.generate(tagLenBytes_); @Test public void serializeDeserialize() { int maxEncryptedDataKeys = 42; Map<String, String> encryptionContext = new HashMap<String, String>(1); encryptionContext.put("ENC", "CiphertextHeader Test"); for (CryptoAlgorithm alg : testAlgs) { final CiphertextHeaders ciphertextHeaders = createCiphertextHeaders(encryptionContext, alg); final byte[] headerBytes = ciphertextHeaders.toByteArray(); final CiphertextHeaders reconstructedHeaders = new CiphertextHeaders(); reconstructedHeaders.deserialize(headerBytes, 0, maxEncryptedDataKeys); final byte[] reconstructedHeaderBytes = reconstructedHeaders.toByteArray(); assertEquals(reconstructedHeaders.getMaxEncryptedDataKeys(), maxEncryptedDataKeys); assertArrayEquals(headerBytes, reconstructedHeaderBytes); } } @Test public void serializeDeserializeDefaultMaxEncryptedDataKeys() { Map<String, String> encryptionContext = new HashMap<String, String>(1); encryptionContext.put("ENC", "CiphertextHeader Test"); for (CryptoAlgorithm alg : testAlgs) { final CiphertextHeaders ciphertextHeaders = createCiphertextHeaders(encryptionContext, alg); final byte[] headerBytes = ciphertextHeaders.toByteArray(); final CiphertextHeaders reconstructedHeaders = new CiphertextHeaders(); reconstructedHeaders.deserialize(headerBytes, 0); final byte[] reconstructedHeaderBytes = reconstructedHeaders.toByteArray(); assertEquals( reconstructedHeaders.getMaxEncryptedDataKeys(), CiphertextHeaders.NO_MAX_ENCRYPTED_DATA_KEYS); assertArrayEquals(headerBytes, reconstructedHeaderBytes); } } @Test public void serializeDeserializeStreaming() { Map<String, String> encryptionContext = new HashMap<String, String>(1); encryptionContext.put("ENC", "CiphertextHeader Streaming Test"); for (CryptoAlgorithm alg : testAlgs) { final CiphertextHeaders ciphertextHeaders = createCiphertextHeaders(encryptionContext, alg); final byte[] headerBytes = ciphertextHeaders.toByteArray(); final CiphertextHeaders reconstructedHeaders = new CiphertextHeaders(); int totalParsedBytes = 0; int bytesToParseLen = 1; int bytesParsed; while (reconstructedHeaders.isComplete() == false) { final byte[] bytesToParse = new byte[bytesToParseLen]; System.arraycopy(headerBytes, totalParsedBytes, bytesToParse, 0, bytesToParse.length); bytesParsed = reconstructedHeaders.deserialize( bytesToParse, 0, CiphertextHeaders.NO_MAX_ENCRYPTED_DATA_KEYS); if (bytesParsed == 0) { bytesToParseLen++; } else { totalParsedBytes += bytesParsed; bytesToParseLen = 1; } } final byte[] reconstructedHeaderBytes = reconstructedHeaders.toByteArray(); assertArrayEquals(headerBytes, reconstructedHeaderBytes); } } @Test public void deserializeNull() { final CiphertextHeaders ciphertextHeaders = new CiphertextHeaders(); final int deserializedBytes = ciphertextHeaders.deserialize(null, 0, CiphertextHeaders.NO_MAX_ENCRYPTED_DATA_KEYS); assertEquals(0, deserializedBytes); } @Test public void overlyLargeEncryptionContext() { final int size = Constants.UNSIGNED_SHORT_MAX_VAL + 1; final byte[] encContextBytes = RandomBytesGenerator.generate(size); for (CryptoAlgorithm alg : testAlgs) { assertThrows(AwsCryptoException.class, () -> createCiphertextHeaders(encContextBytes, alg)); } } @Test public void serializeWithNullHeaderNonce() { for (CryptoAlgorithm alg : testAlgs) { final CiphertextHeaders ciphertextHeaders = new CiphertextHeaders( type_, alg, new byte[0], Collections.singletonList(keyBlob_), contentType_, frameSize_); ciphertextHeaders.setHeaderTag(headerTag_); assertThrows(AwsCryptoException.class, () -> ciphertextHeaders.toByteArray()); } } @Test public void serializeWithNullHeaderTag() { for (CryptoAlgorithm alg : testAlgs) { final CiphertextHeaders ciphertextHeaders = new CiphertextHeaders( type_, alg, new byte[0], Collections.singletonList(keyBlob_), contentType_, frameSize_); ciphertextHeaders.setHeaderNonce(headerNonce_); assertThrows(AwsCryptoException.class, () -> ciphertextHeaders.toByteArray()); } } @Test public void serializeWithNullSuiteData() { // Only applicable for V2 algorithms CryptoAlgorithm alg = CryptoAlgorithm.ALG_AES_256_GCM_HKDF_SHA512_COMMIT_KEY; final CiphertextHeaders ciphertextHeaders = new CiphertextHeaders( type_, alg, new byte[0], Collections.singletonList(keyBlob_), contentType_, frameSize_); ciphertextHeaders.setHeaderTag(headerTag_); ciphertextHeaders.setHeaderNonce(headerNonce_); assertThrows(AwsCryptoException.class, () -> ciphertextHeaders.toByteArray()); } /* * @Test * public void byteFormatCheck() { * testPlaintextKey_ = ByteFormatCheckValues.getPlaintextKey(); * testKey_ = new SecretKeySpec(testPlaintextKey_, * cryptoAlgo_.getKeySpec()); * encryptedKey_ = ByteFormatCheckValues.getEncryptedKey(); * dataKey_ = new AWSKMSDataKey(testKey_, encryptedKey_); * headerNonce_ = ByteFormatCheckValues.getNonce(); * headerTag_ = ByteFormatCheckValues.getTag(); * * Map<String, String> encryptionContext = new HashMap<String, String>(1); * encryptionContext.put("ENC", "CiphertextHeader format check test"); * * final CiphertextHeaders ciphertextHeaders = * createCiphertextHeaders(encryptionContext); * //NOTE: this test will fail because of the line below. * //That is, the message id is randomly generated in the ciphertext * headers. * messageId_ = ciphertextHeaders.getMessageId(); * final byte[] ciphertextHeaderHash = * TestIOUtils.getSha256Hash(ciphertextHeaders.toByteArray()); * * assertArrayEquals(ByteFormatCheckValues.getCiphertextHeaderHash(), * ciphertextHeaderHash); * } */ private CiphertextHeaders createCiphertextHeaders( final byte[] encryptionContextBytes, CryptoAlgorithm cryptoAlg) { final CiphertextHeaders ciphertextHeaders = new CiphertextHeaders( type_, cryptoAlg, encryptionContextBytes, Collections.singletonList(keyBlob_), contentType_, frameSize_); ciphertextHeaders.setHeaderNonce(headerNonce_); ciphertextHeaders.setHeaderTag(headerTag_); if (cryptoAlg.getMessageFormatVersion() == 2) { ciphertextHeaders.setSuiteData(new byte[cryptoAlg.getSuiteDataLength()]); } return ciphertextHeaders; } private CiphertextHeaders createCiphertextHeaders( final Map<String, String> encryptionContext, CryptoAlgorithm cryptoAlg) { byte[] encryptionContextBytes = null; if (encryptionContext != null) { encryptionContextBytes = EncryptionContextSerializer.serialize(encryptionContext); } return createCiphertextHeaders(encryptionContextBytes, cryptoAlg); } @SuppressWarnings("deprecation") @Test public void legacyConstructCiphertextHeaders() { final Map<String, String> encryptionContext = new HashMap<String, String>(1); encryptionContext.put("ENC", "CiphertextHeader Streaming Test"); final byte[] encryptionContextBytes = EncryptionContextSerializer.serialize(encryptionContext); final CiphertextHeaders ciphertextHeaders = new CiphertextHeaders( version_, type_, cryptoAlgo_, encryptionContextBytes, Collections.singletonList(keyBlob_), contentType_, frameSize_); ciphertextHeaders.setHeaderNonce(headerNonce_); ciphertextHeaders.setHeaderTag(headerTag_); assertNotNull(ciphertextHeaders); } @SuppressWarnings("deprecation") @Test(expected = IllegalArgumentException.class) public void legacyConstructCiphertextHeadersMismatchedVersion() { final Map<String, String> encryptionContext = new HashMap<String, String>(1); encryptionContext.put("ENC", "CiphertextHeader Streaming Test"); final byte[] encryptionContextBytes = EncryptionContextSerializer.serialize(encryptionContext); final CiphertextHeaders ciphertextHeaders = new CiphertextHeaders( invalidVersion_, type_, cryptoAlgo_, encryptionContextBytes, Collections.singletonList(keyBlob_), contentType_, frameSize_); } @Test public void checkEncContextLen() { final Map<String, String> encryptionContext = new HashMap<String, String>(1); encryptionContext.put("ENC", "CiphertextHeader Streaming Test"); final byte[] encryptionContextBytes = EncryptionContextSerializer.serialize(encryptionContext); final int encryptionContextLen = encryptionContextBytes.length; for (CryptoAlgorithm alg : testAlgs) { final CiphertextHeaders ciphertextHeaders = createCiphertextHeaders(encryptionContext, alg); final byte[] headerBytes = ciphertextHeaders.toByteArray(); final CiphertextHeaders reconstructedHeaders = new CiphertextHeaders(); reconstructedHeaders.deserialize( headerBytes, 0, CiphertextHeaders.NO_MAX_ENCRYPTED_DATA_KEYS); assertEquals(encryptionContextLen, reconstructedHeaders.getEncryptionContextLen()); } } @Test public void checkKeyBlobCount() { final Map<String, String> encryptionContext = new HashMap<String, String>(1); encryptionContext.put("ENC", "CiphertextHeader Streaming Test"); for (CryptoAlgorithm alg : testAlgs) { final CiphertextHeaders ciphertextHeaders = createCiphertextHeaders(encryptionContext, alg); final byte[] headerBytes = ciphertextHeaders.toByteArray(); final CiphertextHeaders reconstructedHeaders = new CiphertextHeaders(); reconstructedHeaders.deserialize( headerBytes, 0, CiphertextHeaders.NO_MAX_ENCRYPTED_DATA_KEYS); assertEquals(1, reconstructedHeaders.getEncryptedKeyBlobCount()); } } @Test public void checkNullMessageId() { final CiphertextHeaders ciphertextHeaders = new CiphertextHeaders(); assertEquals(null, ciphertextHeaders.getMessageId()); } @Test public void checkNullHeaderNonce() { final CiphertextHeaders ciphertextHeaders = new CiphertextHeaders(); assertEquals(null, ciphertextHeaders.getHeaderNonce()); } @Test public void checkNullHeaderTag() { final CiphertextHeaders ciphertextHeaders = new CiphertextHeaders(); assertEquals(null, ciphertextHeaders.getHeaderTag()); } private void readVersion(final ByteBuffer headerBuff) { headerBuff.get(); } private void readType(final ByteBuffer headerBuff) { readVersion(headerBuff); headerBuff.get(); } private void readToAlgoId(final ByteBuffer headerBuff, final CryptoAlgorithm cryptoAlg) { // Use the message format version to determine where the algorithm Id is in the // header and how to get to it. if (cryptoAlg.getMessageFormatVersion() == 1) { readType(headerBuff); } else { readVersion(headerBuff); } } private void readAlgoId(final ByteBuffer headerBuff, final CryptoAlgorithm cryptoAlg) { readToAlgoId(headerBuff, cryptoAlg); headerBuff.getShort(); } private void readEncContext(final ByteBuffer headerBuff, final CryptoAlgorithm cryptoAlg) { readAlgoId(headerBuff, cryptoAlg); // pull out messageId to get to enc context len. final byte[] msgId = new byte[cryptoAlg.getMessageIdLength()]; headerBuff.get(msgId); // pull out enc context to get to key count. final int encContextLen = headerBuff.getShort(); final byte[] encContext = new byte[encContextLen]; headerBuff.get(encContext); } private void readKeyBlob(final ByteBuffer headerBuff, final CryptoAlgorithm cryptoAlg) { readEncContext(headerBuff, cryptoAlg); headerBuff.getShort(); // get key count final short keyProviderIdLen = headerBuff.getShort(); final byte[] keyProviderId = new byte[keyProviderIdLen]; headerBuff.get(keyProviderId); final short keyProviderInfoLen = headerBuff.getShort(); final byte[] keyProviderInfo = new byte[keyProviderInfoLen]; headerBuff.get(keyProviderInfo); final short keyLen = headerBuff.getShort(); final byte[] key = new byte[keyLen]; headerBuff.get(key); } private void readToContentType(final ByteBuffer headerBuff, final CryptoAlgorithm cryptoAlg) { readKeyBlob(headerBuff, cryptoAlg); } private void readContentType(final ByteBuffer headerBuff, final CryptoAlgorithm cryptoAlg) { readToContentType(headerBuff, cryptoAlg); headerBuff.get(); } private void readToReservedField(final ByteBuffer headerBuff, final CryptoAlgorithm cryptoAlg) { readContentType(headerBuff, cryptoAlg); } private void readReservedField(final ByteBuffer headerBuff, final CryptoAlgorithm cryptoAlg) { readToReservedField(headerBuff, cryptoAlg); headerBuff.getInt(); } private void readToNonceLen(final ByteBuffer headerBuff, final CryptoAlgorithm cryptoAlg) { readReservedField(headerBuff, cryptoAlg); } private void readNonceLen(final ByteBuffer headerBuff, final CryptoAlgorithm cryptoAlg) { readToNonceLen(headerBuff, cryptoAlg); headerBuff.get(); } private void readToFrameLen(final ByteBuffer headerBuff, final CryptoAlgorithm cryptoAlg) { // Use the message format version to determine where the frame length is in the // header and how to get to it. if (cryptoAlg.getMessageFormatVersion() == 1) { readNonceLen(headerBuff, cryptoAlg); } else { readContentType(headerBuff, cryptoAlg); } } @Test public void invalidVersion() { final Map<String, String> encryptionContext = new HashMap<String, String>(1); encryptionContext.put("ENC", "CiphertextHeader Streaming Test"); for (CryptoAlgorithm alg : testAlgs) { final CiphertextHeaders ciphertextHeaders = createCiphertextHeaders(encryptionContext, alg); final byte[] headerBytes = ciphertextHeaders.toByteArray(); final ByteBuffer headerBuff = ByteBuffer.wrap(headerBytes); // set version to invalid type of 0. headerBuff.put((byte) 0); final CiphertextHeaders reconstructedHeaders = new CiphertextHeaders(); assertThrows( BadCiphertextException.class, "Invalid version", () -> reconstructedHeaders.deserialize( headerBuff.array(), 0, CiphertextHeaders.NO_MAX_ENCRYPTED_DATA_KEYS)); } } @Test public void invalidType() { // Only applicable for V1 algorithms final Map<String, String> encryptionContext = new HashMap<String, String>(1); encryptionContext.put("ENC", "CiphertextHeader Streaming Test"); final CryptoAlgorithm cryptoAlgorithm = CryptoAlgorithm.ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA256; final CiphertextHeaders ciphertextHeaders = createCiphertextHeaders(encryptionContext, cryptoAlgorithm); final byte[] headerBytes = ciphertextHeaders.toByteArray(); final ByteBuffer headerBuff = ByteBuffer.wrap(headerBytes); readVersion(headerBuff); // set type to invalid value of 0. headerBuff.put((byte) 0); final CiphertextHeaders reconstructedHeaders = new CiphertextHeaders(); assertThrows( BadCiphertextException.class, "Invalid ciphertext type", () -> reconstructedHeaders.deserialize( headerBuff.array(), 0, CiphertextHeaders.NO_MAX_ENCRYPTED_DATA_KEYS)); } @Test public void invalidAlgoId() { final Map<String, String> encryptionContext = new HashMap<String, String>(1); encryptionContext.put("ENC", "CiphertextHeader Streaming Test"); for (CryptoAlgorithm alg : testAlgs) { final CiphertextHeaders ciphertextHeaders = createCiphertextHeaders(encryptionContext, alg); final byte[] headerBytes = ciphertextHeaders.toByteArray(); final ByteBuffer headerBuff = ByteBuffer.wrap(headerBytes); readToAlgoId(headerBuff, alg); // set algoId to invalid value of 0. headerBuff.putShort((short) 0); final CiphertextHeaders reconstructedHeaders = new CiphertextHeaders(); assertThrows( BadCiphertextException.class, "Invalid algorithm identifier in ciphertext", () -> reconstructedHeaders.deserialize( headerBuff.array(), 0, CiphertextHeaders.NO_MAX_ENCRYPTED_DATA_KEYS)); } } @Test public void invalidContentType() { final Map<String, String> encryptionContext = new HashMap<String, String>(1); encryptionContext.put("ENC", "CiphertextHeader Streaming Test"); for (CryptoAlgorithm alg : testAlgs) { final CiphertextHeaders ciphertextHeaders = createCiphertextHeaders(encryptionContext, alg); final byte[] headerBytes = ciphertextHeaders.toByteArray(); final ByteBuffer headerBuff = ByteBuffer.wrap(headerBytes); readToContentType(headerBuff, alg); // set content type to an invalid value headerBuff.put((byte) 10); final CiphertextHeaders reconstructedHeaders = new CiphertextHeaders(); assertThrows( BadCiphertextException.class, "Invalid content type in ciphertext.", () -> reconstructedHeaders.deserialize( headerBuff.array(), 0, CiphertextHeaders.NO_MAX_ENCRYPTED_DATA_KEYS)); } } @Test public void invalidReservedFieldLen() { // Only applicable for V1 algorithms final Map<String, String> encryptionContext = new HashMap<String, String>(1); encryptionContext.put("ENC", "CiphertextHeader Streaming Test"); final CryptoAlgorithm cryptoAlgorithm = CryptoAlgorithm.ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA256; final CiphertextHeaders ciphertextHeaders = createCiphertextHeaders(encryptionContext, cryptoAlgorithm); final byte[] headerBytes = ciphertextHeaders.toByteArray(); final ByteBuffer headerBuff = ByteBuffer.wrap(headerBytes); readToReservedField(headerBuff, cryptoAlgorithm); // set reserved field to an invalid value headerBuff.putInt(-1); final CiphertextHeaders reconstructedHeaders = new CiphertextHeaders(); assertThrows( BadCiphertextException.class, "Invalid value for reserved field in ciphertext", () -> reconstructedHeaders.deserialize( headerBuff.array(), 0, CiphertextHeaders.NO_MAX_ENCRYPTED_DATA_KEYS)); } @Test public void invalidNonceLen() { // Only applicable for V1 algorithms final Map<String, String> encryptionContext = new HashMap<String, String>(1); encryptionContext.put("ENC", "CiphertextHeader Streaming Test"); final CryptoAlgorithm cryptoAlgorithm = CryptoAlgorithm.ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA256; final CiphertextHeaders ciphertextHeaders = createCiphertextHeaders(encryptionContext, cryptoAlgorithm); final byte[] headerBytes = ciphertextHeaders.toByteArray(); final ByteBuffer headerBuff = ByteBuffer.wrap(headerBytes); readToNonceLen(headerBuff, cryptoAlgorithm); // set nonce len to an invalid value headerBuff.put((byte) -1); final CiphertextHeaders reconstructedHeaders = new CiphertextHeaders(); assertThrows( BadCiphertextException.class, "Invalid nonce length in ciphertext", () -> reconstructedHeaders.deserialize( headerBuff.array(), 0, CiphertextHeaders.NO_MAX_ENCRYPTED_DATA_KEYS)); } @Test public void invalidFrameLength() { final Map<String, String> encryptionContext = new HashMap<String, String>(1); encryptionContext.put("ENC", "CiphertextHeader Streaming Test"); for (CryptoAlgorithm alg : testAlgs) { final CiphertextHeaders ciphertextHeaders = createCiphertextHeaders(encryptionContext, alg); final byte[] headerBytes = ciphertextHeaders.toByteArray(); final ByteBuffer headerBuff = ByteBuffer.wrap(headerBytes); readToFrameLen(headerBuff, alg); // set frame len to an invalid value headerBuff.putInt(-1); final CiphertextHeaders reconstructedHeaders = new CiphertextHeaders(); assertThrows( BadCiphertextException.class, "Invalid frame length in ciphertext", () -> reconstructedHeaders.deserialize( headerBuff.array(), 0, CiphertextHeaders.NO_MAX_ENCRYPTED_DATA_KEYS)); } } }
764
0
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk/model/EncryptionMaterialsRequestTest.java
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package com.amazonaws.encryptionsdk.model; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import com.amazonaws.encryptionsdk.CommitmentPolicy; import org.junit.Test; public class EncryptionMaterialsRequestTest { @Test(expected = IllegalArgumentException.class) public void testConstructWithNullCommitmentPolicy() { EncryptionMaterialsRequest.newBuilder().setCommitmentPolicy(null).build(); } @Test(expected = IllegalArgumentException.class) public void testConstructWithoutCommitmentPolicy() { EncryptionMaterialsRequest.newBuilder().build(); } @Test public void testConstructWithCommitmentPolicy() { EncryptionMaterialsRequest req = EncryptionMaterialsRequest.newBuilder() .setCommitmentPolicy(CommitmentPolicy.ForbidEncryptAllowDecrypt) .build(); assertNotNull(req); assertEquals(CommitmentPolicy.ForbidEncryptAllowDecrypt, req.getCommitmentPolicy()); } }
765
0
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk/model/DecryptionMaterialsRequestTest.java
/* * Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except * in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.amazonaws.encryptionsdk.model; import static org.junit.Assert.assertEquals; import com.amazonaws.encryptionsdk.CryptoAlgorithm; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.junit.Test; public class DecryptionMaterialsRequestTest { @Test public void build() { CryptoAlgorithm alg = CryptoAlgorithm.ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA256; Map<String, String> encryptionContext = new HashMap<String, String>(1); encryptionContext.put("DMR", "DecryptionMaterialsRequest Test"); List<KeyBlob> kbs = new ArrayList<KeyBlob>(); DecryptionMaterialsRequest request0 = DecryptionMaterialsRequest.newBuilder() .setAlgorithm(alg) .setEncryptionContext(encryptionContext) .setEncryptedDataKeys(kbs) .build(); DecryptionMaterialsRequest request1 = request0.toBuilder().build(); assertEquals(request0.getAlgorithm(), request1.getAlgorithm()); assertEquals(request0.getEncryptionContext().size(), request1.getEncryptionContext().size()); assertEquals(request0.getEncryptedDataKeys().size(), request1.getEncryptedDataKeys().size()); } }
766
0
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk/model/KeyBlobTest.java
/* * Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except * in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.amazonaws.encryptionsdk.model; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import com.amazonaws.encryptionsdk.CryptoAlgorithm; import com.amazonaws.encryptionsdk.DataKey; import com.amazonaws.encryptionsdk.exception.AwsCryptoException; import com.amazonaws.encryptionsdk.internal.Constants; import com.amazonaws.encryptionsdk.internal.RandomBytesGenerator; import com.amazonaws.encryptionsdk.internal.StaticMasterKey; import java.nio.charset.StandardCharsets; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import org.junit.Before; import org.junit.Test; public class KeyBlobTest { private static CryptoAlgorithm ALGORITHM = CryptoAlgorithm.ALG_AES_128_GCM_IV12_TAG16_NO_KDF; final String providerId_ = "Test Key"; final String providerInfo_ = "Test Info"; private StaticMasterKey masterKeyProvider_; @Before public void init() { masterKeyProvider_ = new StaticMasterKey("testmaterial"); } private byte[] createKeyBlobBytes() { final Map<String, String> encryptionContext = new HashMap<String, String>(1); encryptionContext.put("ENC", "Test Encryption Context"); final DataKey<StaticMasterKey> mockDataKey_ = masterKeyProvider_.generateDataKey(ALGORITHM, encryptionContext); final KeyBlob keyBlob = new KeyBlob( providerId_, providerInfo_.getBytes(StandardCharsets.UTF_8), mockDataKey_.getEncryptedDataKey()); return keyBlob.toByteArray(); } private KeyBlob deserialize(final byte[] keyBlobBytes) { final KeyBlob reconstructedKeyBlob = new KeyBlob(); reconstructedKeyBlob.deserialize(keyBlobBytes, 0); return reconstructedKeyBlob; } @Test public void serializeDeserialize() { final byte[] keyBlobBytes = createKeyBlobBytes(); final KeyBlob reconstructedKeyBlob = deserialize(keyBlobBytes); final byte[] reconstructedKeyBlobBytes = reconstructedKeyBlob.toByteArray(); assertArrayEquals(reconstructedKeyBlobBytes, keyBlobBytes); } @Test(expected = AwsCryptoException.class) public void overlyLargeKeyProviderIdLen() { final Map<String, String> encryptionContext = new HashMap<String, String>(1); encryptionContext.put("ENC", "Test Encryption Context"); final DataKey<StaticMasterKey> mockDataKey = masterKeyProvider_.generateDataKey(ALGORITHM, encryptionContext); final int providerId_Len = Constants.UNSIGNED_SHORT_MAX_VAL + 1; final byte[] providerId_Bytes = RandomBytesGenerator.generate(providerId_Len); final String providerId_ = new String(providerId_Bytes, StandardCharsets.UTF_8); final String providerInfo_ = "Test Info"; new KeyBlob( providerId_, providerInfo_.getBytes(StandardCharsets.UTF_8), mockDataKey.getEncryptedDataKey()); } @Test(expected = AwsCryptoException.class) public void overlyLargeKeyProviderInfoLen() { final Map<String, String> encryptionContext = new HashMap<String, String>(1); encryptionContext.put("ENC", "Test Encryption Context"); final DataKey<StaticMasterKey> mockDataKey = masterKeyProvider_.generateDataKey(ALGORITHM, encryptionContext); final int providerInfo_Len = Constants.UNSIGNED_SHORT_MAX_VAL + 1; final byte[] providerInfo_ = RandomBytesGenerator.generate(providerInfo_Len); new KeyBlob(providerId_, providerInfo_, mockDataKey.getEncryptedDataKey()); } @Test(expected = AwsCryptoException.class) public void overlyLargeKey() { final int keyLen = Constants.UNSIGNED_SHORT_MAX_VAL + 1; final byte[] encryptedKeyBytes = RandomBytesGenerator.generate(keyLen); new KeyBlob(providerId_, providerInfo_.getBytes(StandardCharsets.UTF_8), encryptedKeyBytes); } @Test public void deserializeNull() { final KeyBlob keyBlob = new KeyBlob(); final int deserializedBytes = keyBlob.deserialize(null, 0); assertEquals(0, deserializedBytes); } @Test public void checkKeyProviderIdLen() { final byte[] keyBlobBytes = createKeyBlobBytes(); final KeyBlob reconstructedKeyBlob = deserialize(keyBlobBytes); assertEquals(providerId_.length(), reconstructedKeyBlob.getKeyProviderIdLen()); } @Test public void checkKeyProviderId() { final byte[] keyBlobBytes = createKeyBlobBytes(); final KeyBlob reconstructedKeyBlob = deserialize(keyBlobBytes); assertArrayEquals( providerId_.getBytes(StandardCharsets.UTF_8), reconstructedKeyBlob.getProviderId().getBytes(StandardCharsets.UTF_8)); } @Test public void checkKeyProviderInfoLen() { final byte[] keyBlobBytes = createKeyBlobBytes(); final KeyBlob reconstructedKeyBlob = deserialize(keyBlobBytes); assertEquals(providerInfo_.length(), reconstructedKeyBlob.getKeyProviderInfoLen()); } @Test public void checkKeyProviderInfo() { final byte[] keyBlobBytes = createKeyBlobBytes(); final KeyBlob reconstructedKeyBlob = deserialize(keyBlobBytes); assertArrayEquals( providerInfo_.getBytes(StandardCharsets.UTF_8), reconstructedKeyBlob.getProviderInformation()); } @Test public void checkKeyLen() { final Map<String, String> encryptionContext = new HashMap<String, String>(1); encryptionContext.put("ENC", "Test Encryption Context"); final DataKey<StaticMasterKey> mockDataKey_ = masterKeyProvider_.generateDataKey(ALGORITHM, encryptionContext); final KeyBlob keyBlob = new KeyBlob( providerId_, providerInfo_.getBytes(StandardCharsets.UTF_8), mockDataKey_.getEncryptedDataKey()); final byte[] keyBlobBytes = keyBlob.toByteArray(); final KeyBlob reconstructedKeyBlob = deserialize(keyBlobBytes); assertEquals( mockDataKey_.getEncryptedDataKey().length, reconstructedKeyBlob.getEncryptedDataKeyLen()); } private KeyBlob generateRandomKeyBlob(int idLen, int infoLen, int keyLen) { final byte[] idBytes = new byte[idLen]; Arrays.fill(idBytes, (byte) 'A'); final byte[] infoBytes = RandomBytesGenerator.generate(infoLen); final byte[] keyBytes = RandomBytesGenerator.generate(keyLen); return new KeyBlob(new String(idBytes, StandardCharsets.UTF_8), infoBytes, keyBytes); } private void assertKeyBlobsEqual(KeyBlob b1, KeyBlob b2) { assertArrayEquals( b1.getProviderId().getBytes(StandardCharsets.UTF_8), b2.getProviderId().getBytes(StandardCharsets.UTF_8)); assertArrayEquals(b1.getProviderInformation(), b2.getProviderInformation()); assertArrayEquals(b1.getEncryptedDataKey(), b2.getEncryptedDataKey()); } @Test public void checkKeyProviderIdLenUnsigned() { // provider id length is too large for a signed short but fits in unsigned final KeyBlob blob = generateRandomKeyBlob(Constants.UNSIGNED_SHORT_MAX_VAL, Short.MAX_VALUE, Short.MAX_VALUE); final byte[] arr = blob.toByteArray(); assertKeyBlobsEqual(deserialize(arr), blob); } @Test public void checkKeyProviderInfoLenUnsigned() { // provider info length is too large for a signed short but fits in unsigned final KeyBlob blob = generateRandomKeyBlob(Short.MAX_VALUE, Constants.UNSIGNED_SHORT_MAX_VAL, Short.MAX_VALUE); final byte[] arr = blob.toByteArray(); assertKeyBlobsEqual(deserialize(arr), blob); } @Test public void checkKeyLenUnsigned() { // key length is too large for a signed short but fits in unsigned final KeyBlob blob = generateRandomKeyBlob(Short.MAX_VALUE, Short.MAX_VALUE, Constants.UNSIGNED_SHORT_MAX_VAL); final byte[] arr = blob.toByteArray(); assertKeyBlobsEqual(deserialize(arr), blob); } }
767
0
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk/model/CipherFrameHeadersTest.java
/* * Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except * in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.amazonaws.encryptionsdk.model; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import com.amazonaws.encryptionsdk.TestUtils; import com.amazonaws.encryptionsdk.exception.AwsCryptoException; import com.amazonaws.encryptionsdk.exception.BadCiphertextException; import com.amazonaws.encryptionsdk.internal.Constants; import com.amazonaws.encryptionsdk.internal.RandomBytesGenerator; import com.amazonaws.encryptionsdk.internal.TestIOUtils; import java.nio.ByteBuffer; import java.util.Arrays; import org.junit.Test; public class CipherFrameHeadersTest { final int nonceLen_ = TestUtils.DEFAULT_TEST_CRYPTO_ALG.getNonceLen(); final int testSeqNum_ = 1; final int testFrameContentLen_ = 4096; byte[] nonce_ = RandomBytesGenerator.generate(nonceLen_); @Test public void serializeDeserializeTest() { for (boolean includeContentLen : new boolean[] {true, false}) { for (boolean isFinalFrame : new boolean[] {true, false}) { assertTrue(serializeDeserialize(includeContentLen, isFinalFrame)); } } } @Test public void serializeDeserializeStreamingTest() { for (boolean includeContentLen : new boolean[] {true, false}) { for (boolean isFinalFrame : new boolean[] {true, false}) { assertTrue(serializeDeserializeStreaming(includeContentLen, isFinalFrame)); } } } private byte[] createHeaderBytes(final boolean includeContentLen, final boolean isFinalFrame) { final CipherFrameHeaders cipherFrameHeaders = new CipherFrameHeaders(testSeqNum_, nonce_, testFrameContentLen_, isFinalFrame); cipherFrameHeaders.includeFrameSize(includeContentLen); return cipherFrameHeaders.toByteArray(); } private CipherFrameHeaders deserialize(final boolean parseContentLen, final byte[] headerBytes) { final CipherFrameHeaders reconstructedHeaders = new CipherFrameHeaders(); reconstructedHeaders.setNonceLength((short) nonceLen_); reconstructedHeaders.includeFrameSize(parseContentLen); reconstructedHeaders.deserialize(headerBytes, 0); return reconstructedHeaders; } private boolean serializeDeserialize( final boolean includeContentLen, final boolean isFinalFrame) { final byte[] headerBytes = createHeaderBytes(includeContentLen, isFinalFrame); final CipherFrameHeaders reconstructedHeaders = deserialize(includeContentLen, headerBytes); final byte[] reconstructedHeaderBytes = reconstructedHeaders.toByteArray(); return Arrays.equals(headerBytes, reconstructedHeaderBytes) ? true : false; } private boolean serializeDeserializeStreaming( final boolean includeContentLen, final boolean isFinalFrame) { final byte[] headerBytes = createHeaderBytes(includeContentLen, isFinalFrame); final CipherFrameHeaders reconstructedHeaders = new CipherFrameHeaders(); reconstructedHeaders.setNonceLength((short) nonceLen_); reconstructedHeaders.includeFrameSize(includeContentLen); int totalParsedBytes = 0; int bytesToParseLen = 1; int bytesParsed; while (reconstructedHeaders.isComplete() == false) { final byte[] bytesToParse = new byte[bytesToParseLen]; System.arraycopy(headerBytes, totalParsedBytes, bytesToParse, 0, bytesToParse.length); bytesParsed = reconstructedHeaders.deserialize(bytesToParse, 0); if (bytesParsed == 0) { bytesToParseLen++; } else { totalParsedBytes += bytesParsed; bytesToParseLen = 1; } } final byte[] reconstructedHeaderBytes = reconstructedHeaders.toByteArray(); return Arrays.equals(headerBytes, reconstructedHeaderBytes) ? true : false; } @Test public void deserializeNull() { final CipherFrameHeaders cipherFrameHeaders = new CipherFrameHeaders(); final int deserializedBytes = cipherFrameHeaders.deserialize(null, 0); assertEquals(0, deserializedBytes); } @Test public void checkNullNonce() { final CipherFrameHeaders cipherFrameHeaders = new CipherFrameHeaders(); cipherFrameHeaders.setNonceLength((short) nonceLen_); assertEquals(null, cipherFrameHeaders.getNonce()); } @Test public void checkNonce() { final byte[] headerBytes = createHeaderBytes(false, false); final CipherFrameHeaders reconstructedHeaders = deserialize(false, headerBytes); assertArrayEquals(nonce_, reconstructedHeaders.getNonce()); } @Test public void checkSeqNum() { final byte[] headerBytes = createHeaderBytes(false, false); final CipherFrameHeaders reconstructedHeaders = deserialize(false, headerBytes); assertEquals(testSeqNum_, reconstructedHeaders.getSequenceNumber()); } @Test public void checkFrameLen() { final boolean isFinalFrame = false; final boolean includeContentLen = true; final byte[] headerBytes = createHeaderBytes(includeContentLen, isFinalFrame); final CipherFrameHeaders reconstructedHeaders = deserialize(includeContentLen, headerBytes); assertEquals(testFrameContentLen_, reconstructedHeaders.getFrameContentLength()); } @Test(expected = BadCiphertextException.class) public void invalidFrameLen() { final boolean isFinalFrame = false; final boolean includeContentLen = true; final byte[] headerBytes = createHeaderBytes(includeContentLen, isFinalFrame); final ByteBuffer headerBuff = ByteBuffer.wrap(headerBytes); // Pull out seq num to move to nonce headerBuff.getInt(); // Pull out nonce to move to content len final byte[] nonce = new byte[nonceLen_]; headerBuff.get(nonce); // Set content length (of type long) to -1; headerBuff.putInt(-1); final CipherFrameHeaders reconstructedHeaders = new CipherFrameHeaders(); reconstructedHeaders.setNonceLength((short) nonceLen_); reconstructedHeaders.includeFrameSize(includeContentLen); reconstructedHeaders.deserialize(headerBuff.array(), 0); } @Test(expected = AwsCryptoException.class) public void nullNonce() { boolean isFinalFrame = false; new CipherFrameHeaders(testSeqNum_, null, testFrameContentLen_, isFinalFrame); } @Test(expected = AwsCryptoException.class) public void invalidNonce() { boolean isFinalFrame = false; new CipherFrameHeaders( testSeqNum_, new byte[Constants.MAX_NONCE_LENGTH + 1], testFrameContentLen_, isFinalFrame); } @Test public void byteFormatCheck() { boolean isFinalFrame = false; nonce_ = ByteFormatCheckValues.getNonce(); final CipherFrameHeaders cipherFrameHeaders = new CipherFrameHeaders(testSeqNum_, nonce_, testFrameContentLen_, isFinalFrame); final byte[] cipherFrameHeaderHash = TestIOUtils.getSha256Hash(cipherFrameHeaders.toByteArray()); assertArrayEquals(ByteFormatCheckValues.getCipherFrameHeaderHash(), cipherFrameHeaderHash); } @Test public void byteFormatCheckforFinalFrame() { boolean isFinalFrame = true; nonce_ = ByteFormatCheckValues.getNonce(); final CipherFrameHeaders cipherFinalFrameHeaders = new CipherFrameHeaders(testSeqNum_, nonce_, testFrameContentLen_, isFinalFrame); final byte[] cipherFinalFrameHeaderHash = TestIOUtils.getSha256Hash(cipherFinalFrameHeaders.toByteArray()); assertArrayEquals( ByteFormatCheckValues.getCipherFinalFrameHeaderHash(), cipherFinalFrameHeaderHash); } }
768
0
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk/model/CipherBlockHeadersTest.java
/* * Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except * in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.amazonaws.encryptionsdk.model; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import com.amazonaws.encryptionsdk.exception.AwsCryptoException; import com.amazonaws.encryptionsdk.exception.BadCiphertextException; import com.amazonaws.encryptionsdk.internal.Constants; import com.amazonaws.encryptionsdk.internal.RandomBytesGenerator; import com.amazonaws.encryptionsdk.internal.TestIOUtils; import java.nio.ByteBuffer; import java.util.Arrays; import org.junit.Test; public class CipherBlockHeadersTest { final int nonceLen_ = 12; byte[] nonce_ = RandomBytesGenerator.generate(nonceLen_); final int sampleContentLen_ = 1024; @Test public void serializeDeserialize() { final CipherBlockHeaders cipherBlockHeaders = new CipherBlockHeaders(nonce_, sampleContentLen_); final byte[] headerBytes = cipherBlockHeaders.toByteArray(); final CipherBlockHeaders reconstructedHeaders = new CipherBlockHeaders(); reconstructedHeaders.setNonceLength((short) nonceLen_); reconstructedHeaders.deserialize(headerBytes, 0); final byte[] reconstructedHeaderBytes = reconstructedHeaders.toByteArray(); assertArrayEquals(headerBytes, reconstructedHeaderBytes); } private boolean serializeDeserializeStreaming(final boolean isFinalFrame) { final CipherBlockHeaders cipherBlockHeaders = new CipherBlockHeaders(nonce_, sampleContentLen_); final byte[] headerBytes = cipherBlockHeaders.toByteArray(); final CipherBlockHeaders reconstructedHeaders = new CipherBlockHeaders(); reconstructedHeaders.setNonceLength((short) nonceLen_); int totalParsedBytes = 0; int bytesToParseLen = 1; int bytesParsed; while (reconstructedHeaders.isComplete() == false) { final byte[] bytesToParse = new byte[bytesToParseLen]; System.arraycopy(headerBytes, totalParsedBytes, bytesToParse, 0, bytesToParse.length); bytesParsed = reconstructedHeaders.deserialize(bytesToParse, 0); if (bytesParsed == 0) { bytesToParseLen++; } else { totalParsedBytes += bytesParsed; bytesToParseLen = 1; } } final byte[] reconstructedHeaderBytes = reconstructedHeaders.toByteArray(); return Arrays.equals(headerBytes, reconstructedHeaderBytes) ? true : false; } @Test public void serializeDeserializeStreamingFinalFrame() { assertTrue(serializeDeserializeStreaming(true)); } @Test public void deserializeNull() { final CipherBlockHeaders cipherBlockHeaders = new CipherBlockHeaders(); final int deserializedBytes = cipherBlockHeaders.deserialize(null, 0); assertEquals(0, deserializedBytes); } @Test public void checkContentLen() { final CipherBlockHeaders cipherBlockHeaders = new CipherBlockHeaders(nonce_, sampleContentLen_); final byte[] headerBytes = cipherBlockHeaders.toByteArray(); final CipherBlockHeaders reconstructedHeaders = new CipherBlockHeaders(); reconstructedHeaders.setNonceLength((short) nonceLen_); reconstructedHeaders.deserialize(headerBytes, 0); assertEquals(sampleContentLen_, reconstructedHeaders.getContentLength()); } @Test public void checkNonce() { final CipherBlockHeaders cipherBlockHeaders = new CipherBlockHeaders(nonce_, sampleContentLen_); final byte[] headerBytes = cipherBlockHeaders.toByteArray(); final CipherBlockHeaders reconstructedHeaders = new CipherBlockHeaders(); reconstructedHeaders.setNonceLength((short) nonceLen_); reconstructedHeaders.deserialize(headerBytes, 0); assertArrayEquals(nonce_, reconstructedHeaders.getNonce()); } @Test public void checkNullNonce() { final CipherBlockHeaders cipherBlockHeaders = new CipherBlockHeaders(); cipherBlockHeaders.setNonceLength((short) nonceLen_); assertArrayEquals(null, cipherBlockHeaders.getNonce()); } @Test(expected = AwsCryptoException.class) public void nullNonce() { new CipherBlockHeaders(null, sampleContentLen_); } @Test(expected = AwsCryptoException.class) public void invalidNonce() { new CipherBlockHeaders(new byte[Constants.MAX_NONCE_LENGTH + 1], sampleContentLen_); } @Test(expected = BadCiphertextException.class) public void invalidContentLen() { final CipherBlockHeaders cipherBlockHeaders = new CipherBlockHeaders(nonce_, sampleContentLen_); final byte[] headerBytes = cipherBlockHeaders.toByteArray(); final ByteBuffer headerBuff = ByteBuffer.wrap(headerBytes); // Pull out nonce to move to content len final byte[] nonce = new byte[nonceLen_]; headerBuff.get(nonce); // Set content length (of type long) to -1; headerBuff.putLong(-1); final CipherBlockHeaders reconstructedHeaders = new CipherBlockHeaders(); reconstructedHeaders.setNonceLength((short) nonceLen_); reconstructedHeaders.deserialize(headerBuff.array(), 0); } @Test public void byteFormatCheck() { nonce_ = ByteFormatCheckValues.getNonce(); final CipherBlockHeaders cipherBlockHeaders = new CipherBlockHeaders(nonce_, sampleContentLen_); final byte[] cipherBlockHeaderHash = TestIOUtils.getSha256Hash(cipherBlockHeaders.toByteArray()); assertArrayEquals(ByteFormatCheckValues.getCipherBlockHeaderHash(), cipherBlockHeaderHash); } }
769
0
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk/model/ByteFormatCheckValues.java
/* * Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except * in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.amazonaws.encryptionsdk.model; import com.amazonaws.encryptionsdk.internal.Utils; public class ByteFormatCheckValues { private static final String base64MessageId_ = "NQ/NXvg4mMN5zm5JFZHUWw=="; private static final String base64PlaintextKey_ = "N9vW5Ox5xh4BrUgeaL2gXg=="; private static final String base64EncryptedKey_ = "Zg5VUzPfgD0/H92Fx7h0ew=="; private static final String base64Nonce_ = "3rktZhNbwrZBSaqt"; private static final String base64Tag_ = "cBPLjSEz0fsWDToxTqMvfQ=="; private static final String base64CiphertextHeaderHash_ = "bCScP4wa25l9TLQZ4KLv7xqVCg9AN58lB1FHrl2yVes="; private static final String base64BlockHeaderHash_ = "7q8fULz95XaJqrksEuzDoVpSYih54QbPC1+v833s/5Y="; private static final String base64FrameHeaderHash_ = "tB/UmW+/hLJU5i2D9Or8guXrn8lP0uCiUaP1KkdyKGs="; private static final String base64FinalFrameHeaderHash_ = "/b2fVFOxvnaM5vXDMGyyFPNTWMjuU/c/48qeH3uTHj0="; public static byte[] getMessageId() { return Utils.decodeBase64String(base64MessageId_); } public static byte[] getEncryptedKey() { return Utils.decodeBase64String(base64EncryptedKey_); } public static byte[] getPlaintextKey() { return Utils.decodeBase64String(base64PlaintextKey_); } public static byte[] getCiphertextHeaderHash() { return Utils.decodeBase64String(base64CiphertextHeaderHash_); } public static byte[] getCipherBlockHeaderHash() { return Utils.decodeBase64String(base64BlockHeaderHash_); } public static byte[] getCipherFrameHeaderHash() { return Utils.decodeBase64String(base64FrameHeaderHash_); } public static byte[] getCipherFinalFrameHeaderHash() { return Utils.decodeBase64String(base64FinalFrameHeaderHash_); } public static byte[] getNonce() { return Utils.decodeBase64String(base64Nonce_); } public static byte[] getTag() { return Utils.decodeBase64String(base64Tag_); } }
770
0
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk/caching/LocalCryptoMaterialsCacheTest.java
package com.amazonaws.encryptionsdk.caching; import static com.amazonaws.encryptionsdk.TestUtils.assertThrows; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import com.amazonaws.encryptionsdk.caching.CryptoMaterialsCache.UsageStats; import com.amazonaws.encryptionsdk.model.DecryptionMaterials; import com.amazonaws.encryptionsdk.model.EncryptionMaterials; import java.lang.reflect.Field; import java.util.Map; import java.util.Optional; import org.junit.Assert; import org.junit.Before; import org.junit.Test; public class LocalCryptoMaterialsCacheTest { public static final String PARTTION_NAME = "foo"; FakeClock clock; LocalCryptoMaterialsCache cache; CryptoMaterialsCache.CacheHint hint = () -> 1000; // maxAge = 1000 @Before public void setUp() { clock = new FakeClock(); cache = new LocalCryptoMaterialsCache(5); cache.clock = clock; } @Test public void whenNoEntriesInCache_noEntriesReturned() { assertNull(cache.getEntryForDecrypt(new byte[10])); byte[] cacheId = new byte[10]; assertNull(cache.getEntryForEncrypt(cacheId, UsageStats.ZERO)); } @Test public void whenEntriesAddedToDecryptCache_correctEntriesReturned() { DecryptionMaterials result1 = CacheTestFixtures.createDecryptResult(CacheTestFixtures.createDecryptRequest(1)); DecryptionMaterials result2 = CacheTestFixtures.createDecryptResult(CacheTestFixtures.createDecryptRequest(2)); cache.putEntryForDecrypt(new byte[] {1}, result1, hint); cache.putEntryForDecrypt(new byte[] {2}, result2, hint); assertEquals(result2, cache.getEntryForDecrypt(new byte[] {2}).getResult()); assertEquals(result1, cache.getEntryForDecrypt(new byte[] {1}).getResult()); } @Test public void whenManyDecryptEntriesAdded_LRURespected() { DecryptionMaterials[] results = new DecryptionMaterials[6]; for (int i = 0; i < results.length; i++) { results[i] = CacheTestFixtures.createDecryptResult(CacheTestFixtures.createDecryptRequest(i)); } cache.putEntryForDecrypt(new byte[] {0}, results[0], hint); cache.putEntryForDecrypt(new byte[] {1}, results[1], hint); cache.putEntryForDecrypt(new byte[] {2}, results[2], hint); cache.putEntryForDecrypt(new byte[] {3}, results[3], hint); cache.putEntryForDecrypt(new byte[] {4}, results[4], hint); // make entry 0 most recently used assertEquals(results[0], cache.getEntryForDecrypt(new byte[] {0}).getResult()); // entry 1 is evicted cache.putEntryForDecrypt(new byte[] {5}, results[5], hint); for (int i = 0; i < results.length; i++) { DecryptionMaterials actualResult = Optional.ofNullable(cache.getEntryForDecrypt(new byte[] {(byte) i})) .map(CryptoMaterialsCache.DecryptCacheEntry::getResult) .orElse(null); DecryptionMaterials expected = (i == 1) ? null : results[i]; assertEquals("index " + i, expected, actualResult); } } @Test public void whenEncryptEntriesAdded_theyCanBeRetrieved() { EncryptionMaterials result1a = CacheTestFixtures.createMaterialsResult(CacheTestFixtures.createMaterialsRequest(0)); EncryptionMaterials result1b = CacheTestFixtures.createMaterialsResult(CacheTestFixtures.createMaterialsRequest(0)); EncryptionMaterials result2 = CacheTestFixtures.createMaterialsResult(CacheTestFixtures.createMaterialsRequest(1)); cache.putEntryForEncrypt(new byte[] {0}, result1a, hint, UsageStats.ZERO); cache.putEntryForEncrypt(new byte[] {0}, result1b, hint, UsageStats.ZERO); cache.putEntryForEncrypt(new byte[] {1}, result2, hint, UsageStats.ZERO); assertEncryptEntry(new byte[] {0}, result1b); assertEncryptEntry(new byte[] {1}, result2); } @Test public void whenInitialUsagePassed_itIsRetained() { UsageStats stats = new UsageStats(123, 456); EncryptionMaterials result1a = CacheTestFixtures.createMaterialsResult(CacheTestFixtures.createMaterialsRequest(0)); cache.putEntryForEncrypt(new byte[] {0}, result1a, hint, stats); assertEquals(stats, cache.getEntryForEncrypt(new byte[] {0}, UsageStats.ZERO).getUsageStats()); } @Test public void whenManyEncryptEntriesAdded_LRUIsRespected() { EncryptionMaterials[] results = new EncryptionMaterials[6]; for (int i = 0; i < results.length; i++) { results[i] = CacheTestFixtures.createMaterialsResult(CacheTestFixtures.createMaterialsRequest(i / 3)); cache.putEntryForEncrypt(new byte[] {(byte) (i)}, results[i], hint, UsageStats.ZERO); } for (int i = 0; i < results.length; i++) { EncryptionMaterials expected = i == 0 ? null : results[i]; assertEncryptEntry(new byte[] {(byte) i}, expected); } } @Test public void whenManyEncryptEntriesAdded_andEntriesTouched_LRUIsRespected() { EncryptionMaterials[] results = new EncryptionMaterials[6]; for (int i = 0; i < 3; i++) { results[i] = CacheTestFixtures.createMaterialsResult(CacheTestFixtures.createMaterialsRequest(0)); cache.putEntryForEncrypt(new byte[] {(byte) i}, results[i], hint, UsageStats.ZERO); } cache.getEntryForEncrypt(new byte[] {0}, UsageStats.ZERO); for (int i = 3; i < 6; i++) { results[i] = CacheTestFixtures.createMaterialsResult(CacheTestFixtures.createMaterialsRequest(0)); cache.putEntryForEncrypt(new byte[] {(byte) i}, results[i], hint, UsageStats.ZERO); } assertEncryptEntry(new byte[] {0}, results[0]); assertEncryptEntry(new byte[] {1}, null); assertEncryptEntry(new byte[] {2}, results[2]); assertEncryptEntry(new byte[] {3}, results[3]); assertEncryptEntry(new byte[] {4}, results[4]); assertEncryptEntry(new byte[] {5}, results[5]); } @Test public void whenManyEncryptEntriesAdded_andEntryInvalidated_LRUIsRespected() { EncryptionMaterials[] results = new EncryptionMaterials[6]; for (int i = 0; i < 3; i++) { results[i] = CacheTestFixtures.createMaterialsResult(CacheTestFixtures.createMaterialsRequest(0)); cache.putEntryForEncrypt(new byte[] {(byte) i}, results[i], hint, UsageStats.ZERO); } cache.getEntryForEncrypt(new byte[] {2}, UsageStats.ZERO).invalidate(); for (int i = 3; i < 6; i++) { results[i] = CacheTestFixtures.createMaterialsResult(CacheTestFixtures.createMaterialsRequest(0)); cache.putEntryForEncrypt(new byte[] {(byte) i}, results[i], hint, UsageStats.ZERO); } assertEncryptEntry(new byte[] {0}, results[0]); assertEncryptEntry(new byte[] {1}, results[1]); assertEncryptEntry(new byte[] {2}, null); assertEncryptEntry(new byte[] {3}, results[3]); assertEncryptEntry(new byte[] {4}, results[4]); assertEncryptEntry(new byte[] {5}, results[5]); } @Test public void testCacheEntryBehavior() { EncryptionMaterials result = createResult(); CryptoMaterialsCache.EncryptCacheEntry e = cache.putEntryForEncrypt(new byte[] {0}, result, hint, new UsageStats(1, 2)); assertEquals(clock.now, e.getEntryCreationTime()); assertEquals(new UsageStats(1, 2), e.getUsageStats()); CryptoMaterialsCache.EncryptCacheEntry e2 = cache.getEntryForEncrypt(new byte[] {0}, new UsageStats(200, 100)); // Old entry usage is unchanged assertEquals(new UsageStats(1, 2), e.getUsageStats()); assertEquals(new UsageStats(201, 102), e2.getUsageStats()); e2.invalidate(); // All EncryptCacheEntry methods should still work after invalidation Assert.assertEquals(result, e2.getResult()); assertEquals(new UsageStats(201, 102), e2.getUsageStats()); } @Test public void whenTTLExceeded_encryptEntriesAreEvicted() throws Exception { EncryptionMaterials result = createResult(); cache.putEntryForEncrypt(new byte[] {0}, result, () -> 500, UsageStats.ZERO); clock.now += 500; assertEncryptEntry(new byte[] {0}, result); clock.now += 1; assertEncryptEntry(new byte[] {0}, null); // Verify that the cache isn't hanging on to memory once it notices the entry is expired assertEquals(0, getCacheMap(cache).size()); } @Test public void whenManyEntriesExpireAtOnce_expiredEncryptEntriesStillNotReturned() { // Our active TTL expiration logic will only remove a certain number of entries per call, make // sure that even // if we bail out before removing a particular entry, it's still filtered from the return value. cache = new LocalCryptoMaterialsCache(200); cache.clock = clock; for (int i = 0; i < 100; i++) { cache.putEntryForEncrypt(new byte[] {(byte) i}, createResult(), () -> 500, UsageStats.ZERO); } cache.putEntryForEncrypt(new byte[] {(byte) 0xFF}, createResult(), () -> 501, UsageStats.ZERO); clock.now += 502; assertEncryptEntry(new byte[] {(byte) 0xFF}, null); } @Test public void whenAccessed_encryptEntryTTLNotReset() { EncryptionMaterials result = createResult(); cache.putEntryForEncrypt(new byte[] {0}, result, hint, UsageStats.ZERO); clock.now += 1000; assertEncryptEntry(new byte[] {0}, result); clock.now += 1; assertEncryptEntry(new byte[] {0}, null); } @Test public void whenTTLExceeded_decryptEntriesAreEvicted() throws Exception { DecryptionMaterials result = CacheTestFixtures.createDecryptResult(CacheTestFixtures.createDecryptRequest(0)); cache.putEntryForDecrypt(new byte[] {0}, result, hint); clock.now += 1001; assertNull(cache.getEntryForDecrypt(new byte[] {0})); // Verify that the cache isn't hanging on to memory once it notices the entry is expired assertEquals(0, getCacheMap(cache).size()); } @Test public void whenAccessed_decryptEntryTTLNotReset() { DecryptionMaterials result = CacheTestFixtures.createDecryptResult(CacheTestFixtures.createDecryptRequest(0)); cache.putEntryForDecrypt(new byte[] {0}, result, hint); clock.now += 500; assertNotNull(cache.getEntryForDecrypt(new byte[] {0})); clock.now += 501; assertNull(cache.getEntryForDecrypt(new byte[] {0})); } @Test public void whenManyEntriesExpireAtOnce_expiredDecryptEntriesStillNotReturned() { cache = new LocalCryptoMaterialsCache(200); cache.clock = clock; for (int i = 0; i < 100; i++) { cache.putEntryForEncrypt( new byte[] {(byte) (i + 1)}, createResult(), () -> 500, UsageStats.ZERO); } DecryptionMaterials result = CacheTestFixtures.createDecryptResult(CacheTestFixtures.createDecryptRequest(0)); cache.putEntryForDecrypt(new byte[] {0}, result, () -> 501); // our encrypt entries will expire first clock.now += 502; assertNull(cache.getEntryForDecrypt(new byte[] {0})); } @Test public void testDecryptInvalidate() { DecryptionMaterials result = CacheTestFixtures.createDecryptResult(CacheTestFixtures.createDecryptRequest(0)); cache.putEntryForDecrypt(new byte[] {0}, result, hint); cache.getEntryForDecrypt(new byte[] {0}).invalidate(); assertNull(cache.getEntryForDecrypt(new byte[] {0})); } @Test public void testDecryptEntryCreationTime() { DecryptionMaterials result = CacheTestFixtures.createDecryptResult(CacheTestFixtures.createDecryptRequest(0)); cache.putEntryForDecrypt(new byte[] {0}, result, hint); assertEquals( clock.timestamp(), cache.getEntryForDecrypt(new byte[] {0}).getEntryCreationTime()); } @Test public void whenIdentifiersDifferInLowOrderBytes_theyAreNotConsideredEquivalent() throws Exception { DecryptionMaterials result = CacheTestFixtures.createDecryptResult(CacheTestFixtures.createDecryptRequest(0)); cache.putEntryForDecrypt(new byte[128], result, hint); for (int i = 0; i < 128; i++) { byte[] otherIdentifier = new byte[128]; otherIdentifier[i]++; assertNull(cache.getEntryForDecrypt(otherIdentifier)); } } @Test public void testUsageStatsCtorValidation() { assertThrows(() -> new UsageStats(1, -1)); assertThrows(() -> new UsageStats(-1, 1)); } private EncryptionMaterials createResult() { return CacheTestFixtures.createMaterialsResult(CacheTestFixtures.createMaterialsRequest(0)); } private void assertEncryptEntry(byte[] cacheId, EncryptionMaterials expectedResult) { CryptoMaterialsCache.EncryptCacheEntry entry = cache.getEntryForEncrypt(cacheId, UsageStats.ZERO); EncryptionMaterials actual = entry == null ? null : entry.getResult(); assertEquals(expectedResult, actual); } private Map getCacheMap(LocalCryptoMaterialsCache cache) throws Exception { Field field = LocalCryptoMaterialsCache.class.getDeclaredField("cacheMap"); field.setAccessible(true); return (Map) field.get(cache); } private static final class FakeClock implements MsClock { long now = 0x1_0000_0000L; @Override public long timestamp() { return now; } } }
771
0
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk/caching/CacheIdentifierTests.java
package com.amazonaws.encryptionsdk.caching; import static com.amazonaws.encryptionsdk.CryptoAlgorithm.ALG_AES_128_GCM_IV12_TAG16_HKDF_SHA256; import static com.amazonaws.encryptionsdk.CryptoAlgorithm.ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA384_ECDSA_P384; import static java.nio.charset.StandardCharsets.UTF_8; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.mock; import com.amazonaws.encryptionsdk.CommitmentPolicy; import com.amazonaws.encryptionsdk.CryptoAlgorithm; import com.amazonaws.encryptionsdk.CryptoMaterialsManager; import com.amazonaws.encryptionsdk.TestUtils; import com.amazonaws.encryptionsdk.internal.Utils; import com.amazonaws.encryptionsdk.model.DecryptionMaterialsRequest; import com.amazonaws.encryptionsdk.model.EncryptionMaterialsRequest; import com.amazonaws.encryptionsdk.model.KeyBlob; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; import org.bouncycastle.util.encoders.Hex; import org.junit.Test; public class CacheIdentifierTests { static String partitionName = "c15b9079-6d0e-42b6-8784-5e804b025692"; static Map<String, String> contextEmpty = Collections.emptyMap(); static Map<String, String> contextFull; static CommitmentPolicy commitmentPolicy = TestUtils.DEFAULT_TEST_COMMITMENT_POLICY; static { contextFull = new HashMap<>(); contextFull.put("this", "is"); contextFull.put("a", "non-empty"); contextFull.put("encryption", "context"); } static List<KeyBlob> keyBlobs = Arrays.asList( new KeyBlob( "this is a provider ID", "this is some key info".getBytes(UTF_8), "super secret key, now with encryption!".getBytes(UTF_8)), new KeyBlob( "another provider ID!", "this is some different key info".getBytes(UTF_8), "better super secret key, now with encryption!".getBytes(UTF_8))); @Test public void pythonTestVecs() throws Exception { assertEncryptId( partitionName, null, contextEmpty, "rkrFAso1YyPbOJbmwVMjrPw+wwLJT7xusn8tA8zMe9e3+OqbtfDueB7bvoKLU3fsmdUvZ6eMt7mBp1ThMMB25Q=="); assertEncryptId( partitionName, ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA384_ECDSA_P384, contextEmpty, "3icBIkLK4V3fVwbm3zSxUdUQV6ZvZYUOLl8buN36g6gDMqAkghcGryxX7QiVABkW1JhB6GRp5z+bzbiuciBcKQ=="); assertEncryptId( partitionName, null, contextFull, "IHiUHYOUVUEFTc3BcZPJDlsWct2Qy1A7JdfQl9sQoV/ILIbRpoz9q7RtGd/MlibaGl5ihE66cN8ygM8A5rtYbg=="); assertEncryptId( partitionName, ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA384_ECDSA_P384, contextFull, "mRNK7qhTb/kJiiyGPgAevp0gwFRcET4KeeNYwZHhoEDvSUzQiDgl8Of+YRDaVzKxAqpNBgcAuFXde9JlaRRsmw=="); assertDecryptId( partitionName, ALG_AES_128_GCM_IV12_TAG16_HKDF_SHA256, Collections.singletonList(keyBlobs.get(0)), contextEmpty, "n0zVzk9QIVxhz6ET+aJIKKOJNxtpGtSe1yAbu7WU5l272Iw/jmhlER4psDHJs9Mr8KYiIvLGSXzggNDCc23+9w=="); assertDecryptId( partitionName, ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA384_ECDSA_P384, keyBlobs, contextFull, "+rtwUe38CGnczGmYu12iqGWHIyDyZ44EvYQ4S6ACmsgS8VaEpiw0RTGpDk6Z/7YYN/jVHOAcNKDyCNP8EmstFg=="); } void assertDecryptId( String partitionName, CryptoAlgorithm algo, List<KeyBlob> blobs, Map<String, String> context, String expect) throws Exception { DecryptionMaterialsRequest request = DecryptionMaterialsRequest.newBuilder() .setAlgorithm(algo) .setEncryptionContext(context) .setEncryptedDataKeys(blobs) .build(); byte[] id = getCacheIdentifier(getCMM(partitionName), request); assertEquals(expect, Utils.encodeBase64String(id)); } void assertEncryptId( String partitionName, CryptoAlgorithm algo, Map<String, String> context, String expect) throws Exception { EncryptionMaterialsRequest request = EncryptionMaterialsRequest.newBuilder() .setContext(context) .setRequestedAlgorithm(algo) .setCommitmentPolicy(commitmentPolicy) .build(); byte[] id = getCacheIdentifier(getCMM(partitionName), request); assertEquals(expect, Utils.encodeBase64String(id)); } @Test public void encryptDigestTestVector() throws Exception { HashMap<String, String> contextMap = new HashMap<>(); contextMap.put("\0\0TEST", "\0\0test"); // Note! This key is actually U+10000, but java treats it as a UTF-16 surrogate pair. // UTF-8 encoding should be 0xF0 0x90 0x80 0x80 contextMap.put("\uD800\uDC00", "UTF-16 surrogate"); contextMap.put("\uABCD", "\\uABCD"); byte[] id = getCacheIdentifier( getCMM("partition ID"), EncryptionMaterialsRequest.newBuilder() .setContext(contextMap) .setRequestedAlgorithm(null) .setCommitmentPolicy(commitmentPolicy) .build()); assertEquals( "683328d033fc60a20e3d3936190b33d91aad0143163226af9530e7d1b3de0e96" + "39c00a2885f9cea09cf9a273bef316a39616475b50adc2441b69f67e1a25145f", new String(Hex.encode(id))); id = getCacheIdentifier( getCMM("partition ID"), EncryptionMaterialsRequest.newBuilder() .setContext(contextMap) .setRequestedAlgorithm(CryptoAlgorithm.ALG_AES_128_GCM_IV12_TAG16_HKDF_SHA256) .setCommitmentPolicy(commitmentPolicy) .build()); assertEquals( "3dc70ff1d4621059b97179563ab6592dff4319bfaf8ed1a819c96d33d3194d5c" + "354a361e879d0356e4d9e868170ebc9e934fa5eaf6e6d11de4ee801645723fa9", new String(Hex.encode(id))); } @Test public void decryptDigestTestVector() throws Exception { HashMap<String, String> contextMap = new HashMap<>(); contextMap.put("\0\0TEST", "\0\0test"); // Note! This key is actually U+10000, but java treats it as a UTF-16 surrogate pair. // UTF-8 encoding should be 0xF0 0x90 0x80 0x80 contextMap.put("\uD800\uDC00", "UTF-16 surrogate"); contextMap.put("\uABCD", "\\uABCD"); ArrayList<KeyBlob> keyBlobs = new ArrayList<>(); keyBlobs.addAll( Arrays.asList( new KeyBlob("", new byte[] {}, new byte[] {}), // always first new KeyBlob("\0", new byte[] {0}, new byte[] {0}), new KeyBlob("\u0081", new byte[] {(byte) 0x81}, new byte[] {(byte) 0x81}), new KeyBlob("abc", Hex.decode("deadbeef"), Hex.decode("bad0cafe")))); assertEquals( "e16344634350fe8cb51e69ec4e0681c84ac7ef2df427bd4de4aefbebcd3ead22" + "95f1b15a98ce60699e0efbf69dbbc12e2552b16eff84a6e9b5766ee4d69a7897", new String( Hex.encode( getCacheIdentifier( getCMM("partition ID"), DecryptionMaterialsRequest.newBuilder() .setAlgorithm( CryptoAlgorithm.ALG_AES_128_GCM_IV12_TAG16_HKDF_SHA256_ECDSA_P256) .setEncryptionContext(contextMap) .setEncryptedDataKeys(keyBlobs) .build())))); } private byte[] getCacheIdentifier( CachingCryptoMaterialsManager cmm, EncryptionMaterialsRequest request) throws Exception { Method m = CachingCryptoMaterialsManager.class.getDeclaredMethod( "getCacheIdentifier", EncryptionMaterialsRequest.class); m.setAccessible(true); return (byte[]) m.invoke(cmm, request); } private byte[] getCacheIdentifier( CachingCryptoMaterialsManager cmm, DecryptionMaterialsRequest request) throws Exception { Method m = CachingCryptoMaterialsManager.class.getDeclaredMethod( "getCacheIdentifier", DecryptionMaterialsRequest.class); m.setAccessible(true); return (byte[]) m.invoke(cmm, request); } private CachingCryptoMaterialsManager getCMM(final String partitionName) { return CachingCryptoMaterialsManager.newBuilder() .withCache(mock(CryptoMaterialsCache.class)) .withBackingMaterialsManager(mock(CryptoMaterialsManager.class)) .withMaxAge(1, TimeUnit.MILLISECONDS) .withPartitionId(partitionName) .build(); } }
772
0
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk/caching/CacheTestFixtures.java
package com.amazonaws.encryptionsdk.caching; import com.amazonaws.encryptionsdk.CommitmentPolicy; import com.amazonaws.encryptionsdk.DataKey; import com.amazonaws.encryptionsdk.DefaultCryptoMaterialsManager; import com.amazonaws.encryptionsdk.MasterKey; import com.amazonaws.encryptionsdk.TestUtils; import com.amazonaws.encryptionsdk.jce.JceMasterKey; import com.amazonaws.encryptionsdk.model.DecryptionMaterials; import com.amazonaws.encryptionsdk.model.DecryptionMaterialsRequest; import com.amazonaws.encryptionsdk.model.EncryptionMaterials; import com.amazonaws.encryptionsdk.model.EncryptionMaterialsRequest; import java.util.Collections; import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec; public class CacheTestFixtures { private static final CommitmentPolicy commitmentPolicy = TestUtils.DEFAULT_TEST_COMMITMENT_POLICY; private static final MasterKey<?> FIXED_KEY = JceMasterKey.getInstance( new SecretKeySpec(TestUtils.insecureRandomBytes(16), "AES"), "prov", "keyid", "AES/GCM/NoPadding"); public static EncryptionMaterialsRequest createMaterialsRequest(int index) { return EncryptionMaterialsRequest.newBuilder() .setContext(Collections.singletonMap("index", Integer.toString(index))) .setCommitmentPolicy(commitmentPolicy) .build(); } public static EncryptionMaterials createMaterialsResult(EncryptionMaterialsRequest request) { return new DefaultCryptoMaterialsManager(FIXED_KEY) .getMaterialsForEncrypt(request).toBuilder().setCleartextDataKey(new SentinelKey()).build(); } public static DecryptionMaterialsRequest createDecryptRequest(int index) { EncryptionMaterialsRequest mreq = createMaterialsRequest(index); EncryptionMaterials mres = createMaterialsResult(mreq); return createDecryptRequest(mres); } public static DecryptionMaterialsRequest createDecryptRequest(EncryptionMaterials mres) { return DecryptionMaterialsRequest.newBuilder() .setAlgorithm(mres.getAlgorithm()) .setEncryptionContext(mres.getEncryptionContext()) .setEncryptedDataKeys(mres.getEncryptedDataKeys()) .build(); } public static DecryptionMaterials createDecryptResult(DecryptionMaterialsRequest request) { DecryptionMaterials realResult = new DefaultCryptoMaterialsManager(FIXED_KEY).decryptMaterials(request); return realResult.toBuilder() .setDataKey( new DataKey( new SentinelKey(), realResult.getDataKey().getEncryptedDataKey(), realResult.getDataKey().getProviderInformation(), realResult.getDataKey().getMasterKey())) .build(); } static EncryptionMaterials createMaterialsResult() { return createMaterialsResult(createMaterialsRequest(0)); } // These SentinelKeys let us detect when a particular DecryptionMaterials or EncryptionMaterials // is being used, without // being concerned about matching all of the fields - we can just use object identity. public static class SentinelKey implements SecretKey { @Override public String getAlgorithm() { return "AES"; } @Override public String getFormat() { return "RAW"; } @Override public byte[] getEncoded() { return null; } } }
773
0
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk/caching/NullCryptoMaterialsCacheTest.java
package com.amazonaws.encryptionsdk.caching; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; import com.amazonaws.encryptionsdk.model.DecryptionMaterials; import com.amazonaws.encryptionsdk.model.DecryptionMaterialsRequest; import com.amazonaws.encryptionsdk.model.EncryptionMaterials; import com.amazonaws.encryptionsdk.model.EncryptionMaterialsRequest; import org.junit.Test; public class NullCryptoMaterialsCacheTest { @Test public void testEncryptPath() { NullCryptoMaterialsCache cache = new NullCryptoMaterialsCache(); EncryptionMaterialsRequest req = CacheTestFixtures.createMaterialsRequest(1); EncryptionMaterials result = CacheTestFixtures.createMaterialsResult(req); CryptoMaterialsCache.UsageStats stats = new CryptoMaterialsCache.UsageStats(123, 456); CryptoMaterialsCache.EncryptCacheEntry entry = cache.putEntryForEncrypt(new byte[1], result, () -> Long.MAX_VALUE, stats); assertEquals(result, entry.getResult()); assertFalse(entry.getEntryCreationTime() > System.currentTimeMillis()); assertEquals(stats, entry.getUsageStats()); ; // the entry should not be in the "cache" byte[] cacheId = new byte[1]; assertNull(cache.getEntryForEncrypt(cacheId, CryptoMaterialsCache.UsageStats.ZERO)); entry.invalidate(); // shouldn't throw } @Test public void testDecryptPath() { NullCryptoMaterialsCache cache = new NullCryptoMaterialsCache(); DecryptionMaterialsRequest request = CacheTestFixtures.createDecryptRequest(1); DecryptionMaterials result = CacheTestFixtures.createDecryptResult(request); assertNull(cache.getEntryForDecrypt(new byte[1])); cache.putEntryForDecrypt(new byte[1], result, () -> Long.MAX_VALUE); assertNull(cache.getEntryForDecrypt(new byte[1])); } }
774
0
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk/caching/LocalCryptoMaterialsCacheThreadStormTest.java
package com.amazonaws.encryptionsdk.caching; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import com.amazonaws.encryptionsdk.DataKey; import com.amazonaws.encryptionsdk.caching.CryptoMaterialsCache.UsageStats; import com.amazonaws.encryptionsdk.model.DecryptionMaterials; import com.amazonaws.encryptionsdk.model.EncryptionMaterials; import java.lang.reflect.Field; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.TreeMap; import java.util.TreeSet; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CountDownLatch; import java.util.concurrent.CyclicBarrier; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ThreadLocalRandom; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicLong; import java.util.function.Function; import java.util.function.Supplier; import org.junit.Test; public class LocalCryptoMaterialsCacheThreadStormTest { /* * This test tests the behavior of LocalCryptoMaterialsCache under contention at the cache level. * We specifically test: * * 1. Gets and puts of encrypt and decrypt entries, including entries under the same cache ID for encrypt * 2. Invalidations * 3. Changes to cache capacity * * Periodically, we verify that the system state is sane. This is done by inspecting the private members of * LocalCryptoMaterialsCache and verifying that all cache entries are in the LRU map. */ // Private member accessors private static final Function<LocalCryptoMaterialsCache, HashMap<?, ?>> get_cacheMap; private static final Function<LocalCryptoMaterialsCache, TreeSet<?>> get_expirationQueue; private static <T, R> Function<T, R> getGetter(Class<T> klass, String fieldName) { try { Field f = klass.getDeclaredField(fieldName); f.setAccessible(true); return obj -> { try { return (R) f.get(obj); } catch (Exception e) { throw new RuntimeException(e); } }; } catch (Exception e) { throw new Error(e); } } static { get_cacheMap = getGetter(LocalCryptoMaterialsCache.class, "cacheMap"); get_expirationQueue = getGetter(LocalCryptoMaterialsCache.class, "expirationQueue"); } public static void assertConsistent(LocalCryptoMaterialsCache cache) { synchronized (cache) { HashSet<Object> expirationQueue = new HashSet<>(get_expirationQueue.apply(cache)); HashSet<Object> cacheMap = new HashSet<>(get_cacheMap.apply(cache).values()); assertEquals( "Cache group entries are inconsistent with expiration queue", cacheMap, expirationQueue); } } LocalCryptoMaterialsCache cache; // When barrier request = true, all worker threads will join the barrier twice. CyclicBarrier barrier; volatile boolean barrierRequest = false; CountDownLatch stopRequest = new CountDownLatch(1); // Decrypt results that _might_ be returned. Note that due to race conditions in the test itself, // we might be // missing valid cached values here; if a result is in neither forbiddenKeys nor possibleDecrypts, // then we must // assume that it's allowed to be returned. ConcurrentHashMap<ByteBuffer, ConcurrentHashMap<CacheTestFixtures.SentinelKey, Object>> possibleDecrypts = new ConcurrentHashMap<>(); // The values of the inner map are arbitrary but non-null (we use this effectively like a set) ConcurrentHashMap<ByteBuffer, ConcurrentHashMap<CacheTestFixtures.SentinelKey, Object>> possibleEncrypts = new ConcurrentHashMap<>(); // Counters for debugging the test itself. If null, this debug infrastructure is disabled. private ConcurrentHashMap<String, AtomicLong> counters = null; // new ConcurrentHashMap<>(); void inc(String s) { if (counters != null) { counters.computeIfAbsent(s, ignored -> new AtomicLong(0)).incrementAndGet(); } } private static final EncryptionMaterials BASE_ENCRYPT = CacheTestFixtures.createMaterialsResult(); private static final DecryptionMaterials BASE_DECRYPT = CacheTestFixtures.createDecryptResult(CacheTestFixtures.createDecryptRequest(0)); private void maybeBarrier() { if (barrierRequest) { try { barrier.await(); barrier.await(); } catch (Exception e) { throw new RuntimeException(e); } } } // This thread continually adds items to the decrypt cache, logging ones it added. // The expectedDecryptMap has multiple items because we don't know if the cache expired the prior // one; the // decrypt check thread will check and forget/forbid the expected items that were not found. public void decryptAddThread() { int nItemsBeforeRelax = 200_000; int nItems = 0; try { while (stopRequest.getCount() > 0) { maybeBarrier(); byte[] ref = new byte[3]; ThreadLocalRandom.current().nextBytes(ref); ref[0] = 0; CacheTestFixtures.SentinelKey key = new CacheTestFixtures.SentinelKey(); DecryptionMaterials result = BASE_DECRYPT.toBuilder() .setDataKey( new DataKey( key, new byte[0], new byte[0], BASE_DECRYPT.getDataKey().getMasterKey())) .build(); ConcurrentHashMap<CacheTestFixtures.SentinelKey, Object> expectedDecryptMap = possibleDecrypts.computeIfAbsent( ByteBuffer.wrap(ref), ignored -> new ConcurrentHashMap<>()); synchronized (expectedDecryptMap) { cache.putEntryForDecrypt(ref, result, () -> Long.MAX_VALUE); expectedDecryptMap.put(key, this); } inc("decrypt put"); if (++nItems >= nItemsBeforeRelax) { Thread.sleep(5); nItems = 0; } } } catch (Exception e) { throw new RuntimeException(e); } } // The decrypt check thread verifies that the decrypt results are sane - specifically, if we don't // see an item // that is known to have once been added to the cache, we should not see it reappear later. public void decryptCheckThread() { try { while (stopRequest.getCount() > 0) { maybeBarrier(); byte[] ref = new byte[3]; ThreadLocalRandom.current().nextBytes(ref); ref[0] = 0; ConcurrentHashMap<CacheTestFixtures.SentinelKey, Object> expectedDecryptMap = possibleDecrypts.computeIfAbsent( ByteBuffer.wrap(ref), ignored -> new ConcurrentHashMap<>()); synchronized (expectedDecryptMap) { CryptoMaterialsCache.DecryptCacheEntry result = cache.getEntryForDecrypt(ref); CacheTestFixtures.SentinelKey cachedKey = null; if (result != null) { inc("decrypt: hit"); cachedKey = (CacheTestFixtures.SentinelKey) result.getResult().getDataKey().getKey(); if (expectedDecryptMap.containsKey(cachedKey)) { inc("decrypt: found key in expected"); } else { fail("decrypt: unexpected key"); } } else { inc("decrypt: miss"); } for (CacheTestFixtures.SentinelKey expectedKey : expectedDecryptMap.keySet()) { if (cachedKey != expectedKey) { inc("decrypt: prune"); expectedDecryptMap.remove(expectedKey); } } } } } catch (Exception e) { throw new RuntimeException(e); } } // Continually adds encryption cache entries. public void encryptAddThread() { int nItemsBeforeRelax = 200_000; int nItems = 0; try { while (stopRequest.getCount() > 0) { maybeBarrier(); byte[] ref = new byte[2]; ThreadLocalRandom.current().nextBytes(ref); EncryptionMaterials result = BASE_ENCRYPT.toBuilder() .setCleartextDataKey(new CacheTestFixtures.SentinelKey()) .build(); ConcurrentHashMap<CacheTestFixtures.SentinelKey, Object> keys = possibleEncrypts.computeIfAbsent( ByteBuffer.wrap(ref), ignored -> new ConcurrentHashMap<>()); synchronized (keys) { inc("encrypt: add"); cache.putEntryForEncrypt(ref, result, () -> Long.MAX_VALUE, UsageStats.ZERO); keys.put((CacheTestFixtures.SentinelKey) result.getCleartextDataKey(), this); } if (++nItems >= nItemsBeforeRelax) { Thread.sleep(5); nItems = 0; } } } catch (Exception e) { throw new RuntimeException(e); } } // Verifies that there is no resurrection, as above. public void encryptCheckThread() { try { while (stopRequest.getCount() > 0) { maybeBarrier(); byte[] ref = new byte[2]; ThreadLocalRandom.current().nextBytes(ref); ConcurrentHashMap<CacheTestFixtures.SentinelKey, Object> allowedKeys = possibleEncrypts.computeIfAbsent( ByteBuffer.wrap(ref), ignored -> new ConcurrentHashMap<>()); synchronized (allowedKeys) { HashSet<CacheTestFixtures.SentinelKey> foundKeys = new HashSet<>(); CryptoMaterialsCache.EncryptCacheEntry ece = cache.getEntryForEncrypt(ref, UsageStats.ZERO); if (ece != null) { foundKeys.add((CacheTestFixtures.SentinelKey) ece.getResult().getCleartextDataKey()); } if (foundKeys.isEmpty()) { inc("encrypt check: empty foundRefs"); } else { inc("encrypt check: non-empty foundRefs"); } foundKeys.forEach( foundKey -> { if (!allowedKeys.containsKey(foundKey)) { fail("encrypt check: unexpected key; " + allowedKeys + " " + foundKeys); } }); allowedKeys .keySet() .forEach( allowedKey -> { if (!foundKeys.contains(allowedKey)) { inc("encrypt check: prune"); // safe since this is a concurrent map allowedKeys.remove(allowedKey); } }); } } } catch (Exception e) { throw new RuntimeException(e); } } // Performs a consistency check of the cache entries vs the LRU tracker periodically. Due to the // high overhead // of this test, we run it infrequently. public void checkThread() { try { while (!stopRequest.await(5000, TimeUnit.MILLISECONDS)) { barrierRequest = true; barrier.await(); assertConsistent(cache); inc("consistency check passed"); barrier.await(); } } catch (Exception e) { throw new RuntimeException(e); } } @Test public void test() throws Exception { cache = new LocalCryptoMaterialsCache(100_000); ArrayList<CompletableFuture<?>> futures = new ArrayList<>(); ExecutorService es = Executors.newCachedThreadPool(); ArrayList<Supplier<CompletableFuture<?>>> starters = new ArrayList<>(); for (int i = 0; i < 2; i++) { starters.add(() -> CompletableFuture.runAsync(this::encryptAddThread, es)); starters.add(() -> CompletableFuture.runAsync(this::encryptCheckThread, es)); starters.add(() -> CompletableFuture.runAsync(this::decryptAddThread, es)); starters.add(() -> CompletableFuture.runAsync(this::decryptCheckThread, es)); } starters.add(() -> CompletableFuture.runAsync(this::checkThread, es)); barrier = new CyclicBarrier(starters.size()); try { starters.forEach(s -> futures.add(s.get())); CompletableFuture<?> metaFuture = CompletableFuture.anyOf(futures.toArray(new CompletableFuture[0])); try { metaFuture.get(10, TimeUnit.SECONDS); fail("unexpected termination"); } catch (TimeoutException e) { // ok } } finally { stopRequest.countDown(); es.shutdownNow(); es.awaitTermination(1, TimeUnit.SECONDS); if (counters != null) { new TreeMap<>(counters) .forEach((k, v) -> System.out.println(String.format("%s: %d", k, v.get()))); } } } }
775
0
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk
Create_ds/aws-encryption-sdk-java/src/test/java/com/amazonaws/encryptionsdk/caching/CachingCryptoMaterialsManagerTest.java
package com.amazonaws.encryptionsdk.caching; import static com.amazonaws.encryptionsdk.TestUtils.assertThrows; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotEquals; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.never; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; import com.amazonaws.encryptionsdk.CryptoAlgorithm; import com.amazonaws.encryptionsdk.CryptoMaterialsManager; import com.amazonaws.encryptionsdk.caching.CryptoMaterialsCache.EncryptCacheEntry; import com.amazonaws.encryptionsdk.caching.CryptoMaterialsCache.UsageStats; import com.amazonaws.encryptionsdk.jce.JceMasterKey; import com.amazonaws.encryptionsdk.model.DecryptionMaterials; import com.amazonaws.encryptionsdk.model.DecryptionMaterialsRequest; import com.amazonaws.encryptionsdk.model.EncryptionMaterials; import com.amazonaws.encryptionsdk.model.EncryptionMaterialsRequest; import java.util.Arrays; import java.util.concurrent.TimeUnit; import javax.crypto.spec.SecretKeySpec; import org.junit.Before; import org.junit.Test; import org.mockito.ArgumentCaptor; import org.mockito.Mock; import org.mockito.MockitoAnnotations; public class CachingCryptoMaterialsManagerTest { private static final String PARTITION_ID = "partition ID"; @Mock private CryptoMaterialsCache cache; @Mock private CryptoMaterialsManager delegate; private CachingCryptoMaterialsManager cmm; private CachingCryptoMaterialsManager.Builder builder; private long maxAgeMs = 123456789; @Before public void setUp() throws Exception { MockitoAnnotations.initMocks(this); when(cache.putEntryForEncrypt(any(), any(), any(), any())) .thenAnswer( invocation -> entryFor((EncryptionMaterials) invocation.getArguments()[1], UsageStats.ZERO)); when(delegate.getMaterialsForEncrypt(any())) .thenThrow(new RuntimeException("Unexpected invocation")); when(delegate.decryptMaterials(any())).thenThrow(new RuntimeException("Unexpected invocation")); builder = CachingCryptoMaterialsManager.newBuilder() .withBackingMaterialsManager(delegate) .withCache(cache) .withPartitionId(PARTITION_ID) .withMaxAge(maxAgeMs, TimeUnit.MILLISECONDS) .withByteUseLimit(200) .withMessageUseLimit(100); cmm = builder.build(); } @Test public void whenCacheIsEmpty_performsCacheMiss() throws Exception { EncryptionMaterialsRequest request = CacheTestFixtures.createMaterialsRequest(0).toBuilder().setPlaintextSize(100).build(); EncryptionMaterials result = CacheTestFixtures.createMaterialsResult(request); EncryptCacheEntry entry = setupForCacheMiss(request, result); EncryptionMaterials actualResult = cmm.getMaterialsForEncrypt(request); assertEquals(result, actualResult); verify(delegate).getMaterialsForEncrypt(request); verify(cache).putEntryForEncrypt(any(), any(), any(), eq(new UsageStats(100, 1))); } @Test public void whenCacheMisses_correctHintAndUsagePassed() throws Exception { EncryptionMaterialsRequest request = CacheTestFixtures.createMaterialsRequest(0).toBuilder().setPlaintextSize(100).build(); EncryptionMaterials result = CacheTestFixtures.createMaterialsResult(request); setupForCacheMiss(request, result); cmm.getMaterialsForEncrypt(request); ArgumentCaptor<CryptoMaterialsCache.CacheHint> hintCaptor = ArgumentCaptor.forClass(CryptoMaterialsCache.CacheHint.class); verify(cache).putEntryForEncrypt(any(), any(), hintCaptor.capture(), any()); assertEquals(maxAgeMs, hintCaptor.getValue().getMaxAgeMillis()); } @Test public void whenCacheHasEntry_performsCacheHit() throws Exception { EncryptionMaterialsRequest request = CacheTestFixtures.createMaterialsRequest(0).toBuilder().setPlaintextSize(100).build(); EncryptionMaterials result = CacheTestFixtures.createMaterialsResult(request); EncryptCacheEntry entry = entryFor(result, UsageStats.ZERO); when(cache.getEntryForEncrypt(any(), any())).thenReturn(entry); assertEquals(result, cmm.getMaterialsForEncrypt(request)); verify(delegate, never()).getMaterialsForEncrypt(any()); ArgumentCaptor<UsageStats> statsCaptor = ArgumentCaptor.forClass(UsageStats.class); verify(cache).getEntryForEncrypt(any(), statsCaptor.capture()); assertEquals(statsCaptor.getValue(), new UsageStats(100, 1)); } @Test public void whenAlgorithmIsUncachable_resultNotStoredInCache() throws Exception { EncryptionMaterialsRequest request = CacheTestFixtures.createMaterialsRequest(0).toBuilder().setPlaintextSize(100).build(); EncryptionMaterials result = CacheTestFixtures.createMaterialsResult(request).toBuilder() .setAlgorithm(CryptoAlgorithm.ALG_AES_128_GCM_IV12_TAG16_NO_KDF) .build(); setupForCacheMiss(request, result); CachingCryptoMaterialsManager allowNoKdfCMM = CachingCryptoMaterialsManager.newBuilder() .withBackingMaterialsManager(delegate) .withCache(cache) .withPartitionId(PARTITION_ID) .withMaxAge(maxAgeMs, TimeUnit.MILLISECONDS) .withByteUseLimit(200) .withMessageUseLimit(100) .build(); assertEquals(result, allowNoKdfCMM.getMaterialsForEncrypt(request)); verify(cache, never()).putEntryForEncrypt(any(), any(), any(), any()); } @Test public void whenInitialUsageExceedsLimit_cacheIsBypassed() throws Exception { EncryptionMaterialsRequest request = CacheTestFixtures.createMaterialsRequest(0).toBuilder() // Even at _exactly_ the byte-use limit, we won't try the cache, // because it's unlikely to be useful to leave an entry with zero // bytes remaining. .setPlaintextSize(200) .build(); EncryptionMaterials result = CacheTestFixtures.createMaterialsResult(request).toBuilder() .setAlgorithm(CryptoAlgorithm.ALG_AES_256_GCM_HKDF_SHA512_COMMIT_KEY) .build(); setupForCacheMiss(request, result); assertEquals(result, cmm.getMaterialsForEncrypt(request)); verifyNoMoreInteractions(cache); } @Test public void whenCacheEntryIsExhausted_byMessageLimit_performsCacheMiss() throws Exception { EncryptionMaterialsRequest request = CacheTestFixtures.createMaterialsRequest(0).toBuilder().setPlaintextSize(100).build(); EncryptionMaterials cacheHitResult = CacheTestFixtures.createMaterialsResult(request); doReturn(CacheTestFixtures.createMaterialsResult(request)) .when(delegate) .getMaterialsForEncrypt(request); EncryptCacheEntry entry = entryFor(cacheHitResult, new UsageStats(0, 101)); when(cache.getEntryForEncrypt(any(), any())).thenReturn(entry); EncryptionMaterials returnedResult = cmm.getMaterialsForEncrypt(request); assertNotEquals(cacheHitResult, returnedResult); verify(delegate, times(1)).getMaterialsForEncrypt(any()); verify(cache).putEntryForEncrypt(any(), eq(returnedResult), any(), any()); } @Test public void whenEncryptCacheEntryIsExpired_performsCacheMiss() throws Exception { EncryptionMaterialsRequest request = CacheTestFixtures.createMaterialsRequest(0).toBuilder().setPlaintextSize(100).build(); EncryptionMaterials cacheHitResult = CacheTestFixtures.createMaterialsResult(request); doReturn(CacheTestFixtures.createMaterialsResult(request)) .when(delegate) .getMaterialsForEncrypt(request); EncryptCacheEntry entry = entryFor(cacheHitResult, new UsageStats(0, 100)); when(entry.getEntryCreationTime()).thenReturn(System.currentTimeMillis() - maxAgeMs - 1); when(cache.getEntryForEncrypt(any(), any())).thenReturn(entry); EncryptionMaterials returnedResult = cmm.getMaterialsForEncrypt(request); assertNotEquals(cacheHitResult, returnedResult); verify(delegate, times(1)).getMaterialsForEncrypt(any()); verify(cache).putEntryForEncrypt(any(), eq(returnedResult), any(), any()); verify(entry).invalidate(); } @Test public void whenCacheEntryIsExhausted_byByteLimit_performsCacheMiss() throws Exception { EncryptionMaterialsRequest request = CacheTestFixtures.createMaterialsRequest(0).toBuilder().setPlaintextSize(100).build(); EncryptionMaterials cacheHitResult = CacheTestFixtures.createMaterialsResult(request); doReturn(CacheTestFixtures.createMaterialsResult(request)) .when(delegate) .getMaterialsForEncrypt(request); EncryptCacheEntry entry = entryFor(cacheHitResult, new UsageStats(1_000_000 - 99, 0)); when(cache.getEntryForEncrypt(any(), any())).thenReturn(entry); EncryptionMaterials returnedResult = cmm.getMaterialsForEncrypt(request); assertNotEquals(cacheHitResult, returnedResult); verify(delegate, times(1)).getMaterialsForEncrypt(any()); verify(cache).putEntryForEncrypt(any(), eq(returnedResult), any(), any()); } @Test public void whenStreaming_cacheMiss_withNoSizeHint_doesNotCache() throws Exception { EncryptionMaterialsRequest request = CacheTestFixtures.createMaterialsRequest(0); EncryptionMaterials result = CacheTestFixtures.createMaterialsResult(request); EncryptCacheEntry entry = setupForCacheMiss(request, result); EncryptionMaterials actualResult = cmm.getMaterialsForEncrypt(request); verifyNoMoreInteractions(cache); } @Test public void whenDecrypting_cacheMiss() throws Exception { DecryptionMaterialsRequest request = CacheTestFixtures.createDecryptRequest(0); DecryptionMaterials result = CacheTestFixtures.createDecryptResult(request); doReturn(result).when(delegate).decryptMaterials(any()); DecryptionMaterials actual = cmm.decryptMaterials(request); assertEquals(result, actual); verify(cache).putEntryForDecrypt(any(), eq(result), any()); } @Test public void whenDecryptCacheMisses_correctHintPassed() throws Exception { DecryptionMaterialsRequest request = CacheTestFixtures.createDecryptRequest(0); DecryptionMaterials result = CacheTestFixtures.createDecryptResult(request); doReturn(result).when(delegate).decryptMaterials(any()); cmm.decryptMaterials(request); ArgumentCaptor<CryptoMaterialsCache.CacheHint> hintCaptor = ArgumentCaptor.forClass(CryptoMaterialsCache.CacheHint.class); verify(cache).putEntryForDecrypt(any(), any(), hintCaptor.capture()); assertEquals(maxAgeMs, hintCaptor.getValue().getMaxAgeMillis()); } @Test public void whenDecrypting_cacheHit() throws Exception { DecryptionMaterialsRequest request = CacheTestFixtures.createDecryptRequest(0); DecryptionMaterials result = CacheTestFixtures.createDecryptResult(request); when(cache.getEntryForDecrypt(any())).thenReturn(new TestDecryptCacheEntry(result)); DecryptionMaterials actual = cmm.decryptMaterials(request); assertEquals(result, actual); verify(cache, never()).putEntryForDecrypt(any(), any(), any()); verify(delegate, never()).decryptMaterials(any()); } @Test public void whenDecrypting_andEntryExpired_cacheMiss() throws Exception { DecryptionMaterialsRequest request = CacheTestFixtures.createDecryptRequest(0); DecryptionMaterials result = CacheTestFixtures.createDecryptResult(request); doReturn(CacheTestFixtures.createDecryptResult(request)).when(delegate).decryptMaterials(any()); TestDecryptCacheEntry entry = new TestDecryptCacheEntry(result); entry.creationTime -= (maxAgeMs + 1); when(cache.getEntryForDecrypt(any())).thenReturn(entry); DecryptionMaterials actual = cmm.decryptMaterials(request); assertNotEquals(result, actual); verify(delegate, times(1)).decryptMaterials(any()); verify(cache, times(1)).putEntryForDecrypt(any(), any(), any()); } @Test public void testBuilderValidation() throws Exception { CachingCryptoMaterialsManager.Builder b = CachingCryptoMaterialsManager.newBuilder(); assertThrows(() -> b.withMaxAge(-1, TimeUnit.MILLISECONDS)); assertThrows(() -> b.withMaxAge(0, TimeUnit.MILLISECONDS)); assertThrows(() -> b.withMessageUseLimit(-1)); assertThrows(() -> b.withMessageUseLimit(1L << 33)); assertThrows(() -> b.withByteUseLimit(-1)); assertThrows(b::build); // backing CMM not set b.withBackingMaterialsManager(delegate); assertThrows(b::build); // cache not set b.withCache(cache); assertThrows(b::build); // max age b.withMaxAge(1, TimeUnit.SECONDS); b.build(); } @Test public void whenBuilderReused_uniquePartitionSet() throws Exception { EncryptionMaterialsRequest request = CacheTestFixtures.createMaterialsRequest(0).toBuilder().setPlaintextSize(1).build(); EncryptionMaterials result = CacheTestFixtures.createMaterialsResult(request); EncryptCacheEntry entry = setupForCacheMiss(request, result); CachingCryptoMaterialsManager.Builder builder = CachingCryptoMaterialsManager.newBuilder() .withCache(cache) .withBackingMaterialsManager(delegate) .withMaxAge(5, TimeUnit.DAYS); builder.build().getMaterialsForEncrypt(request); builder.build().getMaterialsForEncrypt(request); ArgumentCaptor<byte[]> idCaptor = ArgumentCaptor.forClass(byte[].class); verify(cache, times(2)).getEntryForEncrypt(idCaptor.capture(), any()); byte[] firstId = idCaptor.getAllValues().get(0); byte[] secondId = idCaptor.getAllValues().get(1); assertFalse(Arrays.equals(firstId, secondId)); } @Test public void whenMKPPassed_itIsUsed() throws Exception { JceMasterKey key = spy( JceMasterKey.getInstance( new SecretKeySpec(new byte[16], "AES"), "provider", "keyId", "AES/GCM/NoPadding")); CryptoMaterialsManager cmm = CachingCryptoMaterialsManager.newBuilder() .withCache(cache) .withMasterKeyProvider(key) .withMaxAge(5, TimeUnit.DAYS) .build(); cmm.getMaterialsForEncrypt(CacheTestFixtures.createMaterialsRequest(0)); verify(key).generateDataKey(any(), any()); } private EncryptCacheEntry setupForCacheMiss( EncryptionMaterialsRequest request, EncryptionMaterials result) throws Exception { doReturn(result).when(delegate).getMaterialsForEncrypt(request); EncryptCacheEntry entry = entryFor(result, UsageStats.ZERO); doReturn(entry).when(cache).putEntryForEncrypt(any(), eq(result), any(), any()); return entry; } private EncryptCacheEntry entryFor(EncryptionMaterials result, final UsageStats initialUsage) throws Exception { return spy(new TestEncryptCacheEntry(result, initialUsage)); } private static class TestEncryptCacheEntry implements EncryptCacheEntry { private final EncryptionMaterials result; private final UsageStats stats; public TestEncryptCacheEntry(EncryptionMaterials result, UsageStats initialUsage) { this.result = result; stats = initialUsage; } @Override public UsageStats getUsageStats() { return stats; } @Override public long getEntryCreationTime() { return System.currentTimeMillis(); } @Override public EncryptionMaterials getResult() { return result; } @Override public void invalidate() {} } private class TestDecryptCacheEntry implements CryptoMaterialsCache.DecryptCacheEntry { private final DecryptionMaterials result; private long creationTime = System.currentTimeMillis(); public TestDecryptCacheEntry(final DecryptionMaterials result) { this.result = result; } @Override public DecryptionMaterials getResult() { return result; } @Override public void invalidate() {} @Override public long getEntryCreationTime() { return creationTime; } } }
776
0
Create_ds/aws-encryption-sdk-java/src/examples/java/com/amazonaws/crypto
Create_ds/aws-encryption-sdk-java/src/examples/java/com/amazonaws/crypto/examples/FileStreamingExample.java
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package com.amazonaws.crypto.examples; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.security.SecureRandom; import java.util.Collections; import java.util.Map; import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec; import com.amazonaws.encryptionsdk.AwsCrypto; import com.amazonaws.encryptionsdk.CryptoAlgorithm; import com.amazonaws.encryptionsdk.CryptoInputStream; import com.amazonaws.encryptionsdk.MasterKey; import com.amazonaws.encryptionsdk.jce.JceMasterKey; import com.amazonaws.encryptionsdk.CommitmentPolicy; import com.amazonaws.util.IOUtils; /** * <p> * Encrypts and then decrypts a file under a random key. * * <p> * Arguments: * <ol> * <li>Name of file containing plaintext data to encrypt * </ol> * * <p> * This program demonstrates using a standard Java {@link SecretKey} object as a {@link MasterKey} to * encrypt and decrypt streaming data. */ public class FileStreamingExample { private static String srcFile; public static void main(String[] args) throws IOException { srcFile = args[0]; // In this example, we generate a random key. In practice, // you would get a key from an existing store SecretKey cryptoKey = retrieveEncryptionKey(); // Create a JCE master key provider using the random key and an AES-GCM encryption algorithm JceMasterKey masterKey = JceMasterKey.getInstance(cryptoKey, "Example", "RandomKey", "AES/GCM/NoPadding"); // Instantiate the SDK. // This builds the AwsCrypto client with the RequireEncryptRequireDecrypt commitment policy, // which enforces that this client only encrypts using committing algorithm suites and enforces // that this client will only decrypt encrypted messages that were created with a committing algorithm suite. // This is the default commitment policy if you build the client with `AwsCrypto.builder().build()` // or `AwsCrypto.standard()`. // This also chooses to encrypt with an algorithm suite that doesn't include signing for faster decryption, // since this use case assumes that the contexts that encrypt and decrypt are equally trusted. final AwsCrypto crypto = AwsCrypto.builder() .withCommitmentPolicy(CommitmentPolicy.RequireEncryptRequireDecrypt) .withEncryptionAlgorithm(CryptoAlgorithm.ALG_AES_256_GCM_HKDF_SHA512_COMMIT_KEY) .build(); // Create an encryption context to identify this ciphertext Map<String, String> context = Collections.singletonMap("Example", "FileStreaming"); // Because the file might be to large to load into memory, we stream the data, instead of //loading it all at once. FileInputStream in = new FileInputStream(srcFile); CryptoInputStream<JceMasterKey> encryptingStream = crypto.createEncryptingStream(masterKey, in, context); FileOutputStream out = new FileOutputStream(srcFile + ".encrypted"); IOUtils.copy(encryptingStream, out); encryptingStream.close(); out.close(); // Decrypt the file. Verify the encryption context before returning the plaintext. // Since we encrypted using an unsigned algorithm suite, we can use the recommended // createUnsignedMessageDecryptingStream method that only accepts unsigned messages. in = new FileInputStream(srcFile + ".encrypted"); CryptoInputStream<JceMasterKey> decryptingStream = crypto.createUnsignedMessageDecryptingStream(masterKey, in); // Does it contain the expected encryption context? if (!"FileStreaming".equals(decryptingStream.getCryptoResult().getEncryptionContext().get("Example"))) { throw new IllegalStateException("Bad encryption context"); } // Write the plaintext data to disk. out = new FileOutputStream(srcFile + ".decrypted"); IOUtils.copy(decryptingStream, out); decryptingStream.close(); out.close(); } /** * In practice, this key would be saved in a secure location. * For this demo, we generate a new random key for each operation. */ private static SecretKey retrieveEncryptionKey() { SecureRandom rnd = new SecureRandom(); byte[] rawKey = new byte[16]; // 128 bits rnd.nextBytes(rawKey); return new SecretKeySpec(rawKey, "AES"); } }
777
0
Create_ds/aws-encryption-sdk-java/src/examples/java/com/amazonaws/crypto
Create_ds/aws-encryption-sdk-java/src/examples/java/com/amazonaws/crypto/examples/BasicMultiRegionKeyEncryptionExample.java
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package com.amazonaws.crypto.examples; import com.amazonaws.encryptionsdk.AwsCrypto; import com.amazonaws.encryptionsdk.CommitmentPolicy; import com.amazonaws.encryptionsdk.CryptoResult; import com.amazonaws.encryptionsdk.kmssdkv2.AwsKmsMrkAwareMasterKey; import com.amazonaws.encryptionsdk.kmssdkv2.AwsKmsMrkAwareMasterKeyProvider; import java.nio.charset.StandardCharsets; import java.util.Arrays; import java.util.Collections; import java.util.Map; /** * Encrypts and then decrypts data using two related AWS KMS multi-Region keys. In this example, the * AWS KMS multi-Region encrypt key is in a different region than the related AWS KMS multi-Region * decrypt key. * * <p>This example demonstrates how you might use AWS KMS multi-Region keys and the AWS Encryption * SDK client-side library to encrypt data in one region, move or copy it to a different region, and * decrypt the data in the destination region. * * <p>Arguments: Two related AWS KMS multi-Region keys * * <ol> * <li>Encrypt multi-Region key ARN * <li>Decrypt multi-Region key ARN * </ol> * * For help finding the key ARN of your multi-Region key, see "Finding the key ID and ARN" at * https://docs.aws.amazon.com/kms/latest/developerguide/find-cmk-id-arn.html */ public class BasicMultiRegionKeyEncryptionExample { private static final byte[] EXAMPLE_DATA = "Hello World".getBytes(StandardCharsets.UTF_8); public static void main(final String[] args) { final String multiRegionEncryptKey = args[0]; final String multiRegionDecryptKey = args[1]; encryptAndDecrypt(multiRegionEncryptKey, multiRegionDecryptKey); } static void encryptAndDecrypt( final String multiRegionEncryptKey, final String multiRegionDecryptKey ) { // 1. Instantiate the SDK // This builds the AwsCrypto client with // the RequireEncryptRequireDecrypt commitment policy, // which encrypts and decrypts only with committing algorithm suites. // This is the default commitment policy // if you build the client with `AwsCrypto.builder().build()` // or `AwsCrypto.standard()`. final AwsCrypto crypto = AwsCrypto.builder() .withCommitmentPolicy(CommitmentPolicy.RequireEncryptRequireDecrypt) .build(); // 2. Instantiate an AWS KMS multi-Region optimized master key provider // in strict mode using buildStrict(). // This example uses two related multi-Region keys. // In strict mode, the AWS KMS multi-Region optimized master key provider encrypts // and decrypts only by using the key indicated // by key ARN passed to `buildStrict`. // To encrypt with this master key provider, // use any valid AWS KMS key identifier to identify the CMKs. // In strict mode, the decrypt operation requires a key ARN. final AwsKmsMrkAwareMasterKeyProvider encryptingKeyProvider = AwsKmsMrkAwareMasterKeyProvider .builder() .buildStrict(multiRegionEncryptKey); // 3. Create an encryption context // Most encrypted data // should have an associated encryption context // protect its integrity. // This sample uses placeholder values. // For more information see: // blogs.aws.amazon.com/security/post/Tx2LZ6WBJJANTNW/How-to-Protect-the-Integrity-of-Your-Encrypted-Data-by-Using-AWS-Key-Management final Map<String, String> encryptionContext = Collections.singletonMap("ExampleContextKey", "ExampleContextValue"); // 4. Encrypt the data final CryptoResult<byte[], AwsKmsMrkAwareMasterKey> encryptResult = crypto.encryptData(encryptingKeyProvider, EXAMPLE_DATA, encryptionContext); final byte[] ciphertext = encryptResult.getResult(); // 5. Instantiate an AWS KMS multi-Region optimized master key provider // in strict mode using buildStrict(). // This example uses two related multi-Region keys. // Now decrypt with a related multi-Region key in a different region. // In strict mode, the decrypt operation requires a key ARN. final AwsKmsMrkAwareMasterKeyProvider decryptKeyProvider = AwsKmsMrkAwareMasterKeyProvider .builder() .buildStrict(multiRegionDecryptKey); // 6. Decrypt the data with a related multi-Region key in a different region. final CryptoResult<byte[], AwsKmsMrkAwareMasterKey> decryptResult = crypto.decryptData(decryptKeyProvider, ciphertext); // 7. Verify that the encryption context in the result contains // the encryption context supplied to the encryptData method. // Because the ESDK can add values to the encryption context, // don't require that the entire context matches. if (!encryptionContext.entrySet().stream() .allMatch(e -> e.getValue().equals(decryptResult.getEncryptionContext().get(e.getKey())))) { throw new IllegalStateException("Wrong Encryption Context!"); } // 8. Verify that the decrypted plaintext matches the original plaintext assert Arrays.equals(decryptResult.getResult(), EXAMPLE_DATA); } }
778
0
Create_ds/aws-encryption-sdk-java/src/examples/java/com/amazonaws/crypto
Create_ds/aws-encryption-sdk-java/src/examples/java/com/amazonaws/crypto/examples/SetCommitmentPolicyExample.java
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package com.amazonaws.crypto.examples; import java.nio.charset.StandardCharsets; import java.util.Arrays; import java.util.Collections; import java.util.Map; import com.amazonaws.encryptionsdk.AwsCrypto; import com.amazonaws.encryptionsdk.CommitmentPolicy; import com.amazonaws.encryptionsdk.CryptoResult; import com.amazonaws.encryptionsdk.kmssdkv2.KmsMasterKey; import com.amazonaws.encryptionsdk.kmssdkv2.KmsMasterKeyProvider; /** * <p> * Configures a client with a specific commitment policy, then * encrypts and decrypts data using an AWS KMS customer master key. * * This configuration should only be used as part of a migration from version 1.x to 2.x, or for advanced users * with specialized requirements. We recommend that AWS Encryption SDK users use the default commitment policy * whenever possible. * * <p> * Arguments: * <ol> * <li>Key ARN: For help finding the Amazon Resource Name (ARN) of your AWS KMS customer master * key (CMK), see 'Viewing Keys' at http://docs.aws.amazon.com/kms/latest/developerguide/viewing-keys.html * </ol> */ public class SetCommitmentPolicyExample { private static final byte[] EXAMPLE_DATA = "Hello World".getBytes(StandardCharsets.UTF_8); public static void main(final String[] args) { final String keyArn = args[0]; encryptAndDecrypt(keyArn); } static void encryptAndDecrypt(final String keyArn) { // 1. Instantiate the SDK with a specific commitment policy // // `withCommitmentPolicy(CommitmentPolicy)` configures the client with // a commitment policy that dictates whether the client is required to encrypt // using committing algorithms and whether the client must require that the messages // it decrypts were encrypted using committing algorithms. // In this example, we set the commitment policy to `ForbidEncryptAllowDecrypt`. // This policy enforces that the client writes using non-committing algorithms, // and allows decrypting of messages created with committing algorithms. // // If this value is not set, the client is configured to use our recommended default: // `RequireEncryptRequireDecrypt`. // This policy enforces that the client uses committing algorithms // to encrypt and enforces that the client only decrypts messages created with committing algorithms. // We recommend using the default whenever possible. final AwsCrypto crypto = AwsCrypto.builder() .withCommitmentPolicy(CommitmentPolicy.ForbidEncryptAllowDecrypt) .build(); // 2. Instantiate an AWS KMS master key provider in strict mode using buildStrict() // In strict mode, the AWS KMS master key provider encrypts and decrypts only by using the key // indicated by keyArn. // To encrypt and decrypt with this master key provider, use an AWS KMS key ARN to identify the CMKs. // In strict mode, the decrypt operation requires a key ARN. final KmsMasterKeyProvider keyProvider = KmsMasterKeyProvider.builder().buildStrict(keyArn); // 3. Create an encryption context // Most encrypted data should have an associated encryption context // to protect integrity. This sample uses placeholder values. // For more information see: // blogs.aws.amazon.com/security/post/Tx2LZ6WBJJANTNW/How-to-Protect-the-Integrity-of-Your-Encrypted-Data-by-Using-AWS-Key-Management final Map<String, String> encryptionContext = Collections.singletonMap("ExampleContextKey", "ExampleContextValue"); // 4. Encrypt the data final CryptoResult<byte[], KmsMasterKey> encryptResult = crypto.encryptData(keyProvider, EXAMPLE_DATA, encryptionContext); final byte[] ciphertext = encryptResult.getResult(); // 5. Decrypt the data final CryptoResult<byte[], KmsMasterKey> decryptResult = crypto.decryptData(keyProvider, ciphertext); // 6. Verify that the encryption context in the result contains the // encryption context supplied to the encryptData method. Because the // SDK can add values to the encryption context, don't require that // the entire context matches. if (!encryptionContext.entrySet().stream() .allMatch(e -> e.getValue().equals(decryptResult.getEncryptionContext().get(e.getKey())))) { throw new IllegalStateException("Wrong Encryption Context!"); } // 7. Verify that the decrypted plaintext matches the original plaintext assert Arrays.equals(decryptResult.getResult(), EXAMPLE_DATA); } }
779
0
Create_ds/aws-encryption-sdk-java/src/examples/java/com/amazonaws/crypto
Create_ds/aws-encryption-sdk-java/src/examples/java/com/amazonaws/crypto/examples/EscrowedEncryptExample.java
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package com.amazonaws.crypto.examples; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.FileInputStream; import java.io.FileOutputStream; import java.security.GeneralSecurityException; import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.PrivateKey; import java.security.PublicKey; import com.amazonaws.encryptionsdk.AwsCrypto; import com.amazonaws.encryptionsdk.CryptoOutputStream; import com.amazonaws.encryptionsdk.MasterKeyProvider; import com.amazonaws.encryptionsdk.jce.JceMasterKey; import com.amazonaws.encryptionsdk.kmssdkv2.KmsMasterKeyProvider; import com.amazonaws.encryptionsdk.multi.MultipleProviderFactory; import com.amazonaws.encryptionsdk.CommitmentPolicy; import com.amazonaws.util.IOUtils; /** * <p> * Encrypts a file using both AWS KMS and an asymmetric key pair. * * <p> * Arguments: * <ol> * <li>Key ARN: For help finding the Amazon Resource Name (ARN) of your AWS KMS customer master * key (CMK), see 'Viewing Keys' at http://docs.aws.amazon.com/kms/latest/developerguide/viewing-keys.html * * <li>Name of file containing plaintext data to encrypt * </ol> * * You might use AWS Key Management Service (AWS KMS) for most encryption and decryption operations, but * still want the option of decrypting your data offline independently of AWS KMS. This sample * demonstrates one way to do this. * * The sample encrypts data under both an AWS KMS customer master key (CMK) and an "escrowed" RSA key pair * so that either key alone can decrypt it. You might commonly use the AWS KMS CMK for decryption. However, * at any time, you can use the private RSA key to decrypt the ciphertext independent of AWS KMS. * * This sample uses the JCEMasterKey class to generate a RSA public-private key pair * and saves the key pair in memory. In practice, you would store the private key in a secure offline * location, such as an offline HSM, and distribute the public key to your development team. * */ public class EscrowedEncryptExample { private static PublicKey publicEscrowKey; private static PrivateKey privateEscrowKey; public static void main(final String[] args) throws Exception { // This sample generates a new random key for each operation. // In practice, you would distribute the public key and save the private key in secure // storage. generateEscrowKeyPair(); final String kmsArn = args[0]; final String fileName = args[1]; standardEncrypt(kmsArn, fileName); standardDecrypt(kmsArn, fileName); escrowDecrypt(fileName); } private static void standardEncrypt(final String kmsArn, final String fileName) throws Exception { // Encrypt with the KMS CMK and the escrowed public key // 1. Instantiate the SDK // This builds the AwsCrypto client with the RequireEncryptRequireDecrypt commitment policy, // which enforces that this client only encrypts using committing algorithm suites and enforces // that this client will only decrypt encrypted messages that were created with a committing algorithm suite. // This is the default commitment policy if you build the client with `AwsCrypto.builder().build()` // or `AwsCrypto.standard()`. final AwsCrypto crypto = AwsCrypto.builder() .withCommitmentPolicy(CommitmentPolicy.RequireEncryptRequireDecrypt) .build(); // 2. Instantiate an AWS KMS master key provider in strict mode using buildStrict() // // In strict mode, the AWS KMS master key provider encrypts and decrypts only by using the key // indicated by kmsArn. final KmsMasterKeyProvider keyProvider = KmsMasterKeyProvider.builder().buildStrict(kmsArn); // 3. Instantiate a JCE master key provider // Because the user does not have access to the private escrow key, // they pass in "null" for the private key parameter. final JceMasterKey escrowPub = JceMasterKey.getInstance(publicEscrowKey, null, "Escrow", "Escrow", "RSA/ECB/OAEPWithSHA-512AndMGF1Padding"); // 4. Combine the providers into a single master key provider final MasterKeyProvider<?> provider = MultipleProviderFactory.buildMultiProvider(keyProvider, escrowPub); // 5. Encrypt the file // To simplify the code, we omit the encryption context. Production code should always // use an encryption context. For an example, see the other SDK samples. final FileInputStream in = new FileInputStream(fileName); final FileOutputStream out = new FileOutputStream(fileName + ".encrypted"); final CryptoOutputStream<?> encryptingStream = crypto.createEncryptingStream(provider, out); IOUtils.copy(in, encryptingStream); in.close(); encryptingStream.close(); } private static void standardDecrypt(final String kmsArn, final String fileName) throws Exception { // Decrypt with the AWS KMS CMK and the escrow public key. You can use a combined provider, // as shown here, or just the AWS KMS master key provider. // 1. Instantiate the SDK. // This builds the AwsCrypto client with the RequireEncryptRequireDecrypt commitment policy, // which enforces that this client only encrypts using committing algorithm suites and enforces // that this client will only decrypt encrypted messages that were created with a committing algorithm suite. // This is the default commitment policy if you build the client with `AwsCrypto.builder().build()` // or `AwsCrypto.standard()`. final AwsCrypto crypto = AwsCrypto.builder() .withCommitmentPolicy(CommitmentPolicy.RequireEncryptRequireDecrypt) .build(); // 2. Instantiate an AWS KMS master key provider in strict mode using buildStrict() // // In strict mode, the AWS KMS master key provider encrypts and decrypts only by using the key // indicated by kmsArn. final KmsMasterKeyProvider keyProvider = KmsMasterKeyProvider.builder().buildStrict(kmsArn); // 3. Instantiate a JCE master key provider // Because the user does not have access to the private // escrow key, they pass in "null" for the private key parameter. final JceMasterKey escrowPub = JceMasterKey.getInstance(publicEscrowKey, null, "Escrow", "Escrow", "RSA/ECB/OAEPWithSHA-512AndMGF1Padding"); // 4. Combine the providers into a single master key provider final MasterKeyProvider<?> provider = MultipleProviderFactory.buildMultiProvider(keyProvider, escrowPub); // 5. Decrypt the file // To simplify the code, we omit the encryption context. Production code should always // use an encryption context. For an example, see the other SDK samples. final FileInputStream in = new FileInputStream(fileName + ".encrypted"); final FileOutputStream out = new FileOutputStream(fileName + ".decrypted"); // Since we are using a signing algorithm suite, we avoid streaming decryption directly to the output file, // to ensure that the trailing signature is verified before writing any untrusted plaintext to disk. final ByteArrayOutputStream plaintextBuffer = new ByteArrayOutputStream(); final CryptoOutputStream<?> decryptingStream = crypto.createDecryptingStream(provider, plaintextBuffer); IOUtils.copy(in, decryptingStream); in.close(); decryptingStream.close(); final ByteArrayInputStream plaintextReader = new ByteArrayInputStream(plaintextBuffer.toByteArray()); IOUtils.copy(plaintextReader, out); out.close(); } private static void escrowDecrypt(final String fileName) throws Exception { // You can decrypt the stream using only the private key. // This method does not call AWS KMS. // 1. Instantiate the SDK final AwsCrypto crypto = AwsCrypto.standard(); // 2. Instantiate a JCE master key provider // This method call uses the escrowed private key, not null final JceMasterKey escrowPriv = JceMasterKey.getInstance(publicEscrowKey, privateEscrowKey, "Escrow", "Escrow", "RSA/ECB/OAEPWithSHA-512AndMGF1Padding"); // 3. Decrypt the file // To simplify the code, we omit the encryption context. Production code should always // use an encryption context. For an example, see the other SDK samples. final FileInputStream in = new FileInputStream(fileName + ".encrypted"); final FileOutputStream out = new FileOutputStream(fileName + ".deescrowed"); final CryptoOutputStream<?> decryptingStream = crypto.createDecryptingStream(escrowPriv, out); IOUtils.copy(in, decryptingStream); in.close(); decryptingStream.close(); } private static void generateEscrowKeyPair() throws GeneralSecurityException { final KeyPairGenerator kg = KeyPairGenerator.getInstance("RSA"); kg.initialize(4096); // Escrow keys should be very strong final KeyPair keyPair = kg.generateKeyPair(); publicEscrowKey = keyPair.getPublic(); privateEscrowKey = keyPair.getPrivate(); } }
780
0
Create_ds/aws-encryption-sdk-java/src/examples/java/com/amazonaws/crypto
Create_ds/aws-encryption-sdk-java/src/examples/java/com/amazonaws/crypto/examples/SetEncryptionAlgorithmExample.java
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package com.amazonaws.crypto.examples; import java.nio.charset.StandardCharsets; import java.util.Arrays; import java.util.Collections; import java.util.Map; import com.amazonaws.encryptionsdk.AwsCrypto; import com.amazonaws.encryptionsdk.CryptoAlgorithm; import com.amazonaws.encryptionsdk.CryptoResult; import com.amazonaws.encryptionsdk.kmssdkv2.KmsMasterKey; import com.amazonaws.encryptionsdk.kmssdkv2.KmsMasterKeyProvider; /** * <p> * Configures a client with a specific encryption algorithm, then * encrypts and decrypts data using that encryption algorithm and * an AWS KMS customer master key. * * <p> * Arguments: * <ol> * <li>Key ARN: For help finding the Amazon Resource Name (ARN) of your AWS KMS customer master * key (CMK), see 'Viewing Keys' at http://docs.aws.amazon.com/kms/latest/developerguide/viewing-keys.html * </ol> */ public class SetEncryptionAlgorithmExample { private static final byte[] EXAMPLE_DATA = "Hello World".getBytes(StandardCharsets.UTF_8); public static void main(final String[] args) { final String keyArn = args[0]; encryptAndDecrypt(keyArn); } static void encryptAndDecrypt(final String keyArn) { // 1. Instantiate the SDK with the algorithm for encryption // // `withEncryptionAlgorithm(cryptoAlgorithm)` configures the client to encrypt // using a specified encryption algorithm. // This example sets the encryption algorithm to // `CryptoAlgorithm.ALG_AES_256_GCM_HKDF_SHA512_COMMIT_KEY`, // which is an algorithm that does not contain message signing. // // If this value is not set, the client encrypts with the recommended default: // `CryptoAlgorithm.ALG_AES_256_GCM_HKDF_SHA512_COMMIT_KEY_ECDSA_P384`. // We recommend using the default whenever possible. // For a description of our supported algorithms, see https://docs.aws.amazon.com/encryption-sdk/latest/developer-guide/supported-algorithms.html // // You can update the encryption algorithm after constructing the client // by using `crypto.setEncryptionAlgorithm(CryptoAlgorithm)`. final AwsCrypto crypto = AwsCrypto.builder() .withEncryptionAlgorithm(CryptoAlgorithm.ALG_AES_256_GCM_HKDF_SHA512_COMMIT_KEY) .build(); // 2. Instantiate an AWS KMS master key provider in strict mode using buildStrict(). // In strict mode, the AWS KMS master key provider encrypts and decrypts only by using the key // indicated by keyArn. // To encrypt and decrypt with this master key provider, use an AWS KMS key ARN to identify the CMKs. // In strict mode, the decrypt operation requires a key ARN. final KmsMasterKeyProvider keyProvider = KmsMasterKeyProvider.builder().buildStrict(keyArn); // 3. Create an encryption context // Most encrypted data should have an associated encryption context // to protect integrity. This sample uses placeholder values. // For more information see: // blogs.aws.amazon.com/security/post/Tx2LZ6WBJJANTNW/How-to-Protect-the-Integrity-of-Your-Encrypted-Data-by-Using-AWS-Key-Management final Map<String, String> encryptionContext = Collections.singletonMap("ExampleContextKey", "ExampleContextValue"); // 4. Encrypt the data final CryptoResult<byte[], KmsMasterKey> encryptResult = crypto.encryptData(keyProvider, EXAMPLE_DATA, encryptionContext); final byte[] ciphertext = encryptResult.getResult(); // 5. Decrypt the data final CryptoResult<byte[], KmsMasterKey> decryptResult = crypto.decryptData(keyProvider, ciphertext); // 6. Verify that the encryption context in the result contains the // encryption context supplied to the encryptData method. Because the // SDK can add values to the encryption context, don't require that // the entire context matches. if (!encryptionContext.entrySet().stream() .allMatch(e -> e.getValue().equals(decryptResult.getEncryptionContext().get(e.getKey())))) { throw new IllegalStateException("Wrong Encryption Context!"); } // 7. Verify that the decrypted plaintext matches the original plaintext assert Arrays.equals(decryptResult.getResult(), EXAMPLE_DATA); } }
781
0
Create_ds/aws-encryption-sdk-java/src/examples/java/com/amazonaws/crypto
Create_ds/aws-encryption-sdk-java/src/examples/java/com/amazonaws/crypto/examples/MultipleCmkEncryptExample.java
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package com.amazonaws.crypto.examples; import java.nio.charset.StandardCharsets; import java.util.Arrays; import java.util.Collections; import java.util.Map; import com.amazonaws.encryptionsdk.AwsCrypto; import com.amazonaws.encryptionsdk.CryptoResult; import com.amazonaws.encryptionsdk.kmssdkv2.KmsMasterKey; import com.amazonaws.encryptionsdk.kmssdkv2.KmsMasterKeyProvider; import com.amazonaws.encryptionsdk.CommitmentPolicy; /** * <p> * Encrypts data using two different AWS KMS customer master keys, * which can then be decrypted by configuring an AWS KMS master key provider in * strict mode (`buildStrict`) with at least one of either key. * * <p> * Arguments: * <ol> * <li>Key ARN 1: For help finding the Amazon Resource Name (ARN) of your AWS KMS customer master * key (CMK), see 'Viewing Keys' at http://docs.aws.amazon.com/kms/latest/developerguide/viewing-keys.html * <li>Key ARN 2: For help finding the Amazon Resource Name (ARN) of your AWS KMS customer master * key (CMK), see 'Viewing Keys' at http://docs.aws.amazon.com/kms/latest/developerguide/viewing-keys.html * </ol> */ public class MultipleCmkEncryptExample { private static final byte[] EXAMPLE_DATA = "Hello World".getBytes(StandardCharsets.UTF_8); public static void main(final String[] args) { final String keyArn1 = args[0]; final String keyArn2 = args[1]; encryptAndDecrypt(keyArn1, keyArn2); } static void encryptAndDecrypt(final String keyArn1, final String keyArn2) { // Instantiate the SDK. // This builds the AwsCrypto client with the RequireEncryptRequireDecrypt commitment policy, // which enforces that this client only encrypts using committing algorithm suites and enforces // that this client will only decrypt encrypted messages that were created with a committing algorithm suite. // This is the default commitment policy if you build the client with `AwsCrypto.builder().build()` // or `AwsCrypto.standard()`. final AwsCrypto crypto = AwsCrypto.builder() .withCommitmentPolicy(CommitmentPolicy.RequireEncryptRequireDecrypt) .build(); // 2. Instantiate an AWS KMS master key provider to encrypt with // In strict mode (`buildStrict`), the AWS KMS master key provider encrypts and decrypts only by using the // keys indicated by keyArn1 and keyArn2 final KmsMasterKeyProvider multiCmkKeyProvider = KmsMasterKeyProvider.builder().buildStrict(keyArn1, keyArn2); // 3. Instantiate an AWS KMS master key providers that are configured with keyArn1 and keyArn2 // separately. // These will be used later in this example to show that the encrypted messages created by multiCmkKeyProvider // can be decrypted by AWS KMS master key providers that are configured with either CMK. final KmsMasterKeyProvider singleCMKKeyProvider1 = KmsMasterKeyProvider.builder().buildStrict(keyArn1); final KmsMasterKeyProvider singleCMKKeyProvider2 = KmsMasterKeyProvider.builder().buildStrict(keyArn2); // 4. Create an encryption context // Most encrypted data should have an associated encryption context // to protect integrity. This sample uses placeholder values. // For more information see: // blogs.aws.amazon.com/security/post/Tx2LZ6WBJJANTNW/How-to-Protect-the-Integrity-of-Your-Encrypted-Data-by-Using-AWS-Key-Management final Map<String, String> encryptionContext = Collections.singletonMap("ExampleContextKey", "ExampleContextValue"); // 5. Encrypt the data final CryptoResult<byte[], KmsMasterKey> encryptResult = crypto.encryptData(multiCmkKeyProvider, EXAMPLE_DATA, encryptionContext); final byte[] ciphertext = encryptResult.getResult(); // 6. Decrypt the data with the AWS KMS master key provider that originally encrypted this data final CryptoResult<byte[], KmsMasterKey> decryptResult = crypto.decryptData(multiCmkKeyProvider, ciphertext); // 7. Verify that the encryption context in the result contains the // encryption context supplied to the encryptData method. Because the // SDK can add values to the encryption context, don't require that // the entire context matches. if (!encryptionContext.entrySet().stream() .allMatch(e -> e.getValue().equals(decryptResult.getEncryptionContext().get(e.getKey())))) { throw new IllegalStateException("Wrong Encryption Context!"); } // 8. Verify that the decrypted plaintext matches the original plaintext assert Arrays.equals(decryptResult.getResult(), EXAMPLE_DATA); // 9. Now show that the encrypted message can also be decrypted by AWS KMS master key providers // configured with either CMK. final CryptoResult<byte[], KmsMasterKey> singleCmkDecryptResult1 = crypto.decryptData(singleCMKKeyProvider1, ciphertext); final CryptoResult<byte[], KmsMasterKey> singleCmkDecryptResult2 = crypto.decryptData(singleCMKKeyProvider2, ciphertext); // 10. Verify that the encryption context in the result contains the // encryption context supplied to the encryptData method for both decryptions if (!encryptionContext.entrySet().stream() .allMatch(e -> e.getValue().equals(singleCmkDecryptResult1.getEncryptionContext().get(e.getKey())))) { throw new IllegalStateException("Wrong Encryption Context!"); } if (!encryptionContext.entrySet().stream() .allMatch(e -> e.getValue().equals(singleCmkDecryptResult2.getEncryptionContext().get(e.getKey())))) { throw new IllegalStateException("Wrong Encryption Context!"); } // 11. Verify that the decrypted plaintext matches the original plaintext for each decryption assert Arrays.equals(singleCmkDecryptResult1.getResult(), EXAMPLE_DATA); assert Arrays.equals(singleCmkDecryptResult2.getResult(), EXAMPLE_DATA); } }
782
0
Create_ds/aws-encryption-sdk-java/src/examples/java/com/amazonaws/crypto
Create_ds/aws-encryption-sdk-java/src/examples/java/com/amazonaws/crypto/examples/BasicEncryptionExample.java
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package com.amazonaws.crypto.examples; import java.nio.charset.StandardCharsets; import java.util.Arrays; import java.util.Collections; import java.util.Map; import com.amazonaws.encryptionsdk.AwsCrypto; import com.amazonaws.encryptionsdk.CryptoResult; import com.amazonaws.encryptionsdk.kmssdkv2.KmsMasterKey; import com.amazonaws.encryptionsdk.kmssdkv2.KmsMasterKeyProvider; import com.amazonaws.encryptionsdk.CommitmentPolicy; /** * <p> * Encrypts and then decrypts data using an AWS KMS customer master key. * * <p> * Arguments: * <ol> * <li>Key ARN: For help finding the Amazon Resource Name (ARN) of your AWS KMS customer master * key (CMK), see 'Viewing Keys' at http://docs.aws.amazon.com/kms/latest/developerguide/viewing-keys.html * </ol> */ public class BasicEncryptionExample { private static final byte[] EXAMPLE_DATA = "Hello World".getBytes(StandardCharsets.UTF_8); public static void main(final String[] args) { final String keyArn = args[0]; encryptAndDecrypt(keyArn); } static void encryptAndDecrypt(final String keyArn) { // 1. Instantiate the SDK // This builds the AwsCrypto client with the RequireEncryptRequireDecrypt commitment policy, // which enforces that this client only encrypts using committing algorithm suites and enforces // that this client will only decrypt encrypted messages that were created with a committing algorithm suite. // This is the default commitment policy if you build the client with `AwsCrypto.builder().build()` // or `AwsCrypto.standard()`. final AwsCrypto crypto = AwsCrypto.builder() .withCommitmentPolicy(CommitmentPolicy.RequireEncryptRequireDecrypt) .build(); // 2. Instantiate an AWS KMS master key provider in strict mode using buildStrict(). // In strict mode, the AWS KMS master key provider encrypts and decrypts only by using the key // indicated by keyArn. // To encrypt and decrypt with this master key provider, use an AWS KMS key ARN to identify the CMKs. // In strict mode, the decrypt operation requires a key ARN. final KmsMasterKeyProvider keyProvider = KmsMasterKeyProvider.builder().buildStrict(keyArn); // 3. Create an encryption context // Most encrypted data should have an associated encryption context // to protect integrity. This sample uses placeholder values. // For more information see: // blogs.aws.amazon.com/security/post/Tx2LZ6WBJJANTNW/How-to-Protect-the-Integrity-of-Your-Encrypted-Data-by-Using-AWS-Key-Management final Map<String, String> encryptionContext = Collections.singletonMap("ExampleContextKey", "ExampleContextValue"); // 4. Encrypt the data final CryptoResult<byte[], KmsMasterKey> encryptResult = crypto.encryptData(keyProvider, EXAMPLE_DATA, encryptionContext); final byte[] ciphertext = encryptResult.getResult(); // 5. Decrypt the data final CryptoResult<byte[], KmsMasterKey> decryptResult = crypto.decryptData(keyProvider, ciphertext); // 6. Verify that the encryption context in the result contains the // encryption context supplied to the encryptData method. Because the // SDK can add values to the encryption context, don't require that // the entire context matches. if (!encryptionContext.entrySet().stream() .allMatch(e -> e.getValue().equals(decryptResult.getEncryptionContext().get(e.getKey())))) { throw new IllegalStateException("Wrong Encryption Context!"); } // 7. Verify that the decrypted plaintext matches the original plaintext assert Arrays.equals(decryptResult.getResult(), EXAMPLE_DATA); } }
783
0
Create_ds/aws-encryption-sdk-java/src/examples/java/com/amazonaws/crypto
Create_ds/aws-encryption-sdk-java/src/examples/java/com/amazonaws/crypto/examples/DiscoveryMultiRegionDecryptionExample.java
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package com.amazonaws.crypto.examples; import com.amazonaws.encryptionsdk.AwsCrypto; import com.amazonaws.encryptionsdk.CommitmentPolicy; import com.amazonaws.encryptionsdk.CryptoResult; import com.amazonaws.encryptionsdk.kms.DiscoveryFilter; import com.amazonaws.encryptionsdk.kmssdkv2.AwsKmsMrkAwareMasterKey; import com.amazonaws.encryptionsdk.kmssdkv2.AwsKmsMrkAwareMasterKeyProvider; import java.nio.charset.StandardCharsets; import java.util.Arrays; import java.util.Collections; import java.util.Map; import software.amazon.awssdk.regions.Region; /** * <p> * Encrypts and then decrypts data using an AWS KMS customer master key in discovery mode. * Discovery mode is useful when you can't or don't want to specify a CMK on decrypt. * <p> * Arguments: * <ol> * <li>Key Name: A key identifier for the AWS KMS customer master key (CMK). For example, * a key ARN or a key alias. * For details, see "Key identifiers" at https://docs.aws.amazon.com/kms/latest/developerguide/concepts.html#key-id * <li>Partition: The partition of the AWS KMS customer master key, which is usually "aws." * A partition is a group of regions. The partition is the second element in the key ARN, e.g. "arn" in "aws:aws: ..." * For details, see: https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html#arns-syntax * <li>Account ID: The identifier for the account of the AWS KMS customer master key. * </ol> */ public class DiscoveryMultiRegionDecryptionExample { private static final byte[] EXAMPLE_DATA = "Hello World".getBytes(StandardCharsets.UTF_8); public static void main(final String[] args) { final String keyName = args[0]; final String partition = args[1]; final String accountId = args[2]; final Region discoveryMrkRegion = Region.of(args[3]); encryptAndDecrypt(keyName, partition, accountId, discoveryMrkRegion); } static void encryptAndDecrypt( final String keyName, final String partition, final String accountId, final Region discoveryMrkRegion ) { // 1. Instantiate the SDK // This builds the AwsCrypto client with // the RequireEncryptRequireDecrypt commitment policy, // which decrypts only with committing algorithm suites. // This is the default commitment policy // if you build the client with `AwsCrypto.builder().build()` // or `AwsCrypto.standard()`. final AwsCrypto crypto = AwsCrypto.builder() .withCommitmentPolicy(CommitmentPolicy.RequireEncryptRequireDecrypt) .build(); // 2. Instantiate an AWS KMS multi region optimized master key provider // in strict mode using buildStrict(). // In this example we are using // two related multi region keys. // we will encrypt with // the encrypting in the encrypting region first. // In strict mode, // the AWS KMS multi region optimized master key provider encrypts // and decrypts only by using the key indicated // by key arn passed to `buildStrict`. // To encrypt with this master key provider, // use an AWS KMS key ARN to identify the CMKs. // In strict mode, the decrypt operation requires a key ARN. final AwsKmsMrkAwareMasterKeyProvider encryptingKeyProvider = AwsKmsMrkAwareMasterKeyProvider .builder() .buildStrict(keyName); // 3. Create an encryption context // Most encrypted data // should have an associated encryption context // to protect integrity. // This sample uses placeholder values. // For more information see: // blogs.aws.amazon.com/security/post/Tx2LZ6WBJJANTNW/How-to-Protect-the-Integrity-of-Your-Encrypted-Data-by-Using-AWS-Key-Management final Map<String, String> encryptionContext = Collections.singletonMap("ExampleContextKey", "ExampleContextValue"); // 4. Encrypt the data final CryptoResult<byte[], AwsKmsMrkAwareMasterKey> encryptResult = crypto .encryptData(encryptingKeyProvider, EXAMPLE_DATA, encryptionContext); final byte[] ciphertext = encryptResult.getResult(); // 5. Instantiate a discovery filter for decrypting. // This filter limits the CMKs that the ESDK can use // to those in the specified AWS partition and accounts. // This filter is not required for discovery mode, // but is a best practice. final DiscoveryFilter discoveryFilter = new DiscoveryFilter(partition, accountId); // 6. Instantiate an AWS KMS multi region optimized master key provider // for decryption in discovery mode (`buildDiscovery`) // with a Discovery Mrk Region // and with a discovery filter. // // In discovery mode, the AWS KMS multi region optimized master key provider // attempts to decrypt only by using AWS KMS keys indicated in the encrypted message. // By configuring the master key provider with a Discovery Mrk Region, // this master key provider will only attempt to decrypt // with AWS KMS multi-Region keys in the Discovery Mrk Region. // If the Discovery Mrk Region is not configured, // it is limited to the Region configured for the AWS SDK. final AwsKmsMrkAwareMasterKeyProvider decryptingKeyProvider = AwsKmsMrkAwareMasterKeyProvider .builder() .discoveryMrkRegion(discoveryMrkRegion) .buildDiscovery(discoveryFilter); // 7. Decrypt the data // Even though the message was encrypted with an AWS KMS key in one region // the master key provider will attempt to decrypt with the discoveryMrkRegion. final CryptoResult<byte[], AwsKmsMrkAwareMasterKey> decryptResult = crypto .decryptData(decryptingKeyProvider, ciphertext); // 8. Verify that the encryption context in the result contains // the encryption context supplied to the encryptData method. // Because the ESDK can add values to the encryption context, // don't require that the entire context matches. if (!encryptionContext.entrySet().stream() .allMatch(e -> e.getValue().equals(decryptResult.getEncryptionContext().get(e.getKey())))) { throw new IllegalStateException("Wrong Encryption Context!"); } // 9. Verify that the decrypted plaintext matches the original plaintext assert Arrays.equals(decryptResult.getResult(), EXAMPLE_DATA); } }
784
0
Create_ds/aws-encryption-sdk-java/src/examples/java/com/amazonaws/crypto
Create_ds/aws-encryption-sdk-java/src/examples/java/com/amazonaws/crypto/examples/SimpleDataKeyCachingExample.java
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package com.amazonaws.crypto.examples; import java.nio.charset.StandardCharsets; import java.util.Collections; import java.util.Map; import java.util.concurrent.TimeUnit; import com.amazonaws.encryptionsdk.AwsCrypto; import com.amazonaws.encryptionsdk.CryptoMaterialsManager; import com.amazonaws.encryptionsdk.MasterKeyProvider; import com.amazonaws.encryptionsdk.caching.CachingCryptoMaterialsManager; import com.amazonaws.encryptionsdk.caching.CryptoMaterialsCache; import com.amazonaws.encryptionsdk.caching.LocalCryptoMaterialsCache; import com.amazonaws.encryptionsdk.kmssdkv2.KmsMasterKey; import com.amazonaws.encryptionsdk.kmssdkv2.KmsMasterKeyProvider; /** * <p> * Encrypts a string using an AWS KMS customer master key (CMK) and data key caching * * <p> * Arguments: * <ol> * <li>KMS CMK ARN: To find the Amazon Resource Name of your AWS KMS customer master key (CMK), * see 'Viewing Keys' at http://docs.aws.amazon.com/kms/latest/developerguide/viewing-keys.html * <li>Max entry age: Maximum time (in seconds) that a cached entry can be used * <li>Cache capacity: Maximum number of entries in the cache * </ol> */ public class SimpleDataKeyCachingExample { /* * Security thresholds * Max entry age is required. * Max messages (and max bytes) per data key are optional */ private static final int MAX_ENTRY_MSGS = 100; public static byte[] encryptWithCaching(String kmsCmkArn, int maxEntryAge, int cacheCapacity) { // Plaintext data to be encrypted byte[] myData = "My plaintext data".getBytes(StandardCharsets.UTF_8); // Encryption context // Most encrypted data should have an associated encryption context // to protect integrity. This sample uses placeholder values. // For more information see: // blogs.aws.amazon.com/security/post/Tx2LZ6WBJJANTNW/How-to-Protect-the-Integrity-of-Your-Encrypted-Data-by-Using-AWS-Key-Management final Map<String, String> encryptionContext = Collections.singletonMap("purpose", "test"); // Create a master key provider MasterKeyProvider<KmsMasterKey> keyProvider = KmsMasterKeyProvider.builder().buildStrict(kmsCmkArn); // Create a cache CryptoMaterialsCache cache = new LocalCryptoMaterialsCache(cacheCapacity); // Create a caching CMM CryptoMaterialsManager cachingCmm = CachingCryptoMaterialsManager.newBuilder().withMasterKeyProvider(keyProvider) .withCache(cache) .withMaxAge(maxEntryAge, TimeUnit.SECONDS) .withMessageUseLimit(MAX_ENTRY_MSGS) .build(); // When the call to encryptData specifies a caching CMM, // the encryption operation uses the data key cache final AwsCrypto encryptionSdk = AwsCrypto.standard(); return encryptionSdk.encryptData(cachingCmm, myData, encryptionContext).getResult(); } }
785
0
Create_ds/aws-encryption-sdk-java/src/examples/java/com/amazonaws/crypto
Create_ds/aws-encryption-sdk-java/src/examples/java/com/amazonaws/crypto/examples/RestrictRegionExample.java
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package com.amazonaws.crypto.examples; import java.nio.charset.StandardCharsets; import java.util.Arrays; import java.util.Collections; import java.util.Map; import com.amazonaws.encryptionsdk.AwsCrypto; import com.amazonaws.encryptionsdk.CryptoResult; import com.amazonaws.encryptionsdk.exception.AwsCryptoException; import com.amazonaws.encryptionsdk.kmssdkv2.KmsMasterKey; import com.amazonaws.encryptionsdk.kmssdkv2.KmsMasterKeyProvider; import com.amazonaws.encryptionsdk.CommitmentPolicy; import com.amazonaws.encryptionsdk.kms.DiscoveryFilter; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.kms.KmsClient; /** * <p> * Encrypts and then decrypts data using an AWS KMS customer master key in discovery mode. * Discovery mode is useful when you use an alias to identify a CMK when encrypting and the * underlying key ARN might vary in each AWS Region. * <p> * Arguments: * <ol> * <li>Key Name: An identifier for the AWS KMS customer master key (CMK) to use. For example, * a key ARN or an alias name. * See https://docs.aws.amazon.com/kms/latest/developerguide/concepts.html#key-id for * a description of AWS KMS key identifiers. * <li>Partition: The partition that the AWS KMS customer master key belongs in. This is usually "aws". * <li>Account ID: The identifier for the account that the AWS KMS customer master key belongs in. * <li>Region Name: The region that the AWS KMS customer master key belongs in. * </ol> */ public class RestrictRegionExample { private static final byte[] EXAMPLE_DATA = "Hello World".getBytes(StandardCharsets.UTF_8); public static void main(final String[] args) { final String keyName = args[0]; final String partition = args[1]; final String accountId = args[2]; final Region region = Region.of(args[3]); encryptAndDecrypt(keyName, partition, accountId, region); } static void encryptAndDecrypt(final String keyName, final String partition, final String accountId, final Region region) { // Instantiate the SDK. // This builds the AwsCrypto client with the RequireEncryptRequireDecrypt commitment policy, // which enforces that this client only encrypts using committing algorithm suites and enforces // that this client will only decrypt encrypted messages that were created with a committing algorithm suite. // This is the default commitment policy if you build the client with `AwsCrypto.builder().build()` // or `AwsCrypto.standard()`. final AwsCrypto crypto = AwsCrypto.builder() .withCommitmentPolicy(CommitmentPolicy.RequireEncryptRequireDecrypt) .build(); // 2. Instantiate the AWS KMS client for the desired region final KmsClient kmsClient = KmsClient.builder().region(region).build(); // 3. Instantiate an AWS KMS master key provider for encryption. // // In strict mode (`buildStrict`), the AWS KMS master key provider will only encrypt and decrypt using the key // indicated by keyName. // This example uses an AWS KMS CMK ARN. Because this master key provider will // only be used for encryption, an AWS KMS CMK alias could also be used. final KmsMasterKeyProvider encryptingKeyProvider = KmsMasterKeyProvider.builder().buildStrict(keyName); // 4. Create an encryption context // // Most encrypted data should have an associated encryption context // to protect integrity. This sample uses placeholder values. // // For more information see: // blogs.aws.amazon.com/security/post/Tx2LZ6WBJJANTNW/How-to-Protect-the-Integrity-of-Your-Encrypted-Data-by-Using-AWS-Key-Management final Map<String, String> encryptionContext = Collections.singletonMap("ExampleContextKey", "ExampleContextValue"); // 5. Encrypt the data final CryptoResult<byte[], KmsMasterKey> encryptResult = crypto.encryptData(encryptingKeyProvider, EXAMPLE_DATA, encryptionContext); final byte[] ciphertext = encryptResult.getResult(); // 6. Instantiate a Discovery Filter to restrict which AWS KMS CMKs an AWS KMS master key provider // is allowed to attempt decryption with to a particular partition and account. // Configuring a Discovery AWS KMS master key provider with a Discovery Filter is a best practice, // but is not required to restrict the CMKs by region. final DiscoveryFilter discoveryFilter = new DiscoveryFilter(partition, accountId); // 7. Instantiate an AWS KMS master key provider for decryption in discovery mode (`buildDiscovery`) with a // custom client factory for the desired region. // // The custom client factory will only attempt to decrypt using CMKs from the desired region, // and skip any CMK not in the desired region. // If the encrypted message contains no CMKs within the desired region, decryption fails. // // In discovery mode, the AWS KMS master key provider will attempt to decrypt using AWS KMS ARNs // indicated in the encrypted message. // This example also configures the AWS KMS master key provider with a Discovery Filter to limit // the attempted AWS KMS CMKs to a particular partition and account. final KmsMasterKeyProvider decryptingKeyProvider = KmsMasterKeyProvider.builder() .customRegionalClientSupplier(cmkRegion -> { if(cmkRegion.equals(region)) { // return the previously built AWS KMS client so that we do // not create a new client on every decrypt call. return kmsClient; } throw new AwsCryptoException("Only " + region.id() + " is supported"); }) .buildDiscovery(discoveryFilter); // 8. Decrypt the data final CryptoResult<byte[], KmsMasterKey> decryptResult = crypto.decryptData(decryptingKeyProvider, ciphertext); // 9. Verify that the encryption context in the result contains the // encryption context supplied to the encryptData method. Because the // SDK can add values to the encryption context, don't require that // the entire context matches. if (!encryptionContext.entrySet().stream() .allMatch(e -> e.getValue().equals(decryptResult.getEncryptionContext().get(e.getKey())))) { throw new IllegalStateException("Wrong Encryption Context!"); } // 10. Verify that the decrypted plaintext matches the original plaintext assert Arrays.equals(decryptResult.getResult(), EXAMPLE_DATA); } }
786
0
Create_ds/aws-encryption-sdk-java/src/examples/java/com/amazonaws/crypto
Create_ds/aws-encryption-sdk-java/src/examples/java/com/amazonaws/crypto/examples/DiscoveryDecryptionExample.java
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package com.amazonaws.crypto.examples; import java.nio.charset.StandardCharsets; import java.util.Arrays; import java.util.Collections; import java.util.Map; import com.amazonaws.encryptionsdk.AwsCrypto; import com.amazonaws.encryptionsdk.CryptoResult; import com.amazonaws.encryptionsdk.kmssdkv2.KmsMasterKey; import com.amazonaws.encryptionsdk.kmssdkv2.KmsMasterKeyProvider; import com.amazonaws.encryptionsdk.CommitmentPolicy; import com.amazonaws.encryptionsdk.kms.DiscoveryFilter; /** * <p> * Encrypts and then decrypts data using an AWS KMS customer master key in discovery mode. * Discovery mode is useful when you use an alias to identify a CMK when encrypting and the * underlying key ARN might vary in each AWS Region. * <p> * Arguments: * <ol> * <li>Key Name: An identifier for the AWS KMS customer master key (CMK) to use. For example, * a key ARN or a key alias. * For help finding the Amazon Resource Name (ARN) of your AWS KMS customer master * key (CMK), see 'Viewing Keys' at http://docs.aws.amazon.com/kms/latest/developerguide/viewing-keys.html * <li>Partition: The partition of the AWS KMS customer master key, which is usually "aws." * A partition is a group of regions. The partition is the second element in the key ARN, e.g. "arn" in "aws:aws: ..." * <li>Account ID: The identifier for the account of the AWS KMS customer master key. * </ol> */ public class DiscoveryDecryptionExample { private static final byte[] EXAMPLE_DATA = "Hello World".getBytes(StandardCharsets.UTF_8); public static void main(final String[] args) { final String keyName = args[0]; final String partition = args[1]; final String accountId = args[2]; encryptAndDecrypt(keyName, partition, accountId); } static void encryptAndDecrypt(final String keyName, final String partition, final String accountId) { // 1. Instantiate the SDK // This builds the AwsCrypto client with the RequireEncryptRequireDecrypt commitment policy, // which enforces that this client only encrypts using committing algorithm suites and enforces // that this client will only decrypt encrypted messages that were created with a committing algorithm suite. // This is the default commitment policy if you build the client with `AwsCrypto.builder().build()` // or `AwsCrypto.standard()`. final AwsCrypto crypto = AwsCrypto.builder() .withCommitmentPolicy(CommitmentPolicy.RequireEncryptRequireDecrypt) .build(); // 2. Instantiate an AWS KMS master key provider for encryption. // // In strict mode (`buildStrict`), the AWS KMS master key provider encrypts and decrypts only by using the key // indicated by keyName. final KmsMasterKeyProvider encryptingKeyProvider = KmsMasterKeyProvider.builder().buildStrict(keyName); // 3. Create an encryption context // // Most encrypted data should have an associated encryption context // to protect integrity. This sample uses placeholder values. // // For more information see: // blogs.aws.amazon.com/security/post/Tx2LZ6WBJJANTNW/How-to-Protect-the-Integrity-of-Your-Encrypted-Data-by-Using-AWS-Key-Management final Map<String, String> encryptionContext = Collections.singletonMap("ExampleContextKey", "ExampleContextValue"); // 4. Encrypt the data final CryptoResult<byte[], KmsMasterKey> encryptResult = crypto.encryptData(encryptingKeyProvider, EXAMPLE_DATA, encryptionContext); final byte[] ciphertext = encryptResult.getResult(); // 5. Instantiate a discovery filter for decrypting. This filter restricts what AWS KMS CMKs the // AWS KMS master key provider can use to those in a particular AWS partition and account. // You can create a similar filter with one partition and multiple AWS accounts. // This example only configures the filter with one account, but more may be specified // as long as they exist within the same partition. // This filter is not required for Discovery mode, but is a best practice. final DiscoveryFilter discoveryFilter = new DiscoveryFilter(partition, accountId); // 6. Instantiate an AWS KMS master key provider for decryption in discovery mode (`buildDiscovery`) with a // Discovery Filter. // // In discovery mode, the AWS KMS master key provider attempts to decrypt only by using AWS KMS ARNs // indicated in the encrypted message. // By configuring the master key provider with a Discovery Filter, this master key provider // attempts to decrypt AWS KMS CMKs only in the configured partition and accounts. final KmsMasterKeyProvider decryptingKeyProvider = KmsMasterKeyProvider.builder().buildDiscovery(discoveryFilter); // 7. Decrypt the data final CryptoResult<byte[], KmsMasterKey> decryptResult = crypto.decryptData(decryptingKeyProvider, ciphertext); // 8. Verify that the encryption context in the result contains the // encryption context supplied to the encryptData method. Because the // SDK can add values to the encryption context, don't require that // the entire context matches. if (!encryptionContext.entrySet().stream() .allMatch(e -> e.getValue().equals(decryptResult.getEncryptionContext().get(e.getKey())))) { throw new IllegalStateException("Wrong Encryption Context!"); } // 9. Verify that the decrypted plaintext matches the original plaintext assert Arrays.equals(decryptResult.getResult(), EXAMPLE_DATA); } }
787
0
Create_ds/aws-encryption-sdk-java/src/main/java/com/amazonaws
Create_ds/aws-encryption-sdk-java/src/main/java/com/amazonaws/encryptionsdk/CryptoOutputStream.java
/* * Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except * in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.amazonaws.encryptionsdk; import com.amazonaws.encryptionsdk.caching.CachingCryptoMaterialsManager; import com.amazonaws.encryptionsdk.exception.BadCiphertextException; import com.amazonaws.encryptionsdk.internal.MessageCryptoHandler; import com.amazonaws.encryptionsdk.internal.Utils; import java.io.IOException; import java.io.OutputStream; import java.util.List; /** * A CryptoOutputStream is a subclass of java.io.OutputStream. It performs cryptographic * transformation of the bytes passing through it. * * <p>The CryptoOutputStream wraps a provided OutputStream object and performs cryptographic * transformation of the bytes written to it. The transformed bytes are then written to the wrapped * OutputStream. It uses the cryptography handler provided during construction to invoke methods * that perform the cryptographic transformations. * * <p>In short, writing to the CryptoOutputStream results in those bytes being cryptographically * transformed and written to the wrapped OutputStream. * * <p>For example, if the crypto handler provides methods for decryption, the CryptoOutputStream * will decrypt the provided ciphertext bytes and write the plaintext bytes to the wrapped * OutputStream. * * <p>This class adheres strictly to the semantics, especially the failure semantics, of its * ancestor class java.io.OutputStream. This class overrides all the methods specified in its * ancestor class. * * <p>To instantiate an instance of this class, please see {@link AwsCrypto}. * * @param <K> The type of {@link MasterKey}s used to manipulate the data. */ public class CryptoOutputStream<K extends MasterKey<K>> extends OutputStream { private final OutputStream outputStream_; private final MessageCryptoHandler cryptoHandler_; /** * Constructs a CryptoOutputStream that wraps the provided OutputStream object. It performs * cryptographic transformation of the bytes written to it using the methods provided in the * provided CryptoHandler implementation. The transformed bytes are then written to the wrapped * OutputStream. * * @param outputStream the outputStream object to be wrapped. * @param cryptoHandler the cryptoHandler implementation that provides the methods to use in * performing cryptographic transformation of the bytes written to this stream. */ CryptoOutputStream(final OutputStream outputStream, final MessageCryptoHandler cryptoHandler) { outputStream_ = Utils.assertNonNull(outputStream, "outputStream"); cryptoHandler_ = Utils.assertNonNull(cryptoHandler, "cryptoHandler"); } /** * {@inheritDoc} * * @throws BadCiphertextException This is thrown only during decryption if b contains invalid or * corrupt ciphertext. */ @Override public void write(final byte[] b) throws IllegalArgumentException, IOException, BadCiphertextException { if (b == null) { throw new IllegalArgumentException("b cannot be null"); } write(b, 0, b.length); } /** * {@inheritDoc} * * @throws BadCiphertextException This is thrown only during decryption if b contains invalid or * corrupt ciphertext. */ @Override public void write(final byte[] b, final int off, final int len) throws IllegalArgumentException, IOException, BadCiphertextException { if (b == null) { throw new IllegalArgumentException("b cannot be null"); } if (len < 0 || off < 0) { throw new IllegalArgumentException( String.format("Invalid values for offset: %d and length: %d", off, len)); } final int outLen = cryptoHandler_.estimatePartialOutputSize(len); final byte[] outBytes = new byte[outLen]; int bytesWritten = cryptoHandler_.processBytes(b, off, len, outBytes, 0).getBytesWritten(); if (bytesWritten > 0) { outputStream_.write(outBytes, 0, bytesWritten); } } /** * {@inheritDoc} * * @throws BadCiphertextException This is thrown only during decryption if b contains invalid or * corrupt ciphertext. */ @Override public void write(int b) throws IOException, BadCiphertextException { byte[] bArray = new byte[1]; bArray[0] = (byte) b; write(bArray, 0, 1); } /** * Closes this output stream and releases any system resources associated with this stream. * * <p>This method writes any final bytes to the underlying stream that complete the cyptographic * transformation of the written bytes. It also calls close on the wrapped OutputStream. * * @throws IOException if an I/O error occurs. * @throws BadCiphertextException This is thrown only during decryption if b contains invalid or * corrupt ciphertext. */ @Override public void close() throws IOException, BadCiphertextException { final byte[] outBytes = new byte[cryptoHandler_.estimateFinalOutputSize()]; int finalLen = cryptoHandler_.doFinal(outBytes, 0); outputStream_.write(outBytes, 0, finalLen); outputStream_.close(); } /** * Sets an upper bound on the size of the input data. This method should be called before writing * any data to the stream. If this method is not called prior to writing data, performance may be * reduced (notably, it will not be possible to cache data keys when encrypting). * * <p>Among other things, this size is used to enforce limits configured on the {@link * CachingCryptoMaterialsManager}. * * <p>If the size set here is exceeded, an exception will be thrown, and the encyption or * decryption will fail. * * <p>If this method is called multiple times, the smallest bound will be used. * * @param size Maximum input size. */ public void setMaxInputLength(long size) { cryptoHandler_.setMaxInputLength(size); } /** Returns the result of the cryptographic operations including associate metadata. */ public CryptoResult<CryptoOutputStream<K>, K> getCryptoResult() { if (!cryptoHandler_.getHeaders().isComplete()) { throw new IllegalStateException("Ciphertext headers not yet written to stream"); } //noinspection unchecked return new CryptoResult<>( this, (List<K>) cryptoHandler_.getMasterKeys(), cryptoHandler_.getHeaders()); } }
788
0
Create_ds/aws-encryption-sdk-java/src/main/java/com/amazonaws
Create_ds/aws-encryption-sdk-java/src/main/java/com/amazonaws/encryptionsdk/CryptoMaterialsManager.java
package com.amazonaws.encryptionsdk; import com.amazonaws.encryptionsdk.model.DecryptionMaterials; import com.amazonaws.encryptionsdk.model.DecryptionMaterialsRequest; import com.amazonaws.encryptionsdk.model.EncryptionMaterials; import com.amazonaws.encryptionsdk.model.EncryptionMaterialsRequest; /** * The crypto materials manager is responsible for preparing the cryptographic materials needed to * process a request - notably, preparing the cleartext data key and (if applicable) trailing * signature keys on both encrypt and decrypt. */ public interface CryptoMaterialsManager { /** * Prepares materials for an encrypt request. The resulting materials result must have a cleartext * data key and (if applicable for the crypto algorithm in use) a trailing signature key. * * <p>The encryption context returned may be different from the one passed in the materials * request, and will be serialized (in cleartext) within the encrypted message. * * @see EncryptionMaterials * @see EncryptionMaterialsRequest * @param request * @return */ EncryptionMaterials getMaterialsForEncrypt(EncryptionMaterialsRequest request); DecryptionMaterials decryptMaterials(DecryptionMaterialsRequest request); }
789
0
Create_ds/aws-encryption-sdk-java/src/main/java/com/amazonaws
Create_ds/aws-encryption-sdk-java/src/main/java/com/amazonaws/encryptionsdk/MasterKey.java
/* * Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except * in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.amazonaws.encryptionsdk; import com.amazonaws.encryptionsdk.exception.NoSuchMasterKeyException; import com.amazonaws.encryptionsdk.exception.UnsupportedProviderException; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Objects; /** * Represents the cryptographic key used to protect the {@link DataKey} (which, in turn, protects * the data). * * <p>All MasterKeys extend {@link MasterKeyProvider} because they are all capable of providing * exactly themselves. This simplifies implementation when only a single {@link MasterKey} is used * and/or expected. * * @param <K> the concrete type of the {@link MasterKey} */ public abstract class MasterKey<K extends MasterKey<K>> extends MasterKeyProvider<K> { public abstract String getProviderId(); /** Equivalent to calling {@link #getProviderId()}. */ @Override public String getDefaultProviderId() { return getProviderId(); } public abstract String getKeyId(); /** * Generates a new {@link DataKey} which is protected by this {@link MasterKey} for use with * {@code algorithm} and associated with the provided {@code encryptionContext}. */ public abstract DataKey<K> generateDataKey( CryptoAlgorithm algorithm, Map<String, String> encryptionContext); /** * Returns a new copy of the provided {@code dataKey} which is protected by this {@link MasterKey} * for use with {@code algorithm} and associated with the provided {@code encryptionContext}. */ public abstract DataKey<K> encryptDataKey( CryptoAlgorithm algorithm, Map<String, String> encryptionContext, DataKey<?> dataKey); /** Returns {@code true} if and only if {@code provider} equals {@link #getProviderId()}. */ @Override public boolean canProvide(final String provider) { return getProviderId().equals(provider); } /** * Returns {@code this} if {@code provider} and {@code keyId} match {@code this}. Otherwise, * throws an appropriate exception. */ @SuppressWarnings("unchecked") @Override public K getMasterKey(final String provider, final String keyId) throws UnsupportedProviderException, NoSuchMasterKeyException { if (!canProvide(provider)) { throw new UnsupportedProviderException( "MasterKeys can only provide themselves. Requested " + buildName(provider, keyId) + " but only " + toString() + " is available"); } if (!getKeyId().equals(keyId)) { throw new NoSuchMasterKeyException( "MasterKeys can only provide themselves. Requested " + buildName(provider, keyId) + " but only " + toString() + " is available"); } return (K) this; } @Override public String toString() { return buildName(getProviderId(), getKeyId()); } /** Returns a list of length {@code 1} containing {@code this}. */ @SuppressWarnings("unchecked") @Override public List<K> getMasterKeysForEncryption(final MasterKeyRequest request) { return (List<K>) Collections.singletonList(this); } private static String buildName(final String provider, final String keyId) { return String.format("%s://%s", provider, keyId); } /** * Two {@link MasterKey}s are equal if they are instances of the <em>exact same class</em> and * their values for {@code keyId}, {@code providerId}, and {@code defaultProviderId} are equal. */ @Override public boolean equals(final Object obj) { if (obj == null) { return false; } if (this == obj) { return true; } if (!obj.getClass().equals(getClass())) { return false; } final MasterKey<?> mk = (MasterKey<?>) obj; return Objects.equals(getKeyId(), mk.getKeyId()) && Objects.equals(getProviderId(), mk.getProviderId()) && Objects.equals(getDefaultProviderId(), mk.getDefaultProviderId()); } @Override public int hashCode() { return Objects.hash(getKeyId(), getProviderId(), getDefaultProviderId()); } }
790
0
Create_ds/aws-encryption-sdk-java/src/main/java/com/amazonaws
Create_ds/aws-encryption-sdk-java/src/main/java/com/amazonaws/encryptionsdk/DataKey.java
/* * Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except * in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.amazonaws.encryptionsdk; import javax.crypto.SecretKey; /** * Represents both the cleartext and encrypted bytes of a data key. * * @param <M> the type of {@link MasterKey} used to protect this {@code DataKey}. */ public class DataKey<M extends MasterKey<M>> implements EncryptedDataKey { private final byte[] providerInformation_; private final byte[] encryptedDataKey_; private final SecretKey key_; private final M masterKey_; public DataKey( final SecretKey key, final byte[] encryptedDataKey, final byte[] providerInformation, final M masterKey) { super(); key_ = key; encryptedDataKey_ = encryptedDataKey.clone(); providerInformation_ = providerInformation.clone(); masterKey_ = masterKey; } /** Returns the cleartext bytes of the data key. */ public SecretKey getKey() { return key_; } @Override public String getProviderId() { return masterKey_.getProviderId(); } @Override public byte[] getProviderInformation() { return providerInformation_.clone(); } @Override public byte[] getEncryptedDataKey() { return encryptedDataKey_.clone(); } /** Returns the {@link MasterKey} used to encrypt this {@link DataKey}. */ public M getMasterKey() { return masterKey_; } }
791
0
Create_ds/aws-encryption-sdk-java/src/main/java/com/amazonaws
Create_ds/aws-encryption-sdk-java/src/main/java/com/amazonaws/encryptionsdk/ParsedCiphertext.java
/* * Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except * in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.amazonaws.encryptionsdk; import com.amazonaws.encryptionsdk.exception.BadCiphertextException; import com.amazonaws.encryptionsdk.internal.Utils; import com.amazonaws.encryptionsdk.model.CiphertextHeaders; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; /** * Exposes header information of ciphertexts to make it easier to inspect the algorithm, keys, and * encryption context prior to decryption. * * <p>Please note that the class does <em>not</em> make defensive copies. */ public class ParsedCiphertext extends CiphertextHeaders { private final byte[] ciphertext_; private final int offset_; /** * Parses {@code ciphertext}. Please note that this does <em>not</em> make a defensive copy of * {@code ciphertext} and that any changes made to the backing array will be reflected here as * well. * * @param ciphertext The ciphertext to parse * @param maxEncryptedDataKeys The maximum number of encrypted data keys to parse. Zero indicates * no maximum. */ public ParsedCiphertext(final byte[] ciphertext, final int maxEncryptedDataKeys) { ciphertext_ = Utils.assertNonNull(ciphertext, "ciphertext"); offset_ = deserialize(ciphertext_, 0, maxEncryptedDataKeys); if (!this.isComplete()) { throw new BadCiphertextException("Incomplete ciphertext."); } } /** * Parses {@code ciphertext} without enforcing a max EDK count. Please note that this does * <em>not</em> make a defensive copy of {@code ciphertext} and that any changes made to the * backing array will be reflected here as well. */ public ParsedCiphertext(final byte[] ciphertext) { this(ciphertext, CiphertextHeaders.NO_MAX_ENCRYPTED_DATA_KEYS); } /** * Returns the raw ciphertext backing this object. This is <em>not</em> a defensive copy and so * must not be modified by callers. */ @SuppressFBWarnings("EI_EXPOSE_REP") public byte[] getCiphertext() { return ciphertext_; } /** The offset at which the first non-header byte in {@code ciphertext} is located. */ public int getOffset() { return offset_; } }
792
0
Create_ds/aws-encryption-sdk-java/src/main/java/com/amazonaws
Create_ds/aws-encryption-sdk-java/src/main/java/com/amazonaws/encryptionsdk/MasterKeyProvider.java
/* * Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except * in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.amazonaws.encryptionsdk; import com.amazonaws.encryptionsdk.exception.AwsCryptoException; import com.amazonaws.encryptionsdk.exception.CannotUnwrapDataKeyException; import com.amazonaws.encryptionsdk.exception.NoSuchMasterKeyException; import com.amazonaws.encryptionsdk.exception.UnsupportedProviderException; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Map; /** * Represents the logic necessary to select and construct {@link MasterKey}s for encrypting and * decrypting messages. This is an abstract class. * * @param <K> the type of {@link MasterKey} returned by this provider */ public abstract class MasterKeyProvider<K extends MasterKey<K>> { /** ProviderId used by this instance when no other is specified. */ public abstract String getDefaultProviderId(); /** * Returns true if this MasterKeyProvider can provide keys from the specified @{code provider}. * * @param provider * @return */ public boolean canProvide(final String provider) { return getDefaultProviderId().equals(provider); } /** * Equivalent to calling {@link #getMasterKey(String, String)} using {@link * #getDefaultProviderId()} as the provider. */ public K getMasterKey(final String keyId) throws UnsupportedProviderException, NoSuchMasterKeyException { return getMasterKey(getDefaultProviderId(), keyId); } /** * Returns the specified {@link MasterKey} if possible. * * @param provider * @param keyId * @return * @throws UnsupportedProviderException if this object cannot return {@link MasterKey}s associated * with the given provider * @throws NoSuchMasterKeyException if this object cannot find (and thus construct) the {@link * MasterKey} associated with {@code keyId} */ public abstract K getMasterKey(String provider, String keyId) throws UnsupportedProviderException, NoSuchMasterKeyException; /** * Returns all {@link MasterKey}s which should be used to protect the plaintext described by * {@code request}. */ public abstract List<K> getMasterKeysForEncryption(MasterKeyRequest request); /** * Iterates through {@code encryptedDataKeys} and returns the first one which can be successfully * decrypted. * * @return a DataKey if one can be decrypted, otherwise returns {@code null} * @throws UnsupportedProviderException if the {@code encryptedDataKey} is associated with an * unsupported provider * @throws CannotUnwrapDataKeyException if the {@code encryptedDataKey} cannot be decrypted */ public abstract DataKey<K> decryptDataKey( CryptoAlgorithm algorithm, Collection<? extends EncryptedDataKey> encryptedDataKeys, Map<String, String> encryptionContext) throws UnsupportedProviderException, AwsCryptoException; protected AwsCryptoException buildCannotDecryptDksException() { return buildCannotDecryptDksException(Collections.<Throwable>emptyList()); } protected AwsCryptoException buildCannotDecryptDksException(Throwable t) { return buildCannotDecryptDksException(Collections.singletonList(t)); } protected AwsCryptoException buildCannotDecryptDksException(List<? extends Throwable> t) { if (t == null || t.isEmpty()) { return new CannotUnwrapDataKeyException("Unable to decrypt any data keys"); } else { final CannotUnwrapDataKeyException ex = new CannotUnwrapDataKeyException("Unable to decrypt any data keys", t.get(0)); for (final Throwable e : t) { ex.addSuppressed(e); } return ex; } } }
793
0
Create_ds/aws-encryption-sdk-java/src/main/java/com/amazonaws
Create_ds/aws-encryption-sdk-java/src/main/java/com/amazonaws/encryptionsdk/CryptoInputStream.java
/* * Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except * in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.amazonaws.encryptionsdk; import static com.amazonaws.encryptionsdk.internal.Utils.assertNonNull; import com.amazonaws.encryptionsdk.caching.CachingCryptoMaterialsManager; import com.amazonaws.encryptionsdk.exception.BadCiphertextException; import com.amazonaws.encryptionsdk.internal.MessageCryptoHandler; import com.amazonaws.encryptionsdk.internal.Utils; import java.io.IOException; import java.io.InputStream; import java.util.List; /** * A CryptoInputStream is a subclass of java.io.InputStream. It performs cryptographic * transformation of the bytes passing through it. * * <p>The CryptoInputStream wraps a provided InputStream object and performs cryptographic * transformation of the bytes read from the wrapped InputStream. It uses the cryptography handler * provided during construction to invoke methods that perform the cryptographic transformations. * * <p>In short, reading from the CryptoInputStream returns bytes that are the cryptographic * transformations of the bytes read from the wrapped InputStream. * * <p>For example, if the cryptography handler provides methods for decryption, the * CryptoInputStream will read ciphertext bytes from the wrapped InputStream, decrypt, and return * them as plaintext bytes. * * <p>This class adheres strictly to the semantics, especially the failure semantics, of its * ancestor class java.io.InputStream. This class overrides all the methods specified in its * ancestor class. * * <p>To instantiate an instance of this class, please see {@link AwsCrypto}. * * @param <K> The type of {@link MasterKey}s used to manipulate the data. */ public class CryptoInputStream<K extends MasterKey<K>> extends InputStream { private static final int MAX_READ_LEN = 4096; private byte[] outBytes_ = new byte[0]; private int outStart_; private int outEnd_; private final InputStream inputStream_; private final MessageCryptoHandler cryptoHandler_; private boolean hasFinalCalled_; private boolean hasProcessBytesCalled_; /** * Constructs a CryptoInputStream that wraps the provided InputStream object. It performs * cryptographic transformation of the bytes read from the wrapped InputStream using the methods * provided in the provided CryptoHandler implementation. * * @param inputStream the inputStream object to be wrapped. * @param cryptoHandler the cryptoHandler implementation that provides the methods to use in * performing cryptographic transformation of the bytes read from the inputStream. */ CryptoInputStream(final InputStream inputStream, final MessageCryptoHandler cryptoHandler) { inputStream_ = Utils.assertNonNull(inputStream, "inputStream"); cryptoHandler_ = Utils.assertNonNull(cryptoHandler, "cryptoHandler"); } /** * Fill the output bytes by reading from the wrapped InputStream and processing it through the * crypto handler. * * @return the number of bytes processed and returned by the crypto handler. */ private int fillOutBytes() throws IOException, BadCiphertextException { final byte[] inputStreamBytes = new byte[MAX_READ_LEN]; final int readLen = inputStream_.read(inputStreamBytes); outStart_ = 0; int processedLen; if (readLen < 0) { // Mark end of stream until doFinal returns something. processedLen = -1; if (!hasFinalCalled_) { int outOffset = 0; int outLen = 0; // Handle the case where processBytes() was never called before. // This happens with an empty file where the end of stream is // reached on the first read attempt. In this case, // processBytes() must be called so the header bytes are written // during encryption. if (!hasProcessBytesCalled_) { outBytes_ = new byte[cryptoHandler_.estimateOutputSize(0)]; outLen += cryptoHandler_ .processBytes(inputStreamBytes, 0, 0, outBytes_, outOffset) .getBytesWritten(); outOffset += outLen; } else { outBytes_ = new byte[cryptoHandler_.estimateFinalOutputSize()]; } // Get final bytes. outLen += cryptoHandler_.doFinal(outBytes_, outOffset); processedLen = outLen; hasFinalCalled_ = true; } } else { // process the read bytes. outBytes_ = new byte[cryptoHandler_.estimatePartialOutputSize(readLen)]; processedLen = cryptoHandler_ .processBytes(inputStreamBytes, 0, readLen, outBytes_, outStart_) .getBytesWritten(); hasProcessBytesCalled_ = true; } outEnd_ = processedLen; return processedLen; } /** * {@inheritDoc} * * @throws BadCiphertextException This is thrown only during decryption if b contains invalid or * corrupt ciphertext. */ @Override public int read(final byte[] b, final int off, final int len) throws IllegalArgumentException, IOException, BadCiphertextException { assertNonNull(b, "b"); if (len < 0 || off < 0) { throw new IllegalArgumentException( String.format("Invalid values for offset: %d and length: %d", off, len)); } if (b.length == 0 || len == 0) { return 0; } // fill the output bytes if there aren't any left to return. if ((outEnd_ - outStart_) <= 0) { int newBytesLen = 0; // Block until a byte is read or end of stream in the underlying // stream is reached. while (newBytesLen == 0) { newBytesLen = fillOutBytes(); } if (newBytesLen < 0) { return -1; } } final int copyLen = Math.min((outEnd_ - outStart_), len); System.arraycopy(outBytes_, outStart_, b, off, copyLen); outStart_ += copyLen; return copyLen; } /** * {@inheritDoc} * * @throws BadCiphertextException This is thrown only during decryption if b contains invalid or * corrupt ciphertext. */ @Override public int read(final byte[] b) throws IllegalArgumentException, IOException, BadCiphertextException { return read(b, 0, b.length); } /** * {@inheritDoc} * * @throws BadCiphertextException if b contains invalid or corrupt ciphertext. This is thrown only * during decryption. */ @Override public int read() throws IOException, BadCiphertextException { final byte[] bArray = new byte[1]; int result = 0; while (result == 0) { result = read(bArray, 0, 1); } if (result > 0) { return (bArray[0] & 0xFF); } else { return result; } } @Override public void close() throws IOException { inputStream_.close(); } /** Returns metadata associated with the performed cryptographic operation. */ @Override public int available() throws IOException { return (outBytes_.length + inputStream_.available()); } /** * Sets an upper bound on the size of the input data. This method should be called before reading * any data from the stream. If this method is not called prior to reading any data, performance * may be reduced (notably, it will not be possible to cache data keys when encrypting). * * <p>Among other things, this size is used to enforce limits configured on the {@link * CachingCryptoMaterialsManager}. * * <p>If the input size set here is exceeded, an exception will be thrown, and the encyption or * decryption will fail. * * <p>If this method is called multiple times, the smallest bound will be used. * * @param size Maximum input size. */ public void setMaxInputLength(long size) { cryptoHandler_.setMaxInputLength(size); } /** * Returns the result of the cryptographic operations including associate metadata. * * @throws IOException * @throws BadCiphertextException */ public CryptoResult<CryptoInputStream<K>, K> getCryptoResult() throws BadCiphertextException, IOException { while (!cryptoHandler_.getHeaders().isComplete()) { if (fillOutBytes() == -1) { throw new BadCiphertextException("No CiphertextHeaders found."); } } //noinspection unchecked return new CryptoResult<>( this, (List<K>) cryptoHandler_.getMasterKeys(), cryptoHandler_.getHeaders()); } }
794
0
Create_ds/aws-encryption-sdk-java/src/main/java/com/amazonaws
Create_ds/aws-encryption-sdk-java/src/main/java/com/amazonaws/encryptionsdk/CryptoResult.java
/* * Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except * in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.amazonaws.encryptionsdk; import com.amazonaws.encryptionsdk.model.CiphertextHeaders; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; /** * Represents the result of an operation by {@link AwsCrypto}. It not only captures the {@code * result} of the operation but also additional metadata such as the {@code encryptionContext}, * {@code algorithm}, {@link MasterKey}(s), and any other information captured in the {@link * CiphertextHeaders}. * * @param <T> the type of the underlying {@code result} * @param <K> the type of the {@link MasterKey}s used in production of this result */ public class CryptoResult<T, K extends MasterKey<K>> { private final T result_; private final List<K> masterKeys_; private final Map<String, String> encryptionContext_; private final CiphertextHeaders headers_; /** Note, does not make a defensive copy of any of the data. */ CryptoResult(final T result, final List<K> masterKeys, final CiphertextHeaders headers) { result_ = result; masterKeys_ = Collections.unmodifiableList(masterKeys); headers_ = headers; encryptionContext_ = headers_.getEncryptionContextMap(); } /** * The actual result of the cryptographic operation. This is not a defensive copy and callers * should not modify it. * * @return */ public T getResult() { return result_; } /** * Returns all relevant {@link MasterKey}s. In the case of encryption, returns all {@code * MasterKey}s used to protect the ciphertext. In the case of decryption, returns just the {@code * MasterKey} used to decrypt the ciphertext. * * @return */ public List<K> getMasterKeys() { return masterKeys_; } /** Convenience method for retrieving the keyIds in the results from {@link #getMasterKeys()}. */ public List<String> getMasterKeyIds() { final List<String> result = new ArrayList<>(masterKeys_.size()); for (final MasterKey<K> mk : masterKeys_) { result.add(mk.getKeyId()); } return result; } public Map<String, String> getEncryptionContext() { return encryptionContext_; } /** Convenience method equivalent to {@link #getHeaders()}.{@code getCryptoAlgoId()}. */ public CryptoAlgorithm getCryptoAlgorithm() { return headers_.getCryptoAlgoId(); } public CiphertextHeaders getHeaders() { return headers_; } }
795
0
Create_ds/aws-encryption-sdk-java/src/main/java/com/amazonaws
Create_ds/aws-encryption-sdk-java/src/main/java/com/amazonaws/encryptionsdk/MasterKeyRequest.java
/* * Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except * in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.amazonaws.encryptionsdk; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import java.util.Collections; import java.util.HashMap; import java.util.Map; /** * Contains information which {@link MasterKeyProvider}s can use to select which {@link MasterKey}s * to use to protect a given plaintext. This class is immutable. */ public final class MasterKeyRequest { private final Map<String, String> encryptionContext_; private final boolean isStreaming_; private final byte[] plaintext_; private final long size_; private MasterKeyRequest( final Map<String, String> encryptionContext, final boolean isStreaming, final byte[] plaintext, final long size) { encryptionContext_ = encryptionContext; isStreaming_ = isStreaming; plaintext_ = plaintext; size_ = size; } public Map<String, String> getEncryptionContext() { return encryptionContext_; } public boolean isStreaming() { return isStreaming_; } /** The plaintext, if available, to be protected by this request. Otherwise, {@code null}. */ public byte[] getPlaintext() { return plaintext_ != null ? plaintext_.clone() : null; } /** The size of the plaintext, if available. Otherwise {@code -1}. */ public long getSize() { return size_; } public static Builder newBuilder() { return new Builder(); } public static final class Builder { private Map<String, String> encryptionContext_ = new HashMap<>(); private boolean isStreaming_ = false; private byte[] plaintext_ = null; private long size_ = -1; public Map<String, String> getEncryptionContext() { return encryptionContext_; } public Builder setEncryptionContext(final Map<String, String> encryptionContext) { encryptionContext_ = encryptionContext; return this; } public boolean isStreaming() { return isStreaming_; } public Builder setStreaming(final boolean isStreaming) { isStreaming_ = isStreaming; return this; } /** * Please note that this does not make a defensive copy of the plaintext and so any * modifications made to the backing array will be reflected in this Builder. */ @SuppressFBWarnings("EI_EXPOSE_REP") public byte[] getPlaintext() { return plaintext_; } /** * Please note that this does not make a defensive copy of the plaintext and so any * modifications made to the backing array will be reflected in this Builder. */ @SuppressFBWarnings("EI_EXPOSE_REP") public Builder setPlaintext(final byte[] plaintext) { if (size_ != -1) { throw new IllegalStateException( "The plaintext may only be set if the size has not been explicitly set"); } plaintext_ = plaintext; return this; } public Builder setSize(final long size) { if (plaintext_ != null) { throw new IllegalStateException( "Size may only explicitly set when the plaintext is not set"); } size_ = size; return this; } public long getSize() { return size_; } public MasterKeyRequest build() { return new MasterKeyRequest( Collections.unmodifiableMap(new HashMap<>(encryptionContext_)), isStreaming_, plaintext_, plaintext_ != null ? plaintext_.length : size_); } } }
796
0
Create_ds/aws-encryption-sdk-java/src/main/java/com/amazonaws
Create_ds/aws-encryption-sdk-java/src/main/java/com/amazonaws/encryptionsdk/DefaultCryptoMaterialsManager.java
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package com.amazonaws.encryptionsdk; import static com.amazonaws.encryptionsdk.internal.Utils.assertNonNull; import com.amazonaws.encryptionsdk.exception.AwsCryptoException; import com.amazonaws.encryptionsdk.exception.CannotUnwrapDataKeyException; import com.amazonaws.encryptionsdk.internal.Constants; import com.amazonaws.encryptionsdk.internal.TrailingSignatureAlgorithm; import com.amazonaws.encryptionsdk.internal.Utils; import com.amazonaws.encryptionsdk.model.DecryptionMaterials; import com.amazonaws.encryptionsdk.model.DecryptionMaterialsRequest; import com.amazonaws.encryptionsdk.model.EncryptionMaterials; import com.amazonaws.encryptionsdk.model.EncryptionMaterialsRequest; import com.amazonaws.encryptionsdk.model.KeyBlob; import java.security.GeneralSecurityException; import java.security.KeyPair; import java.security.PublicKey; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * The default implementation of {@link CryptoMaterialsManager}, used implicitly when passing a * {@link MasterKeyProvider} to methods in {@link AwsCrypto}. * * <p>This default implementation delegates to a specific {@link MasterKeyProvider} specified at * construction time. It also handles generating trailing signature keys when needed, placing them * in the encryption context (and extracting them at decrypt time). */ public class DefaultCryptoMaterialsManager implements CryptoMaterialsManager { private final MasterKeyProvider<?> mkp; private final CryptoAlgorithm DEFAULT_CRYPTO_ALGORITHM = CryptoAlgorithm.ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA384_ECDSA_P384; /** @param mkp The master key provider to delegate to */ public DefaultCryptoMaterialsManager(MasterKeyProvider<?> mkp) { Utils.assertNonNull(mkp, "mkp"); this.mkp = mkp; } @Override public EncryptionMaterials getMaterialsForEncrypt(EncryptionMaterialsRequest request) { Map<String, String> context = request.getContext(); CryptoAlgorithm algo = request.getRequestedAlgorithm(); CommitmentPolicy commitmentPolicy = request.getCommitmentPolicy(); // Set default according to commitment policy if (algo == null && commitmentPolicy == CommitmentPolicy.ForbidEncryptAllowDecrypt) { algo = CryptoAlgorithm.ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA384_ECDSA_P384; } else if (algo == null) { algo = CryptoAlgorithm.ALG_AES_256_GCM_HKDF_SHA512_COMMIT_KEY_ECDSA_P384; } KeyPair trailingKeys = null; if (algo.getTrailingSignatureLength() > 0) { try { trailingKeys = generateTrailingSigKeyPair(algo); if (context.containsKey(Constants.EC_PUBLIC_KEY_FIELD)) { throw new IllegalArgumentException( "EncryptionContext contains reserved field " + Constants.EC_PUBLIC_KEY_FIELD); } // make mutable context = new HashMap<>(context); context.put(Constants.EC_PUBLIC_KEY_FIELD, serializeTrailingKeyForEc(algo, trailingKeys)); } catch (final GeneralSecurityException ex) { throw new AwsCryptoException(ex); } } final MasterKeyRequest.Builder mkRequestBuilder = MasterKeyRequest.newBuilder(); mkRequestBuilder.setEncryptionContext(context); mkRequestBuilder.setStreaming(request.getPlaintextSize() == -1); if (request.getPlaintext() != null) { mkRequestBuilder.setPlaintext(request.getPlaintext()); } else { mkRequestBuilder.setSize(request.getPlaintextSize()); } @SuppressWarnings("unchecked") final List<MasterKey> mks = (List<MasterKey>) assertNonNull(mkp, "provider").getMasterKeysForEncryption(mkRequestBuilder.build()); if (mks.isEmpty()) { throw new IllegalArgumentException("No master keys provided"); } DataKey<?> dataKey = mks.get(0).generateDataKey(algo, context); List<KeyBlob> keyBlobs = new ArrayList<>(mks.size()); keyBlobs.add(new KeyBlob(dataKey)); for (int i = 1; i < mks.size(); i++) { //noinspection unchecked keyBlobs.add(new KeyBlob(mks.get(i).encryptDataKey(algo, context, dataKey))); } //noinspection unchecked return EncryptionMaterials.newBuilder() .setAlgorithm(algo) .setCleartextDataKey(dataKey.getKey()) .setEncryptedDataKeys(keyBlobs) .setEncryptionContext(context) .setTrailingSignatureKey(trailingKeys == null ? null : trailingKeys.getPrivate()) .setMasterKeys(mks) .build(); } @Override public DecryptionMaterials decryptMaterials(DecryptionMaterialsRequest request) { DataKey<?> dataKey = mkp.decryptDataKey( request.getAlgorithm(), request.getEncryptedDataKeys(), request.getEncryptionContext()); if (dataKey == null) { throw new CannotUnwrapDataKeyException("Could not decrypt any data keys"); } PublicKey pubKey = null; if (request.getAlgorithm().getTrailingSignatureLength() > 0) { try { String serializedPubKey = request.getEncryptionContext().get(Constants.EC_PUBLIC_KEY_FIELD); if (serializedPubKey == null) { throw new AwsCryptoException("Missing trailing signature public key"); } pubKey = deserializeTrailingKeyFromEc(request.getAlgorithm(), serializedPubKey); } catch (final IllegalStateException ex) { throw new AwsCryptoException(ex); } } else if (request.getEncryptionContext().containsKey(Constants.EC_PUBLIC_KEY_FIELD)) { throw new AwsCryptoException("Trailing signature public key found for non-signed algorithm"); } return DecryptionMaterials.newBuilder() .setDataKey(dataKey) .setTrailingSignatureKey(pubKey) .build(); } private PublicKey deserializeTrailingKeyFromEc(CryptoAlgorithm algo, String pubKey) { return TrailingSignatureAlgorithm.forCryptoAlgorithm(algo).deserializePublicKey(pubKey); } private static String serializeTrailingKeyForEc(CryptoAlgorithm algo, KeyPair trailingKeys) { return TrailingSignatureAlgorithm.forCryptoAlgorithm(algo) .serializePublicKey(trailingKeys.getPublic()); } private static KeyPair generateTrailingSigKeyPair(CryptoAlgorithm algo) throws GeneralSecurityException { return TrailingSignatureAlgorithm.forCryptoAlgorithm(algo).generateKey(); } }
797
0
Create_ds/aws-encryption-sdk-java/src/main/java/com/amazonaws
Create_ds/aws-encryption-sdk-java/src/main/java/com/amazonaws/encryptionsdk/EncryptedDataKey.java
/* * Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except * in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.amazonaws.encryptionsdk; // @ model import java.util.Arrays; // @ model import java.nio.charset.StandardCharsets; // @ nullable_by_default public interface EncryptedDataKey { // @// An EncryptedDataKey object abstractly contains 3 pieces of data. // @// These are represented by 3 byte arrays: // @ model public instance byte[] providerId; // @ model public instance byte[] providerInformation; // @ model public instance byte[] encryptedDataKey; // @// The fields of an EncryptedDataKey may be populated via deserialization. The // @// Encryption SDK design allows the deserialization routine to be called repeatedly, // @// each call trying to fill in information that for some reason was not possible // @// with the previous call. In some such "intermediate" states, the deserialization // @// is incomplete in a way that other methods don't expect. Therefore, those methods // @// should not be called in these incomplete intermediate states. The model field // @// isDeserializing is true in those incomplete intermediate states, and it is used // @// in method specifications. // @ public model instance boolean isDeserializing; // @// There are some complications surrounding the representations of strings versus // @// byte arrays. The serialized form in message headers is always a sequence of // @// bytes, but the EncryptedDataKey interface (and some other methods) // @// expose the provider ID as if it were a string. Conversions (using UTF-8) // @// between byte arrays and strings (which in Java use UTF-16) are not bijections. // @// For example, both "\u003f".getBytes() and "\ud800".getBytes() yield a 1-byte // @// array containing [0x3f], and calling `new String(..., StandardCharsets.UTF_8)` // @// with either the 1-byte array [0x80] or the 3-byte array [0xef,0xbf,0xbd] yields // @// the string "\ufffd". Therefore, all we can say about these conversions // @// is that a given byte[]-String pair satisfies a conversion relation. // @// // @// The model functions "ba2s" and "s2ba" are used to specify the conversions // @// between byte arrays and strings: /*@ public normal_behavior @ requires s != null; @ ensures \result != null; @ function @ public model static byte[] s2ba(String s) { @ return s.getBytes(StandardCharsets.UTF_8); @ } @*/ /*@ public normal_behavior @ requires ba != null; @ ensures \result != null; @ function @ public model static String ba2s(byte[] ba) { @ return new String(ba, StandardCharsets.UTF_8); @ } @*/ // @// The "ba2s" and "s2ba" are given function bodies above, but the verification // @// does not rely on these function bodies directly. Instead, the code (in KeyBlob) // @// uses "assume" statements when it necessary to connect these functions with // @// copies of their bodies that appear in the code. This is a limitation of JML. // @// // @// One of the properties that holds of "s2ba(s)" is that its result depends not // @// on the particular String reference "s" being passed in, but only the contents // @// of the string referenced by "s". This property is captured in the following // @// lemma: /*@ public normal_behavior @ requires s != null && t != null && String.equals(s, t); @ ensures Arrays.equalArrays(s2ba(s), s2ba(t)); @ pure @ public model static void lemma_s2ba_depends_only_string_contents_only(String s, String t); @*/ // @// // @// As a specification convenience, the model function "ba2s2ba" uses the two // @// model functions above to convert from a byte array to a String and then back // @// to a byte array. As mentioned above, this does not always result in a byte // @// array with the original contents. The "assume" statements about the conversion // @// functions need to be careful not to assume too much. /*@ public normal_behavior @ requires ba != null; @ ensures \result == s2ba(ba2s(ba)); @ function @ public model static byte[] ba2s2ba(byte[] ba) { @ return s2ba(ba2s(ba)); @ } @*/ // @// Here follows 3 methods that access the abstract values of interface properties. // @// Something to note about these methods is that each one requires the property // @// requested to be known to be non-null. For example, "getProviderId" is only allowed // @// to be called when "providerId" is known to be non-null. // @ public normal_behavior // @ requires providerId != null; // @ ensures \result != null; // @ ensures String.equals(\result, ba2s(providerId)); // @ pure public String getProviderId(); // @ public normal_behavior // @ requires providerInformation != null; // @ ensures \fresh(\result); // @ ensures Arrays.equalArrays(providerInformation, \result); // @ pure public byte[] getProviderInformation(); // @ public normal_behavior // @ requires encryptedDataKey != null; // @ ensures \fresh(\result); // @ ensures Arrays.equalArrays(encryptedDataKey, \result); // @ pure public byte[] getEncryptedDataKey(); }
798
0
Create_ds/aws-encryption-sdk-java/src/main/java/com/amazonaws
Create_ds/aws-encryption-sdk-java/src/main/java/com/amazonaws/encryptionsdk/AwsCrypto.java
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package com.amazonaws.encryptionsdk; import com.amazonaws.encryptionsdk.exception.AwsCryptoException; import com.amazonaws.encryptionsdk.exception.BadCiphertextException; import com.amazonaws.encryptionsdk.internal.*; import com.amazonaws.encryptionsdk.model.CiphertextHeaders; import com.amazonaws.encryptionsdk.model.EncryptionMaterials; import com.amazonaws.encryptionsdk.model.EncryptionMaterialsRequest; import java.io.InputStream; import java.io.OutputStream; import java.nio.charset.StandardCharsets; import java.util.Collections; import java.util.Map; /** * Provides the primary entry-point to the AWS Encryption SDK. All encryption and decryption * operations should start here. Most people will want to use either {@link * #encryptData(MasterKeyProvider, byte[], Map)} and {@link #decryptData(MasterKeyProvider, byte[])} * to encrypt/decrypt things. * * <p>The core concepts (and classes) in this SDK are: * * <ul> * <li>{@link AwsCrypto} * <li>{@link DataKey} * <li>{@link MasterKey} * <li>{@link MasterKeyProvider} * </ul> * * <p>{@link AwsCrypto} provides the primary way to encrypt/decrypt data. It can operate on * byte-arrays, streams, or {@link java.lang.String Strings}. This data is encrypted using the * specifed {@link CryptoAlgorithm} and a {@link DataKey} which is unique to each encrypted message. * This {@code DataKey} is then encrypted using one (or more) {@link MasterKey MasterKeys}. The * process is reversed on decryption with the code selecting a copy of the {@code DataKey} protected * by a usable {@code MasterKey}, decrypting the {@code DataKey}, and then decrypted the message. * * <p>The main way to get a {@code MasterKey} is through the use of a {@link MasterKeyProvider}. * This provides a common interface for the AwsEncryptionSdk to find and retrieve {@code * MasterKeys}. (Some {@code MasterKeys} can also be constructed directly.) * * <p>{@code AwsCrypto} uses the {@code MasterKeyProvider} to determine which {@code MasterKeys} * should be used to encrypt the {@code DataKeys} by calling {@link * MasterKeyProvider#getMasterKeysForEncryption(MasterKeyRequest)} . When more than one {@code * MasterKey} is returned, the first {@code MasterKeys} is used to create the {@code DataKeys} by * calling {@link MasterKey#generateDataKey(CryptoAlgorithm,java.util.Map)} . All of the other * {@code MasterKeys} are then used to re-encrypt that {@code DataKey} with {@link * MasterKey#encryptDataKey(CryptoAlgorithm,java.util.Map,DataKey)} . This list of {@link * EncryptedDataKey EncryptedDataKeys} (the same {@code DataKey} possibly encrypted multiple times) * is stored in the {@link com.amazonaws.encryptionsdk.model.CiphertextHeaders}. * * <p>{@code AwsCrypto} also uses the {@code MasterKeyProvider} to decrypt one of the {@link * EncryptedDataKey EncryptedDataKeys} from the header to retrieve the actual {@code DataKey} * necessary to decrypt the message. * * <p>Any place a {@code MasterKeyProvider} is used, a {@link MasterKey} can be used instead. The * {@code MasterKey} will behave as a {@code MasterKeyProvider} which is only capable of providing * itself. This is often useful when only one {@code MasterKey} is being used. * * <p>Note regarding the use of generics: This library makes heavy use of generics to provide type * safety to advanced developers. The great majority of users should be able to just use the * provided type parameters or the {@code ?} wildcard. */ @SuppressWarnings("WeakerAccess") // this is a public API public class AwsCrypto { private static final Map<String, String> EMPTY_MAP = Collections.emptyMap(); // These are volatile because we allow unsynchronized writes via our setters, // and without setting volatile we could see strange results. // E.g. copying these to a local might give different values on subsequent reads from the local. // By setting them volatile we ensure that proper memory barriers are applied // to ensure things behave in a sensible manner. private volatile CryptoAlgorithm encryptionAlgorithm_ = null; private volatile int encryptionFrameSize_ = getDefaultFrameSize(); private static final CommitmentPolicy DEFAULT_COMMITMENT_POLICY = CommitmentPolicy.RequireEncryptRequireDecrypt; private final CommitmentPolicy commitmentPolicy_; /** * The maximum number of encrypted data keys to unwrap (resp. wrap) on decrypt (resp. encrypt), if * positive. If zero, do not limit EDKs. */ private final int maxEncryptedDataKeys_; private AwsCrypto(Builder builder) { commitmentPolicy_ = builder.commitmentPolicy_ == null ? DEFAULT_COMMITMENT_POLICY : builder.commitmentPolicy_; if (builder.encryptionAlgorithm_ != null && !commitmentPolicy_.algorithmAllowedForEncrypt(builder.encryptionAlgorithm_)) { if (commitmentPolicy_ == CommitmentPolicy.ForbidEncryptAllowDecrypt) { throw new AwsCryptoException( "Configuration conflict. Cannot encrypt due to CommitmentPolicy " + commitmentPolicy_ + " requiring only non-committed messages. Algorithm ID was " + builder.encryptionAlgorithm_ + ". See: https://docs.aws.amazon.com/encryption-sdk/latest/developer-guide/troubleshooting-migration.html"); } else { throw new AwsCryptoException( "Configuration conflict. Cannot encrypt due to CommitmentPolicy " + commitmentPolicy_ + " requiring only committed messages. Algorithm ID was " + builder.encryptionAlgorithm_ + ". See: https://docs.aws.amazon.com/encryption-sdk/latest/developer-guide/troubleshooting-migration.html"); } } encryptionAlgorithm_ = builder.encryptionAlgorithm_; encryptionFrameSize_ = builder.encryptionFrameSize_; maxEncryptedDataKeys_ = builder.maxEncryptedDataKeys_; } public static class Builder { private CryptoAlgorithm encryptionAlgorithm_; private int encryptionFrameSize_ = getDefaultFrameSize(); private CommitmentPolicy commitmentPolicy_; private int maxEncryptedDataKeys_ = CiphertextHeaders.NO_MAX_ENCRYPTED_DATA_KEYS; private Builder() {} private Builder(final AwsCrypto client) { encryptionAlgorithm_ = client.encryptionAlgorithm_; encryptionFrameSize_ = client.encryptionFrameSize_; commitmentPolicy_ = client.commitmentPolicy_; maxEncryptedDataKeys_ = client.maxEncryptedDataKeys_; } /** * Sets the {@link CryptoAlgorithm} to encrypt with. The Aws Crypto client will use the last * crypto algorithm set with either {@link * AwsCrypto.Builder#withEncryptionAlgorithm(CryptoAlgorithm)} or {@link * #setEncryptionAlgorithm(CryptoAlgorithm)} to encrypt with. * * @param encryptionAlgorithm The {@link CryptoAlgorithm} * @return The Builder, for method chaining */ public Builder withEncryptionAlgorithm(CryptoAlgorithm encryptionAlgorithm) { this.encryptionAlgorithm_ = encryptionAlgorithm; return this; } /** * Sets the frame size of the encrypted messages that the Aws Crypto client produces. The Aws * Crypto client will use the last frame size set with either {@link * AwsCrypto.Builder#withEncryptionFrameSize(int)} or {@link #setEncryptionFrameSize(int)}. * * @param frameSize The frame size to produce encrypted messages with. * @return The Builder, for method chaining */ public Builder withEncryptionFrameSize(int frameSize) { this.encryptionFrameSize_ = frameSize; return this; } /** * Sets the {@link CommitmentPolicy} of this Aws Crypto client. * * @param commitmentPolicy The commitment policy to enforce during encryption and decryption * @return The Builder, for method chaining */ public Builder withCommitmentPolicy(CommitmentPolicy commitmentPolicy) { Utils.assertNonNull(commitmentPolicy, "commitmentPolicy"); this.commitmentPolicy_ = commitmentPolicy; return this; } /** * Sets the maximum number of encrypted data keys that this Aws Crypto client will wrap when * encrypting, or unwrap when decrypting, a single message. * * @param maxEncryptedDataKeys The maximum number of encrypted data keys; must be positive * @return The Builder, for method chaining */ public Builder withMaxEncryptedDataKeys(int maxEncryptedDataKeys) { if (maxEncryptedDataKeys < 1) { throw new IllegalArgumentException("maxEncryptedDataKeys must be positive"); } this.maxEncryptedDataKeys_ = maxEncryptedDataKeys; return this; } public AwsCrypto build() { return new AwsCrypto(this); } } public static Builder builder() { return new Builder(); } public Builder toBuilder() { return new Builder(this); } public static AwsCrypto standard() { return AwsCrypto.builder().build(); } /** * Returns the frame size to use for encryption when none is explicitly selected. Currently it is * 4096. */ public static int getDefaultFrameSize() { return 4096; } /** * Sets the {@link CryptoAlgorithm} to use when <em>encrypting</em> data. This has no impact on * decryption. */ public void setEncryptionAlgorithm(final CryptoAlgorithm alg) { if (!commitmentPolicy_.algorithmAllowedForEncrypt(alg)) { if (commitmentPolicy_ == CommitmentPolicy.ForbidEncryptAllowDecrypt) { throw new AwsCryptoException( "Configuration conflict. Cannot encrypt due to CommitmentPolicy " + commitmentPolicy_ + " requiring only non-committed messages. Algorithm ID was " + alg + ". See: https://docs.aws.amazon.com/encryption-sdk/latest/developer-guide/troubleshooting-migration.html"); } else { throw new AwsCryptoException( "Configuration conflict. Cannot encrypt due to CommitmentPolicy " + commitmentPolicy_ + " requiring only committed messages. Algorithm ID was " + alg + ". See: https://docs.aws.amazon.com/encryption-sdk/latest/developer-guide/troubleshooting-migration.html"); } } encryptionAlgorithm_ = alg; } public CryptoAlgorithm getEncryptionAlgorithm() { return encryptionAlgorithm_; } /** * Sets the framing size to use when <em>encrypting</em> data. This has no impact on decryption. * If {@code frameSize} is 0, then framing is disabled and the entire plaintext will be encrypted * in a single block. * * <p>Note that during encryption arrays of this size will be allocated. Using extremely large * frame sizes may pose compatibility issues when the decryptor is running on 32-bit systems. * Additionally, Java VM limits may set a platform-specific upper bound to frame sizes. */ public void setEncryptionFrameSize(final int frameSize) { if (frameSize < 0) { throw new IllegalArgumentException("frameSize must be non-negative"); } encryptionFrameSize_ = frameSize; } public int getEncryptionFrameSize() { return encryptionFrameSize_; } /** * Returns the best estimate for the output length of encrypting a plaintext with the provided * {@code plaintextSize} and {@code encryptionContext}. The actual ciphertext may be shorter. * * <p>This method is equivalent to calling {@link #estimateCiphertextSize(CryptoMaterialsManager, * int, Map)} with a {@link DefaultCryptoMaterialsManager} based on the given provider. */ public <K extends MasterKey<K>> long estimateCiphertextSize( final MasterKeyProvider<K> provider, final int plaintextSize, final Map<String, String> encryptionContext) { return estimateCiphertextSize( new DefaultCryptoMaterialsManager(provider), plaintextSize, encryptionContext); } /** * Returns the best estimate for the output length of encrypting a plaintext with the provided * {@code plaintextSize} and {@code encryptionContext}. The actual ciphertext may be shorter. */ public long estimateCiphertextSize( CryptoMaterialsManager materialsManager, final int plaintextSize, final Map<String, String> encryptionContext) { EncryptionMaterialsRequest request = EncryptionMaterialsRequest.newBuilder() .setContext(encryptionContext) .setRequestedAlgorithm(getEncryptionAlgorithm()) // We're not actually encrypting any data, so don't consume any bytes from the cache's // limits. We do need to // pass /something/ though, or the cache will be bypassed (as it'll assume this is a // streaming encrypt of // unknown size). .setPlaintextSize(0) .setCommitmentPolicy(commitmentPolicy_) .build(); final MessageCryptoHandler cryptoHandler = new EncryptionHandler( getEncryptionFrameSize(), checkAlgorithm(materialsManager.getMaterialsForEncrypt(request)), commitmentPolicy_); return cryptoHandler.estimateOutputSize(plaintextSize); } /** * Returns the equivalent to calling {@link #estimateCiphertextSize(MasterKeyProvider, int, Map)} * with an empty {@code encryptionContext}. */ public <K extends MasterKey<K>> long estimateCiphertextSize( final MasterKeyProvider<K> provider, final int plaintextSize) { return estimateCiphertextSize(provider, plaintextSize, EMPTY_MAP); } /** * Returns the equivalent to calling {@link #estimateCiphertextSize(CryptoMaterialsManager, int, * Map)} with an empty {@code encryptionContext}. */ public long estimateCiphertextSize( final CryptoMaterialsManager materialsManager, final int plaintextSize) { return estimateCiphertextSize(materialsManager, plaintextSize, EMPTY_MAP); } /** * Returns an encrypted form of {@code plaintext} that has been protected with {@link DataKey * DataKeys} that are in turn protected by {@link MasterKey MasterKeys} provided by {@code * provider}. * * <p>This method is equivalent to calling {@link #encryptData(CryptoMaterialsManager, byte[], * Map)} using a {@link DefaultCryptoMaterialsManager} based on the given provider. */ public <K extends MasterKey<K>> CryptoResult<byte[], K> encryptData( final MasterKeyProvider<K> provider, final byte[] plaintext, final Map<String, String> encryptionContext) { //noinspection unchecked return (CryptoResult<byte[], K>) encryptData(new DefaultCryptoMaterialsManager(provider), plaintext, encryptionContext); } /** * Returns an encrypted form of {@code plaintext} that has been protected with {@link DataKey * DataKeys} that are in turn protected by the given CryptoMaterialsProvider. */ public CryptoResult<byte[], ?> encryptData( CryptoMaterialsManager materialsManager, final byte[] plaintext, final Map<String, String> encryptionContext) { EncryptionMaterialsRequest request = EncryptionMaterialsRequest.newBuilder() .setContext(encryptionContext) .setRequestedAlgorithm(getEncryptionAlgorithm()) .setPlaintext(plaintext) .setCommitmentPolicy(commitmentPolicy_) .build(); EncryptionMaterials encryptionMaterials = checkMaxEncryptedDataKeys(checkAlgorithm(materialsManager.getMaterialsForEncrypt(request))); final MessageCryptoHandler cryptoHandler = new EncryptionHandler(getEncryptionFrameSize(), encryptionMaterials, commitmentPolicy_); final int outSizeEstimate = cryptoHandler.estimateOutputSize(plaintext.length); final byte[] out = new byte[outSizeEstimate]; int outLen = cryptoHandler.processBytes(plaintext, 0, plaintext.length, out, 0).getBytesWritten(); outLen += cryptoHandler.doFinal(out, outLen); final byte[] outBytes = Utils.truncate(out, outLen); //noinspection unchecked return new CryptoResult(outBytes, cryptoHandler.getMasterKeys(), cryptoHandler.getHeaders()); } /** * Returns the equivalent to calling {@link #encryptData(MasterKeyProvider, byte[], Map)} with an * empty {@code encryptionContext}. */ public <K extends MasterKey<K>> CryptoResult<byte[], K> encryptData( final MasterKeyProvider<K> provider, final byte[] plaintext) { return encryptData(provider, plaintext, EMPTY_MAP); } /** * Returns the equivalent to calling {@link #encryptData(CryptoMaterialsManager, byte[], Map)} * with an empty {@code encryptionContext}. */ public CryptoResult<byte[], ?> encryptData( final CryptoMaterialsManager materialsManager, final byte[] plaintext) { return encryptData(materialsManager, plaintext, EMPTY_MAP); } /** * Calls {@link #encryptData(MasterKeyProvider, byte[], Map)} on the UTF-8 encoded bytes of {@code * plaintext} and base64 encodes the result. * * @deprecated Use the {@link #encryptData(MasterKeyProvider, byte[], Map)} and {@link * #decryptData(MasterKeyProvider, byte[])} APIs instead. {@code encryptString} and {@code * decryptString} work as expected if you use them together. However, to work with other * language implementations of the AWS Encryption SDK, you need to base64-decode the output of * {@code encryptString} and base64-encode the input to {@code decryptString}. These * deprecated APIs will be removed in the future. */ @Deprecated public <K extends MasterKey<K>> CryptoResult<String, K> encryptString( final MasterKeyProvider<K> provider, final String plaintext, final Map<String, String> encryptionContext) { //noinspection unchecked return (CryptoResult<String, K>) encryptString(new DefaultCryptoMaterialsManager(provider), plaintext, encryptionContext); } /** * Calls {@link #encryptData(CryptoMaterialsManager, byte[], Map)} on the UTF-8 encoded bytes of * {@code plaintext} and base64 encodes the result. * * @deprecated Use the {@link #encryptData(CryptoMaterialsManager, byte[], Map)} and {@link * #decryptData(CryptoMaterialsManager, byte[])} APIs instead. {@code encryptString} and * {@code decryptString} work as expected if you use them together. However, to work with * other language implementations of the AWS Encryption SDK, you need to base64-decode the * output of {@code encryptString} and base64-encode the input to {@code decryptString}. These * deprecated APIs will be removed in the future. */ @Deprecated public CryptoResult<String, ?> encryptString( CryptoMaterialsManager materialsManager, final String plaintext, final Map<String, String> encryptionContext) { final CryptoResult<byte[], ?> ctBytes = encryptData( materialsManager, plaintext.getBytes(StandardCharsets.UTF_8), encryptionContext); return new CryptoResult<>( Utils.encodeBase64String(ctBytes.getResult()), ctBytes.getMasterKeys(), ctBytes.getHeaders()); } /** * Returns the equivalent to calling {@link #encryptString(MasterKeyProvider, String, Map)} with * an empty {@code encryptionContext}. * * @deprecated Use the {@link #encryptData(MasterKeyProvider, byte[])} and {@link * #decryptData(MasterKeyProvider, byte[])} APIs instead. {@code encryptString} and {@code * decryptString} work as expected if you use them together. However, to work with other * language implementations of the AWS Encryption SDK, you need to base64-decode the output of * {@code encryptString} and base64-encode the input to {@code decryptString}. These * deprecated APIs will be removed in the future. */ @Deprecated public <K extends MasterKey<K>> CryptoResult<String, K> encryptString( final MasterKeyProvider<K> provider, final String plaintext) { return encryptString(provider, plaintext, EMPTY_MAP); } /** * Returns the equivalent to calling {@link #encryptString(CryptoMaterialsManager, String, Map)} * with an empty {@code encryptionContext}. * * @deprecated Use the {@link #encryptData(CryptoMaterialsManager, byte[])} and {@link * #decryptData(CryptoMaterialsManager, byte[])} APIs instead. {@code encryptString} and * {@code decryptString} work as expected if you use them together. However, to work with * other language implementations of the AWS Encryption SDK, you need to base64-decode the * output of {@code encryptString} and base64-encode the input to {@code decryptString}. These * deprecated APIs will be removed in the future. */ @Deprecated public CryptoResult<String, ?> encryptString( final CryptoMaterialsManager materialsManager, final String plaintext) { return encryptString(materialsManager, plaintext, EMPTY_MAP); } /** * Decrypts the provided {@code ciphertext} by requesting that the {@code provider} unwrap any * usable {@link DataKey} in the ciphertext and then decrypts the ciphertext using that {@code * DataKey}. */ public <K extends MasterKey<K>> CryptoResult<byte[], K> decryptData( final MasterKeyProvider<K> provider, final byte[] ciphertext) { return decryptData( Utils.assertNonNull(provider, "provider"), new ParsedCiphertext(ciphertext, maxEncryptedDataKeys_)); } /** * Decrypts the provided ciphertext by delegating to the provided materialsManager to obtain the * decrypted {@link DataKey}. * * @param materialsManager the {@link CryptoMaterialsManager} to use for decryption operations. * @param ciphertext the ciphertext to attempt to decrypt. * @return the {@link CryptoResult} with the decrypted data. */ public CryptoResult<byte[], ?> decryptData( final CryptoMaterialsManager materialsManager, final byte[] ciphertext) { return decryptData( Utils.assertNonNull(materialsManager, "materialsManager"), new ParsedCiphertext(ciphertext, maxEncryptedDataKeys_)); } /** @see #decryptData(MasterKeyProvider, byte[]) */ @SuppressWarnings("unchecked") public <K extends MasterKey<K>> CryptoResult<byte[], K> decryptData( final MasterKeyProvider<K> provider, final ParsedCiphertext ciphertext) { Utils.assertNonNull(provider, "provider"); return (CryptoResult<byte[], K>) decryptData(new DefaultCryptoMaterialsManager(provider), ciphertext); } /** @see #decryptData(CryptoMaterialsManager, byte[]) */ public CryptoResult<byte[], ?> decryptData( final CryptoMaterialsManager materialsManager, final ParsedCiphertext ciphertext) { Utils.assertNonNull(materialsManager, "materialsManager"); final MessageCryptoHandler cryptoHandler = DecryptionHandler.create( materialsManager, ciphertext, commitmentPolicy_, SignaturePolicy.AllowEncryptAllowDecrypt, maxEncryptedDataKeys_); final byte[] ciphertextBytes = ciphertext.getCiphertext(); final int contentLen = ciphertextBytes.length - ciphertext.getOffset(); final int outSizeEstimate = cryptoHandler.estimateOutputSize(contentLen); final byte[] out = new byte[outSizeEstimate]; final ProcessingSummary processed = cryptoHandler.processBytes(ciphertextBytes, ciphertext.getOffset(), contentLen, out, 0); if (processed.getBytesProcessed() != contentLen) { throw new BadCiphertextException( "Unable to process entire ciphertext. May have trailing data."); } int outLen = processed.getBytesWritten(); outLen += cryptoHandler.doFinal(out, outLen); final byte[] outBytes = Utils.truncate(out, outLen); //noinspection unchecked return new CryptoResult(outBytes, cryptoHandler.getMasterKeys(), cryptoHandler.getHeaders()); } /** * Base64 decodes the {@code ciphertext} prior to decryption and then treats the results as a * UTF-8 encoded string. * * @see #decryptData(MasterKeyProvider, byte[]) * @deprecated Use the {@link #decryptData(MasterKeyProvider, byte[])} and {@link * #encryptData(MasterKeyProvider, byte[], Map)} APIs instead. {@code encryptString} and * {@code decryptString} work as expected if you use them together. However, to work with * other language implementations of the AWS Encryption SDK, you need to base64-decode the * output of {@code encryptString} and base64-encode the input to {@code decryptString}. These * deprecated APIs will be removed in the future. */ @Deprecated @SuppressWarnings("unchecked") public <K extends MasterKey<K>> CryptoResult<String, K> decryptString( final MasterKeyProvider<K> provider, final String ciphertext) { return (CryptoResult<String, K>) decryptString(new DefaultCryptoMaterialsManager(provider), ciphertext); } /** * Base64 decodes the {@code ciphertext} prior to decryption and then treats the results as a * UTF-8 encoded string. * * @see #decryptData(CryptoMaterialsManager, byte[]) * @deprecated Use the {@link #decryptData(CryptoMaterialsManager, byte[])} and {@link * #encryptData(CryptoMaterialsManager, byte[], Map)} APIs instead. {@code encryptString} and * {@code decryptString} work as expected if you use them together. However, to work with * other language implementations of the AWS Encryption SDK, you need to base64-decode the * output of {@code encryptString} and base64-encode the input to {@code decryptString}. These * deprecated APIs will be removed in the future. */ @Deprecated public CryptoResult<String, ?> decryptString( final CryptoMaterialsManager provider, final String ciphertext) { Utils.assertNonNull(provider, "provider"); final byte[] ciphertextBytes; try { ciphertextBytes = Utils.decodeBase64String(Utils.assertNonNull(ciphertext, "ciphertext")); } catch (final IllegalArgumentException ex) { throw new BadCiphertextException("Invalid base 64", ex); } final CryptoResult<byte[], ?> ptBytes = decryptData(provider, ciphertextBytes); //noinspection unchecked return new CryptoResult( new String(ptBytes.getResult(), StandardCharsets.UTF_8), ptBytes.getMasterKeys(), ptBytes.getHeaders()); } /** * Returns a {@link CryptoOutputStream} which encrypts the data prior to passing it onto the * underlying {@link OutputStream}. * * @see #encryptData(MasterKeyProvider, byte[], Map) * @see javax.crypto.CipherOutputStream */ public <K extends MasterKey<K>> CryptoOutputStream<K> createEncryptingStream( final MasterKeyProvider<K> provider, final OutputStream os, final Map<String, String> encryptionContext) { //noinspection unchecked return (CryptoOutputStream<K>) createEncryptingStream(new DefaultCryptoMaterialsManager(provider), os, encryptionContext); } /** * Returns a {@link CryptoOutputStream} which encrypts the data prior to passing it onto the * underlying {@link OutputStream}. * * @see #encryptData(MasterKeyProvider, byte[], Map) * @see javax.crypto.CipherOutputStream */ public CryptoOutputStream<?> createEncryptingStream( final CryptoMaterialsManager materialsManager, final OutputStream os, final Map<String, String> encryptionContext) { return new CryptoOutputStream<>( os, getEncryptingStreamHandler(materialsManager, encryptionContext)); } /** * Returns the equivalent to calling {@link #createEncryptingStream(MasterKeyProvider, * OutputStream, Map)} with an empty {@code encryptionContext}. */ public <K extends MasterKey<K>> CryptoOutputStream<K> createEncryptingStream( final MasterKeyProvider<K> provider, final OutputStream os) { return createEncryptingStream(provider, os, EMPTY_MAP); } /** * Returns the equivalent to calling {@link #createEncryptingStream(CryptoMaterialsManager, * OutputStream, Map)} with an empty {@code encryptionContext}. */ public CryptoOutputStream<?> createEncryptingStream( final CryptoMaterialsManager materialsManager, final OutputStream os) { return createEncryptingStream(materialsManager, os, EMPTY_MAP); } /** * Returns a {@link CryptoInputStream} which encrypts the data after reading it from the * underlying {@link InputStream}. * * @see #encryptData(MasterKeyProvider, byte[], Map) * @see javax.crypto.CipherInputStream */ public <K extends MasterKey<K>> CryptoInputStream<K> createEncryptingStream( final MasterKeyProvider<K> provider, final InputStream is, final Map<String, String> encryptionContext) { //noinspection unchecked return (CryptoInputStream<K>) createEncryptingStream(new DefaultCryptoMaterialsManager(provider), is, encryptionContext); } /** * Returns a {@link CryptoInputStream} which encrypts the data after reading it from the * underlying {@link InputStream}. * * @see #encryptData(MasterKeyProvider, byte[], Map) * @see javax.crypto.CipherInputStream */ public CryptoInputStream<?> createEncryptingStream( CryptoMaterialsManager materialsManager, final InputStream is, final Map<String, String> encryptionContext) { final MessageCryptoHandler cryptoHandler = getEncryptingStreamHandler(materialsManager, encryptionContext); return new CryptoInputStream<>(is, cryptoHandler); } /** * Returns the equivalent to calling {@link #createEncryptingStream(MasterKeyProvider, * InputStream, Map)} with an empty {@code encryptionContext}. */ public <K extends MasterKey<K>> CryptoInputStream<K> createEncryptingStream( final MasterKeyProvider<K> provider, final InputStream is) { return createEncryptingStream(provider, is, EMPTY_MAP); } /** * Returns the equivalent to calling {@link #createEncryptingStream(CryptoMaterialsManager, * InputStream, Map)} with an empty {@code encryptionContext}. */ public CryptoInputStream<?> createEncryptingStream( final CryptoMaterialsManager materialsManager, final InputStream is) { return createEncryptingStream(materialsManager, is, EMPTY_MAP); } /** * Returns a {@link CryptoOutputStream} which decrypts the data prior to passing it onto the * underlying {@link OutputStream}. This version only accepts unsigned messages. * * @see #decryptData(MasterKeyProvider, byte[]) * @see javax.crypto.CipherOutputStream */ public <K extends MasterKey<K>> CryptoOutputStream<K> createUnsignedMessageDecryptingStream( final MasterKeyProvider<K> provider, final OutputStream os) { final MessageCryptoHandler cryptoHandler = DecryptionHandler.create( provider, commitmentPolicy_, SignaturePolicy.AllowEncryptForbidDecrypt, maxEncryptedDataKeys_); return new CryptoOutputStream<K>(os, cryptoHandler); } /** * Returns a {@link CryptoInputStream} which decrypts the data after reading it from the * underlying {@link InputStream}. This version only accepts unsigned messages. * * @see #decryptData(MasterKeyProvider, byte[]) * @see javax.crypto.CipherInputStream */ public <K extends MasterKey<K>> CryptoInputStream<K> createUnsignedMessageDecryptingStream( final MasterKeyProvider<K> provider, final InputStream is) { final MessageCryptoHandler cryptoHandler = DecryptionHandler.create( provider, commitmentPolicy_, SignaturePolicy.AllowEncryptForbidDecrypt, maxEncryptedDataKeys_); return new CryptoInputStream<K>(is, cryptoHandler); } /** * Returns a {@link CryptoOutputStream} which decrypts the data prior to passing it onto the * underlying {@link OutputStream}. This version only accepts unsigned messages. * * @see #decryptData(CryptoMaterialsManager, byte[]) * @see javax.crypto.CipherOutputStream */ public CryptoOutputStream<?> createUnsignedMessageDecryptingStream( final CryptoMaterialsManager materialsManager, final OutputStream os) { final MessageCryptoHandler cryptoHandler = DecryptionHandler.create( materialsManager, commitmentPolicy_, SignaturePolicy.AllowEncryptForbidDecrypt, maxEncryptedDataKeys_); return new CryptoOutputStream(os, cryptoHandler); } /** * Returns a {@link CryptoInputStream} which decrypts the data after reading it from the * underlying {@link InputStream}. This version only accepts unsigned messages. * * @see #encryptData(CryptoMaterialsManager, byte[], Map) * @see javax.crypto.CipherInputStream */ public CryptoInputStream<?> createUnsignedMessageDecryptingStream( final CryptoMaterialsManager materialsManager, final InputStream is) { final MessageCryptoHandler cryptoHandler = DecryptionHandler.create( materialsManager, commitmentPolicy_, SignaturePolicy.AllowEncryptForbidDecrypt, maxEncryptedDataKeys_); return new CryptoInputStream(is, cryptoHandler); } /** * Returns a {@link CryptoOutputStream} which decrypts the data prior to passing it onto the * underlying {@link OutputStream}. * * <p>Note that if the encrypted message includes a trailing signature, by necessity it cannot be * verified until after the decrypted plaintext has been released to the underlying {@link * OutputStream}! This behavior can be avoided by using the non-streaming * #decryptData(MasterKeyProvider, byte[]) method instead, or * #createUnsignedMessageDecryptingStream(MasterKeyProvider, OutputStream) if you do not need to * decrypt signed messages. * * @see #decryptData(MasterKeyProvider, byte[]) * @see #createUnsignedMessageDecryptingStream(MasterKeyProvider, OutputStream) * @see javax.crypto.CipherOutputStream */ public <K extends MasterKey<K>> CryptoOutputStream<K> createDecryptingStream( final MasterKeyProvider<K> provider, final OutputStream os) { final MessageCryptoHandler cryptoHandler = DecryptionHandler.create( provider, commitmentPolicy_, SignaturePolicy.AllowEncryptAllowDecrypt, maxEncryptedDataKeys_); return new CryptoOutputStream<K>(os, cryptoHandler); } /** * Returns a {@link CryptoInputStream} which decrypts the data after reading it from the * underlying {@link InputStream}. * * <p>Note that if the encrypted message includes a trailing signature, by necessity it cannot be * verified until after the decrypted plaintext has been produced from the {@link InputStream}! * This behavior can be avoided by using the non-streaming #decryptData(MasterKeyProvider, byte[]) * method instead, or #createUnsignedMessageDecryptingStream(MasterKeyProvider, InputStream) if * you do not need to decrypt signed messages. * * @see #decryptData(MasterKeyProvider, byte[]) * @see #createUnsignedMessageDecryptingStream(MasterKeyProvider, InputStream) * @see javax.crypto.CipherInputStream */ public <K extends MasterKey<K>> CryptoInputStream<K> createDecryptingStream( final MasterKeyProvider<K> provider, final InputStream is) { final MessageCryptoHandler cryptoHandler = DecryptionHandler.create( provider, commitmentPolicy_, SignaturePolicy.AllowEncryptAllowDecrypt, maxEncryptedDataKeys_); return new CryptoInputStream<K>(is, cryptoHandler); } /** * Returns a {@link CryptoOutputStream} which decrypts the data prior to passing it onto the * underlying {@link OutputStream}. * * <p>Note that if the encrypted message includes a trailing signature, by necessity it cannot be * verified until after the decrypted plaintext has been released to the underlying {@link * OutputStream}! This behavior can be avoided by using the non-streaming * #decryptData(CryptoMaterialsManager, byte[]) method instead, or * #createUnsignedMessageDecryptingStream(CryptoMaterialsManager, OutputStream) if you do not need * to decrypt signed messages. * * @see #decryptData(CryptoMaterialsManager, byte[]) * @see #createUnsignedMessageDecryptingStream(CryptoMaterialsManager, OutputStream) * @see javax.crypto.CipherOutputStream */ public CryptoOutputStream<?> createDecryptingStream( final CryptoMaterialsManager materialsManager, final OutputStream os) { final MessageCryptoHandler cryptoHandler = DecryptionHandler.create( materialsManager, commitmentPolicy_, SignaturePolicy.AllowEncryptAllowDecrypt, maxEncryptedDataKeys_); return new CryptoOutputStream(os, cryptoHandler); } /** * Returns a {@link CryptoInputStream} which decrypts the data after reading it from the * underlying {@link InputStream}. * * <p>Note that if the encrypted message includes a trailing signature, by necessity it cannot be * verified until after the decrypted plaintext has been produced from the {@link InputStream}! * This behavior can be avoided by using the non-streaming #decryptData(CryptoMaterialsManager, * byte[]) method instead, or #createUnsignedMessageDecryptingStream(CryptoMaterialsManager, * InputStream) if you do not need to decrypt signed messages. * * @see #decryptData(CryptoMaterialsManager, byte[]) * @see #createUnsignedMessageDecryptingStream(CryptoMaterialsManager, InputStream) * @see javax.crypto.CipherInputStream */ public CryptoInputStream<?> createDecryptingStream( final CryptoMaterialsManager materialsManager, final InputStream is) { final MessageCryptoHandler cryptoHandler = DecryptionHandler.create( materialsManager, commitmentPolicy_, SignaturePolicy.AllowEncryptAllowDecrypt, maxEncryptedDataKeys_); return new CryptoInputStream(is, cryptoHandler); } private MessageCryptoHandler getEncryptingStreamHandler( CryptoMaterialsManager materialsManager, Map<String, String> encryptionContext) { Utils.assertNonNull(materialsManager, "materialsManager"); Utils.assertNonNull(encryptionContext, "encryptionContext"); EncryptionMaterialsRequest.Builder requestBuilder = EncryptionMaterialsRequest.newBuilder() .setContext(encryptionContext) .setRequestedAlgorithm(getEncryptionAlgorithm()) .setCommitmentPolicy(commitmentPolicy_); return new LazyMessageCryptoHandler( info -> { // Hopefully we know the input size now, so we can pass it along to the CMM. if (info.getMaxInputSize() != -1) { requestBuilder.setPlaintextSize(info.getMaxInputSize()); } return new EncryptionHandler( getEncryptionFrameSize(), checkMaxEncryptedDataKeys( checkAlgorithm(materialsManager.getMaterialsForEncrypt(requestBuilder.build()))), commitmentPolicy_); }); } private EncryptionMaterials checkAlgorithm(EncryptionMaterials result) { if (encryptionAlgorithm_ != null && result.getAlgorithm() != encryptionAlgorithm_) { throw new AwsCryptoException( String.format( "Materials manager ignored requested algorithm; algorithm %s was set on AwsCrypto " + "but %s was selected", encryptionAlgorithm_, result.getAlgorithm())); } return result; } private EncryptionMaterials checkMaxEncryptedDataKeys(EncryptionMaterials materials) { if (maxEncryptedDataKeys_ > 0 && materials.getEncryptedDataKeys().size() > maxEncryptedDataKeys_) { throw new AwsCryptoException("Encrypted data keys exceed maxEncryptedDataKeys"); } return materials; } }
799