index int64 0 0 | repo_id stringlengths 26 205 | file_path stringlengths 51 246 | content stringlengths 8 433k | __index_level_0__ int64 0 10k |
|---|---|---|---|---|
0 | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/sdkv1/com/amazonaws/services/dynamodbv2/testing | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/sdkv1/com/amazonaws/services/dynamodbv2/testing/types/DoNotEncryptField.java | /*
* Copyright 2014 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.services.dynamodbv2.testing.types;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBTable;
import com.amazonaws.services.dynamodbv2.datamodeling.encryption.DoNotEncrypt;
@DynamoDBTable(tableName = "TableName")
public class DoNotEncryptField extends Mixed {
@DoNotEncrypt int value;
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
@Override
public int hashCode() {
return 31 * super.hashCode() + value;
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null) return false;
if (getClass() != obj.getClass()) return false;
DoNotEncryptField other = (DoNotEncryptField) obj;
if (value != other.value) return false;
return true;
}
}
| 5,000 |
0 | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/sdkv1/com/amazonaws/services/dynamodbv2/testing | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/sdkv1/com/amazonaws/services/dynamodbv2/testing/types/Untouched.java | /*
* Copyright 2014 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.services.dynamodbv2.testing.types;
import com.amazonaws.services.dynamodbv2.datamodeling.encryption.DoNotTouch;
@DoNotTouch
public class Untouched extends BaseClass {}
| 5,001 |
0 | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/sdkv1/com/amazonaws/services/dynamodbv2/testing | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/sdkv1/com/amazonaws/services/dynamodbv2/testing/types/UntouchedWithUnknownAttributeAnnotation.java | /*
* Copyright 2015 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.services.dynamodbv2.testing.types;
import com.amazonaws.services.dynamodbv2.datamodeling.encryption.DoNotTouch;
import com.amazonaws.services.dynamodbv2.datamodeling.encryption.HandleUnknownAttributes;
@DoNotTouch
@HandleUnknownAttributes
public class UntouchedWithUnknownAttributeAnnotation extends BaseClass {}
| 5,002 |
0 | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/sdkv1/com/amazonaws/services/dynamodbv2 | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/sdkv1/com/amazonaws/services/dynamodbv2/datamodeling/LegacyTestVectors.java | package com.amazonaws.services.dynamodbv2.datamodeling;
import software.amazon.cryptography.dbencryptionsdk.dynamodb.itemencryptor.internaldafny.legacy.InternalLegacyOverride;
import com.amazonaws.services.dynamodbv2.AmazonDynamoDB;
import com.amazonaws.services.dynamodbv2.datamodeling.encryption.DynamoDBEncryptor;
import com.amazonaws.services.dynamodbv2.model.*;
import com.amazonaws.services.dynamodbv2.testing.types.*;
import software.amazon.awssdk.core.SdkBytes;
import software.amazon.cryptography.dbencryptionsdk.dynamodb.itemencryptor.DynamoDbItemEncryptor;
import software.amazon.cryptography.dbencryptionsdk.dynamodb.itemencryptor.model.*;
import software.amazon.cryptography.dbencryptionsdk.dynamodb.model.LegacyOverride;
import software.amazon.cryptography.dbencryptionsdk.dynamodb.model.LegacyPolicy;
import software.amazon.cryptography.materialproviders.IKeyring;
import software.amazon.cryptography.materialproviders.MaterialProviders;
import software.amazon.cryptography.materialproviders.model.AesWrappingAlg;
import software.amazon.cryptography.materialproviders.model.CreateRawAesKeyringInput;
import software.amazon.cryptography.materialproviders.model.MaterialProvidersConfig;
import software.amazon.cryptography.dbencryptionsdk.structuredencryption.model.CryptoAction;
import java.lang.reflect.InvocationTargetException;
import java.nio.ByteBuffer;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;
import static com.amazonaws.services.dynamodbv2.datamodeling.TransformerHolisticIT.*;
import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertTrue;
public class LegacyTestVectors {
public static void decryptBaseClassTestVector(
final AmazonDynamoDB client,
final DynamoDBEncryptor legacyEncryptor,
final BaseClass TEST_VALUE
) {
final DecryptItemOutput out = getAndDecrypt(client, legacyEncryptor, TEST_VALUE);
try {
assertEquals(TEST_VALUE, attributeMapToBaseClass(out.plaintextItem(), TEST_VALUE));
} catch (NoSuchMethodException e) {
throw new RuntimeException(e);
} catch (InvocationTargetException e) {
throw new RuntimeException(e);
} catch (InstantiationException e) {
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}
public static void decryptHashKeyOnlyTestVector(
final AmazonDynamoDB client,
final DynamoDBEncryptor legacyEncryptor,
final String hashKey
) {
final HashKeyOnly TEST_VALUE = new HashKeyOnly();
TEST_VALUE.setHashKey(hashKey);
final DecryptItemOutput out = getAndDecrypt(client, legacyEncryptor, TEST_VALUE);
assertTrue(out.plaintextItem().containsKey(HASH_KEY));
assertEquals(hashKey, out.plaintextItem().get(HASH_KEY).s());
}
public static void decryptKeysOnlyTestVector(
final AmazonDynamoDB client,
final DynamoDBEncryptor legacyEncryptor,
final int hashKey,
final int rangeKey
) {
final KeysOnly TEST_VALUE = new KeysOnly();
TEST_VALUE.setHashKey(hashKey);
TEST_VALUE.setRangeKey(rangeKey);
final DecryptItemOutput out = getAndDecrypt(client, legacyEncryptor, TEST_VALUE);
assertTrue(out.plaintextItem().containsKey(HASH_KEY));
assertTrue(out.plaintextItem().containsKey(RANGE_KEY));
assertEquals(hashKey, Integer.valueOf(out.plaintextItem().get(HASH_KEY).n()).intValue());
assertEquals(rangeKey, Integer.valueOf(out.plaintextItem().get(RANGE_KEY).n()).intValue());
}
public static DecryptItemOutput getAndDecrypt(
final AmazonDynamoDB client,
final DynamoDBEncryptor legacyEncryptor,
final Object TEST_VALUE
) {
final DynamoDbItemEncryptorConfig foo = getConfig(legacyEncryptor, TEST_VALUE);
final DynamoDbItemEncryptor encryptor = DynamoDbItemEncryptor
.builder()
.DynamoDbItemEncryptorConfig(getConfig(legacyEncryptor, TEST_VALUE))
.build();
final GetItemResult item = client.getItem(getRequest(TEST_VALUE));
final DecryptItemInput decryptInput = DecryptItemInput
.builder()
.encryptedItem(InternalLegacyOverride.V1MapToV2Map(item.getItem()))
.build();
return encryptor.DecryptItem(decryptInput);
}
public static PutItemResult encryptAndPut(
final AmazonDynamoDB client,
final DynamoDBEncryptor legacyEncryptor,
final Object TEST_VALUE
) {
final DynamoDbItemEncryptor encryptor = DynamoDbItemEncryptor
.builder()
.DynamoDbItemEncryptorConfig(getConfig(legacyEncryptor, TEST_VALUE))
.build();
final EncryptItemInput encryptInput = EncryptItemInput
.builder()
.plaintextItem(baseClassToAttributeMap(TEST_VALUE))
.build();
EncryptItemOutput encryptOutput = encryptor.EncryptItem(encryptInput);
return client.putItem(putRequest(InternalLegacyOverride.V2MapToV1Map(encryptOutput.encryptedItem()), TEST_VALUE));
}
public static DynamoDbItemEncryptorConfig getConfig(
final DynamoDBEncryptor legacyEncryptor,
final Object TEST_VALUE
) {
final String tableName = getTableName(TEST_VALUE);
final Boolean hasRange = !getRangeKey(TEST_VALUE).equals("");
final HashMap<String, CryptoAction> legacyAttributeFlags = ActionsFromClass(TEST_VALUE);
final LegacyOverride legacyOverride = LegacyOverride
.builder()
.encryptor(legacyEncryptor)
// This is not testing Policy requirements
// This config works for both encrypt and decrypt test vectors.
.policy(LegacyPolicy.FORCE_LEGACY_ENCRYPT_ALLOW_LEGACY_DECRYPT)
.attributeActionsOnEncrypt(legacyAttributeFlags)
.build();
final Map<String, CryptoAction> onlyHashRange = legacyAttributeFlags
.entrySet()
.stream()
.filter(e -> e.getKey() == HASH_KEY || (e.getKey() == RANGE_KEY && hasRange))
.collect(Collectors.toMap(e -> e.getKey(), e -> e.getValue()));
final DynamoDbItemEncryptorConfig.Builder config = DynamoDbItemEncryptorConfig
.builder()
.logicalTableName(tableName)
.partitionKeyName(HASH_KEY)
.legacyOverride(legacyOverride)
// **Not** trying to write things,
// just trying to get to test the legacyOverride.
.attributeActionsOnEncrypt(onlyHashRange)
.keyring(createStaticKeyring());
if (hasRange) {
return config.sortKeyName(RANGE_KEY).build();
} else {
return config.build();
}
}
public static GetItemRequest getRequest(final Object TEST_VALUE) {
final String tableName = getTableName(TEST_VALUE);
HashMap<String, AttributeValue> v1KeyToGet = new HashMap();
if (TEST_VALUE instanceof HashKeyOnly) {
v1KeyToGet.put(HASH_KEY, new AttributeValue().withS(getHashKey(TEST_VALUE)));
} else {
v1KeyToGet.put(HASH_KEY, new AttributeValue().withN(getHashKey(TEST_VALUE)));
}
final String rangeKey = getRangeKey(TEST_VALUE);
if (!rangeKey.equals("")) {
v1KeyToGet.put(RANGE_KEY, new AttributeValue().withN(rangeKey));
}
return new GetItemRequest()
.withTableName(tableName)
.withKey(v1KeyToGet);
}
public static PutItemRequest putRequest(
final Map<String, AttributeValue> encryptedItem,
final Object TEST_VALUE
) {
final String tableName = getTableName(TEST_VALUE);
return new PutItemRequest()
.withTableName(tableName)
.withItem(encryptedItem);
}
public static String getHashKey(final Object TEST_VALUE) {
if (TEST_VALUE instanceof BaseClass) {
return String.valueOf(((BaseClass) TEST_VALUE).getHashKey());
} else if (TEST_VALUE instanceof HashKeyOnly) {
return String.valueOf(((HashKeyOnly) TEST_VALUE).getHashKey());
} else if (TEST_VALUE instanceof KeysOnly) {
return String.valueOf(((KeysOnly) TEST_VALUE).getHashKey());
} else {
return ""; // ???
}
}
public static String getRangeKey(final Object TEST_VALUE) {
if (TEST_VALUE instanceof BaseClass) {
return String.valueOf(((BaseClass) TEST_VALUE).getRangeKey());
} else if (TEST_VALUE instanceof KeysOnly) {
return String.valueOf(((KeysOnly) TEST_VALUE).getRangeKey());
} else {
return ""; // ???
}
}
public static String getTableName(final Object TEST_VALUE) {
return TEST_VALUE.getClass().getAnnotation(DynamoDBTable.class).tableName();
}
// This is verbose.
// This way I can work out what is going on.
// There MAY be some clever use of reflection
// that would make this more compact.
// However, for tests I prefer verbosity.
public static HashMap<String, CryptoAction> ActionsFromClass(final Object value) {
HashMap<String, CryptoAction> attributeActionsOnEncrypt = new HashMap();
if (value instanceof Mixed) {
attributeActionsOnEncrypt.put(HASH_KEY, CryptoAction.SIGN_ONLY);
attributeActionsOnEncrypt.put(RANGE_KEY, CryptoAction.SIGN_ONLY);
attributeActionsOnEncrypt.put("stringValue", CryptoAction.SIGN_ONLY);
attributeActionsOnEncrypt.put("intValue", CryptoAction.DO_NOTHING);
attributeActionsOnEncrypt.put("byteArrayValue", CryptoAction.ENCRYPT_AND_SIGN);
attributeActionsOnEncrypt.put("stringSet", CryptoAction.ENCRYPT_AND_SIGN);
attributeActionsOnEncrypt.put("intSet", CryptoAction.ENCRYPT_AND_SIGN);
attributeActionsOnEncrypt.put("version", CryptoAction.SIGN_ONLY);
attributeActionsOnEncrypt.put("doubleValue", CryptoAction.SIGN_ONLY);
attributeActionsOnEncrypt.put("doubleSet", CryptoAction.SIGN_ONLY);
} else if (value instanceof SignOnly) {
attributeActionsOnEncrypt.put(HASH_KEY, CryptoAction.SIGN_ONLY);
attributeActionsOnEncrypt.put(RANGE_KEY, CryptoAction.SIGN_ONLY);
attributeActionsOnEncrypt.put("stringValue", CryptoAction.SIGN_ONLY);
attributeActionsOnEncrypt.put("intValue", CryptoAction.SIGN_ONLY);
attributeActionsOnEncrypt.put("byteArrayValue", CryptoAction.SIGN_ONLY);
attributeActionsOnEncrypt.put("stringSet", CryptoAction.SIGN_ONLY);
attributeActionsOnEncrypt.put("intSet", CryptoAction.SIGN_ONLY);
attributeActionsOnEncrypt.put("version", CryptoAction.SIGN_ONLY);
attributeActionsOnEncrypt.put("doubleValue", CryptoAction.SIGN_ONLY);
attributeActionsOnEncrypt.put("doubleSet", CryptoAction.SIGN_ONLY);
} else if (value instanceof Untouched) {
attributeActionsOnEncrypt.put(HASH_KEY, CryptoAction.SIGN_ONLY );
attributeActionsOnEncrypt.put(RANGE_KEY, CryptoAction.SIGN_ONLY);
attributeActionsOnEncrypt.put("stringValue", CryptoAction.DO_NOTHING);
attributeActionsOnEncrypt.put("intValue", CryptoAction.DO_NOTHING);
attributeActionsOnEncrypt.put("byteArrayValue", CryptoAction.DO_NOTHING);
attributeActionsOnEncrypt.put("stringSet", CryptoAction.DO_NOTHING);
attributeActionsOnEncrypt.put("intSet", CryptoAction.DO_NOTHING);
attributeActionsOnEncrypt.put("version", CryptoAction.DO_NOTHING);
attributeActionsOnEncrypt.put("doubleValue", CryptoAction.DO_NOTHING);
attributeActionsOnEncrypt.put("doubleSet", CryptoAction.DO_NOTHING);
} else if (value instanceof BaseClass) {
// This is a BaseClass
attributeActionsOnEncrypt.put(HASH_KEY, CryptoAction.SIGN_ONLY);
attributeActionsOnEncrypt.put(RANGE_KEY, CryptoAction.SIGN_ONLY);
attributeActionsOnEncrypt.put("stringValue", CryptoAction.ENCRYPT_AND_SIGN);
attributeActionsOnEncrypt.put("intValue", CryptoAction.ENCRYPT_AND_SIGN);
attributeActionsOnEncrypt.put("byteArrayValue", CryptoAction.ENCRYPT_AND_SIGN);
attributeActionsOnEncrypt.put("stringSet", CryptoAction.ENCRYPT_AND_SIGN);
attributeActionsOnEncrypt.put("intSet", CryptoAction.ENCRYPT_AND_SIGN);
attributeActionsOnEncrypt.put("version", CryptoAction.SIGN_ONLY);
attributeActionsOnEncrypt.put("doubleValue", CryptoAction.ENCRYPT_AND_SIGN);
attributeActionsOnEncrypt.put("doubleSet", CryptoAction.ENCRYPT_AND_SIGN);
} else if (value instanceof KeysOnly) {
attributeActionsOnEncrypt.put(HASH_KEY, CryptoAction.SIGN_ONLY);
attributeActionsOnEncrypt.put(RANGE_KEY, CryptoAction.SIGN_ONLY);
} else if (value instanceof HashKeyOnly) {
attributeActionsOnEncrypt.put(HASH_KEY, CryptoAction.SIGN_ONLY);
}
return attributeActionsOnEncrypt;
}
public static BaseClass attributeMapToBaseClass(
Map<String, software.amazon.awssdk.services.dynamodb.model.AttributeValue> attributeMap,
BaseClass TEST_VALUE
) throws NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
final BaseClass value = TEST_VALUE.getClass().getDeclaredConstructor().newInstance();
if (attributeMap.containsKey(HASH_KEY)) {
value.setHashKey(Integer.valueOf(attributeMap.get(HASH_KEY).n()));
}
if (attributeMap.containsKey(RANGE_KEY)) {
value.setRangeKey(Integer.valueOf(attributeMap.get(RANGE_KEY).n()));
}
if (attributeMap.containsKey("stringValue")) {
value.setStringValue(attributeMap.get("stringValue").s());
}
if (attributeMap.containsKey("intValue")) {
value.setIntValue(Integer.valueOf(attributeMap.get("intValue").n()));
}
if (attributeMap.containsKey("byteArrayValue")) {
value.setByteArrayValue(attributeMap.get("byteArrayValue").b().asByteArray());
}
if (attributeMap.containsKey("stringSet")) {
value.setStringSet(attributeMap.get("stringSet").ss().stream().collect(Collectors.toSet()));
}
if (attributeMap.containsKey("intSet")) {
value.setIntSet(
attributeMap.get("intSet").ns().stream().map(s -> Integer.valueOf(s)).collect(Collectors.toSet()));
}
if (attributeMap.containsKey("version")) {
value.setVersion(Integer.valueOf(attributeMap.get("version").n()));
}
if (attributeMap.containsKey("doubleValue")) {
value.setDoubleValue(Double.valueOf(attributeMap.get("doubleValue").n()));
}
if (attributeMap.containsKey("doubleSet")) {
value.setDoubleSet(
attributeMap.get("doubleSet").ns().stream().map(s -> Double.valueOf(s)).collect(Collectors.toSet()));
}
return value;
}
public static Map<String, software.amazon.awssdk.services.dynamodb.model.AttributeValue> baseClassToAttributeMap(
Object TEST_VALUE
) {
HashMap<String, software.amazon.awssdk.services.dynamodb.model.AttributeValue> attributes = new HashMap();
if (TEST_VALUE instanceof BaseClass) {
attributes.put(
HASH_KEY,
software.amazon.awssdk.services.dynamodb.model.AttributeValue.builder()
.n(String.valueOf(((BaseClass) TEST_VALUE).getHashKey())).build()
);
attributes.put(
RANGE_KEY,
software.amazon.awssdk.services.dynamodb.model.AttributeValue.builder()
.n(String.valueOf(((BaseClass) TEST_VALUE).getRangeKey())).build()
);
attributes.put(
"stringValue",
software.amazon.awssdk.services.dynamodb.model.AttributeValue.builder()
.s(String.valueOf(((BaseClass) TEST_VALUE).getStringValue())).build()
);
attributes.put(
"intValue",
software.amazon.awssdk.services.dynamodb.model.AttributeValue.builder()
.n(String.valueOf(((BaseClass) TEST_VALUE).getIntValue())).build()
);
attributes.put(
"byteArrayValue",
software.amazon.awssdk.services.dynamodb.model.AttributeValue.builder()
.b(SdkBytes.fromByteArray(((BaseClass) TEST_VALUE).getByteArrayValue())).build()
);
attributes.put(
"stringSet",
software.amazon.awssdk.services.dynamodb.model.AttributeValue.builder()
.ss(((BaseClass) TEST_VALUE).getStringSet()).build()
);
attributes.put(
"intSet",
software.amazon.awssdk.services.dynamodb.model.AttributeValue.builder()
.ns(((BaseClass) TEST_VALUE).getIntSet().stream().map(i -> String.valueOf(i)).collect(Collectors.toList())).build()
);
attributes.put(
"version",
software.amazon.awssdk.services.dynamodb.model.AttributeValue.builder()
.n(String.valueOf(((BaseClass) TEST_VALUE).getVersion())).build()
);
attributes.put(
"doubleValue",
software.amazon.awssdk.services.dynamodb.model.AttributeValue.builder()
.n(String.valueOf(((BaseClass) TEST_VALUE).getDoubleValue())).build()
);
attributes.put(
"doubleSet",
software.amazon.awssdk.services.dynamodb.model.AttributeValue.builder()
.ns(((BaseClass) TEST_VALUE).getDoubleSet().stream().map(i -> String.valueOf(i)).collect(Collectors.toList())).build()
);
} else if (TEST_VALUE instanceof KeysOnly) {
attributes.put(
HASH_KEY,
software.amazon.awssdk.services.dynamodb.model.AttributeValue.builder()
.n(String.valueOf(((KeysOnly) TEST_VALUE).getHashKey())).build()
);
attributes.put(
RANGE_KEY,
software.amazon.awssdk.services.dynamodb.model.AttributeValue.builder()
.n(String.valueOf(((KeysOnly) TEST_VALUE).getRangeKey())).build()
);
} else if (TEST_VALUE instanceof HashKeyOnly) {
attributes.put(
HASH_KEY,
software.amazon.awssdk.services.dynamodb.model.AttributeValue.builder()
.s(((HashKeyOnly) TEST_VALUE).getHashKey()).build()
);
}
return attributes;
}
public static IKeyring createStaticKeyring() {
MaterialProviders matProv = MaterialProviders.builder()
.MaterialProvidersConfig(MaterialProvidersConfig.builder().build())
.build();
ByteBuffer key = ByteBuffer.wrap(new byte[32]);
CreateRawAesKeyringInput keyringInput = CreateRawAesKeyringInput.builder()
.keyName("name")
.keyNamespace("namespace")
.wrappingAlg(AesWrappingAlg.ALG_AES256_GCM_IV12_TAG16)
.wrappingKey(key)
.build();
return matProv.CreateRawAesKeyring(keyringInput);
}
}
| 5,003 |
0 | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/sdkv1/com/amazonaws/services/dynamodbv2 | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/sdkv1/com/amazonaws/services/dynamodbv2/datamodeling/TransformerHolisticIT.java | // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package com.amazonaws.services.dynamodbv2.datamodeling;
import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertFalse;
import static org.testng.AssertJUnit.assertNull;
import static org.testng.AssertJUnit.assertTrue;
import static org.testng.AssertJUnit.fail;
import com.amazonaws.services.dynamodbv2.AmazonDynamoDB;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapperConfig.SaveBehavior;
import com.amazonaws.services.dynamodbv2.datamodeling.encryption.DynamoDBEncryptor;
import com.amazonaws.services.dynamodbv2.datamodeling.encryption.providers.AsymmetricStaticProvider;
import com.amazonaws.services.dynamodbv2.datamodeling.encryption.providers.CachingMostRecentProvider;
import com.amazonaws.services.dynamodbv2.datamodeling.encryption.providers.DirectKmsMaterialProvider;
import com.amazonaws.services.dynamodbv2.datamodeling.encryption.providers.EncryptionMaterialsProvider;
import com.amazonaws.services.dynamodbv2.datamodeling.encryption.providers.SymmetricStaticProvider;
import com.amazonaws.services.dynamodbv2.datamodeling.encryption.providers.WrappedMaterialsProvider;
import com.amazonaws.services.dynamodbv2.datamodeling.encryption.providers.store.MetaStore;
import com.amazonaws.services.dynamodbv2.datamodeling.encryption.providers.store.ProviderStore;
import com.amazonaws.services.dynamodbv2.local.embedded.DynamoDBEmbedded;
import com.amazonaws.services.dynamodbv2.model.*;
import com.amazonaws.services.dynamodbv2.testing.AttributeValueDeserializer;
import com.amazonaws.services.dynamodbv2.testing.AttributeValueSerializer;
import com.amazonaws.services.dynamodbv2.testing.ScenarioManifest;
import com.amazonaws.services.dynamodbv2.testing.ScenarioManifest.KeyData;
import com.amazonaws.services.dynamodbv2.testing.ScenarioManifest.Keys;
import com.amazonaws.services.dynamodbv2.testing.ScenarioManifest.Scenario;
import com.amazonaws.services.dynamodbv2.testing.types.BaseClass;
import com.amazonaws.services.dynamodbv2.testing.types.HashKeyOnly;
import com.amazonaws.services.dynamodbv2.testing.types.KeysOnly;
import com.amazonaws.services.dynamodbv2.testing.types.Mixed;
import com.amazonaws.services.dynamodbv2.testing.types.SignOnly;
import com.amazonaws.services.dynamodbv2.testing.types.Untouched;
import com.amazonaws.services.kms.AWSKMS;
import com.amazonaws.services.kms.AWSKMSClientBuilder;
import com.amazonaws.util.Base64;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.module.SimpleModule;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.security.GeneralSecurityException;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.*;
import java.util.stream.Collectors;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
public class TransformerHolisticIT {
private static final SecretKey aesKey =
new SecretKeySpec(new byte[] {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}, "AES");
private static final SecretKey hmacKey =
new SecretKeySpec(new byte[] {0, 1, 2, 3, 4, 5, 6, 7}, "HmacSHA256");
private static final String rsaEncPub =
"MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAtiNSLSvT9cExXOcD0dGZ"
+ "9DFEMHw8895gAZcCdSppDrxbD7XgZiQYTlgt058i5fS+l11guAUJtKt5sZ2u8Fx0"
+ "K9pxMdlczGtvQJdx/LQETEnLnfzAijvHisJ8h6dQOVczM7t01KIkS24QZElyO+kY"
+ "qMWLytUV4RSHnrnIuUtPHCe6LieDWT2+1UBguxgtFt1xdXlquACLVv/Em3wp40Xc"
+ "bIwzhqLitb98rTY/wqSiGTz1uvvBX46n+f2j3geZKCEDGkWcXYw3dH4lRtDWTbqw"
+ "eRcaNDT/MJswQlBk/Up9KCyN7gjX67gttiCO6jMoTNDejGeJhG4Dd2o0vmn8WJlr"
+ "5wIDAQAB";
private static final String rsaEncPriv =
"MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQC2I1ItK9P1wTFc"
+ "5wPR0Zn0MUQwfDzz3mABlwJ1KmkOvFsPteBmJBhOWC3TnyLl9L6XXWC4BQm0q3mx"
+ "na7wXHQr2nEx2VzMa29Al3H8tARMScud/MCKO8eKwnyHp1A5VzMzu3TUoiRLbhBk"
+ "SXI76RioxYvK1RXhFIeeuci5S08cJ7ouJ4NZPb7VQGC7GC0W3XF1eWq4AItW/8Sb"
+ "fCnjRdxsjDOGouK1v3ytNj/CpKIZPPW6+8Ffjqf5/aPeB5koIQMaRZxdjDd0fiVG"
+ "0NZNurB5Fxo0NP8wmzBCUGT9Sn0oLI3uCNfruC22II7qMyhM0N6MZ4mEbgN3ajS+"
+ "afxYmWvnAgMBAAECggEBAIIU293zDWDZZ73oJ+w0fHXQsdjHAmlRitPX3CN99KZX"
+ "k9m2ldudL9bUV3Zqk2wUzgIg6LDEuFfWmAVojsaP4VBopKtriEFfAYfqIbjPgLpT"
+ "gh8FoyWW6D6MBJCFyGALjUAHQ7uRScathvt5ESMEqV3wKJTmdsfX97w/B8J+rLN3"
+ "3fT3ZJUck5duZ8XKD+UtX1Y3UE1hTWo3Ae2MFND964XyUqy+HaYXjH0x6dhZzqyJ"
+ "/OJ/MPGeMJgxp+nUbMWerwxrLQceNFVgnQgHj8e8k4fd04rkowkkPua912gNtmz7"
+ "DuIEvcMnY64z585cn+cnXUPJwtu3JbAmn/AyLsV9FLECgYEA798Ut/r+vORB16JD"
+ "KFu38pQCgIbdCPkXeI0DC6u1cW8JFhgRqi+AqSrEy5SzY3IY7NVMSRsBI9Y026Bl"
+ "R9OQwTrOzLRAw26NPSDvbTkeYXlY9+hX7IovHjGkho/OxyTJ7bKRDYLoNCz56BC1"
+ "khIWvECpcf/fZU0nqOFVFqF3H/UCgYEAwmJ4rjl5fksTNtNRL6ivkqkHIPKXzk5w"
+ "C+L90HKNicic9bqyX8K4JRkGKSNYN3mkjrguAzUlEld390qNBw5Lu7PwATv0e2i+"
+ "6hdwJsjTKNpj7Nh4Mieq6d7lWe1L8FLyHEhxgIeQ4BgqrVtPPOH8IBGpuzVZdWwI"
+ "dgOvEvAi/usCgYBdfk3NB/+SEEW5jn0uldE0s4vmHKq6fJwxWIT/X4XxGJ4qBmec"
+ "NbeoOAtMbkEdWbNtXBXHyMbA+RTRJctUG5ooNou0Le2wPr6+PMAVilXVGD8dIWpj"
+ "v9htpFvENvkZlbU++IKhCY0ICR++3ARpUrOZ3Hou/NRN36y9nlZT48tSoQKBgES2"
+ "Bi6fxmBsLUiN/f64xAc1lH2DA0I728N343xRYdK4hTMfYXoUHH+QjurvwXkqmI6S"
+ "cEFWAdqv7IoPYjaCSSb6ffYRuWP+LK4WxuAO0QV53SSViDdCalntHmlhRhyXVVnG"
+ "CckDIqT0JfHNev7savDzDWpNe2fUXlFJEBPDqrstAoGBAOpd5+QBHF/tP5oPILH4"
+ "aD/zmqMH7VtB+b/fOPwtIM+B/WnU7hHLO5t2lJYu18Be3amPkfoQIB7bpkM3Cer2"
+ "G7Jw+TcHrY+EtIziDB5vwau1fl4VcbA9SfWpBojJ5Ifo9ELVxGiK95WxeQNSmLUy"
+ "7AJzhK1Gwey8a/v+xfqiu9sE";
private static final PrivateKey rsaPriv;
private static final PublicKey rsaPub;
private static final KeyPair rsaPair;
private static final EncryptionMaterialsProvider symProv;
private static final EncryptionMaterialsProvider asymProv;
private static final EncryptionMaterialsProvider symWrappedProv;
protected static final String HASH_KEY = "hashKey";
protected static final String RANGE_KEY = "rangeKey";
protected static final String BASE_CLASS_TABLE_NAME = "TableName";
private static final String RSA = "RSA";
private AmazonDynamoDB client;
private static AWSKMS kmsClient = AWSKMSClientBuilder.standard().build();
private static Map<String, KeyData> keyDataMap = new HashMap<>();
// AttributeEncryptor *must* be used with SaveBehavior.CLOBBER to avoid the risk of data
// corruption.
private static final DynamoDBMapperConfig CLOBBER_CONFIG =
DynamoDBMapperConfig.builder().withSaveBehavior(SaveBehavior.CLOBBER).build();
private static final BaseClass ENCRYPTED_TEST_VALUE = new BaseClass();
private static final Mixed MIXED_TEST_VALUE = new Mixed();
private static final SignOnly SIGNED_TEST_VALUE = new SignOnly();
private static final Untouched UNTOUCHED_TEST_VALUE = new Untouched();
private static final BaseClass ENCRYPTED_TEST_VALUE_2 = new BaseClass();
private static final Mixed MIXED_TEST_VALUE_2 = new Mixed();
private static final SignOnly SIGNED_TEST_VALUE_2 = new SignOnly();
private static final Untouched UNTOUCHED_TEST_VALUE_2 = new Untouched();
private static final String TEST_VECTOR_MANIFEST_DIR = "/vectors/encrypted_item/";
private static final String SCENARIO_MANIFEST_PATH = TEST_VECTOR_MANIFEST_DIR + "scenarios.json";
private static final String JAVA_DIR = "java";
static {
try {
KeyFactory rsaFact = KeyFactory.getInstance("RSA");
rsaPub = rsaFact.generatePublic(new X509EncodedKeySpec(Base64.decode(rsaEncPub)));
rsaPriv = rsaFact.generatePrivate(new PKCS8EncodedKeySpec(Base64.decode(rsaEncPriv)));
rsaPair = new KeyPair(rsaPub, rsaPriv);
} catch (GeneralSecurityException ex) {
throw new RuntimeException(ex);
}
symProv = new SymmetricStaticProvider(aesKey, hmacKey);
asymProv = new AsymmetricStaticProvider(rsaPair, rsaPair);
symWrappedProv = new WrappedMaterialsProvider(aesKey, aesKey, hmacKey);
ENCRYPTED_TEST_VALUE.setHashKey(5);
ENCRYPTED_TEST_VALUE.setRangeKey(7);
ENCRYPTED_TEST_VALUE.setVersion(0);
ENCRYPTED_TEST_VALUE.setIntValue(123);
ENCRYPTED_TEST_VALUE.setStringValue("Hello world!");
ENCRYPTED_TEST_VALUE.setByteArrayValue(new byte[] {0, 1, 2, 3, 4, 5});
ENCRYPTED_TEST_VALUE.setStringSet(
new HashSet<String>(Arrays.asList("Goodbye", "Cruel", "World", "?")));
ENCRYPTED_TEST_VALUE.setIntSet(new HashSet<Integer>(Arrays.asList(1, 200, 10, 15, 0)));
MIXED_TEST_VALUE.setHashKey(6);
MIXED_TEST_VALUE.setRangeKey(8);
MIXED_TEST_VALUE.setVersion(0);
MIXED_TEST_VALUE.setIntValue(123);
MIXED_TEST_VALUE.setStringValue("Hello world!");
MIXED_TEST_VALUE.setByteArrayValue(new byte[] {0, 1, 2, 3, 4, 5});
MIXED_TEST_VALUE.setStringSet(
new HashSet<String>(Arrays.asList("Goodbye", "Cruel", "World", "?")));
MIXED_TEST_VALUE.setIntSet(new HashSet<Integer>(Arrays.asList(1, 200, 10, 15, 0)));
SIGNED_TEST_VALUE.setHashKey(8);
SIGNED_TEST_VALUE.setRangeKey(10);
SIGNED_TEST_VALUE.setVersion(0);
SIGNED_TEST_VALUE.setIntValue(123);
SIGNED_TEST_VALUE.setStringValue("Hello world!");
SIGNED_TEST_VALUE.setByteArrayValue(new byte[] {0, 1, 2, 3, 4, 5});
SIGNED_TEST_VALUE.setStringSet(
new HashSet<String>(Arrays.asList("Goodbye", "Cruel", "World", "?")));
SIGNED_TEST_VALUE.setIntSet(new HashSet<Integer>(Arrays.asList(1, 200, 10, 15, 0)));
UNTOUCHED_TEST_VALUE.setHashKey(7);
UNTOUCHED_TEST_VALUE.setRangeKey(9);
UNTOUCHED_TEST_VALUE.setVersion(0);
UNTOUCHED_TEST_VALUE.setIntValue(123);
UNTOUCHED_TEST_VALUE.setStringValue("Hello world!");
UNTOUCHED_TEST_VALUE.setByteArrayValue(new byte[] {0, 1, 2, 3, 4, 5});
UNTOUCHED_TEST_VALUE.setStringSet(
new HashSet<String>(Arrays.asList("Goodbye", "Cruel", "World", "?")));
UNTOUCHED_TEST_VALUE.setIntSet(new HashSet<Integer>(Arrays.asList(1, 200, 10, 15, 0)));
// Now storing doubles
ENCRYPTED_TEST_VALUE_2.setHashKey(5);
ENCRYPTED_TEST_VALUE_2.setRangeKey(7);
ENCRYPTED_TEST_VALUE_2.setVersion(0);
ENCRYPTED_TEST_VALUE_2.setIntValue(123);
ENCRYPTED_TEST_VALUE_2.setStringValue("Hello world!");
ENCRYPTED_TEST_VALUE_2.setByteArrayValue(new byte[] {0, 1, 2, 3, 4, 5});
ENCRYPTED_TEST_VALUE_2.setStringSet(
new HashSet<String>(Arrays.asList("Goodbye", "Cruel", "World", "?")));
ENCRYPTED_TEST_VALUE_2.setIntSet(new HashSet<Integer>(Arrays.asList(1, 200, 10, 15, 0)));
ENCRYPTED_TEST_VALUE_2.setDoubleValue(15);
ENCRYPTED_TEST_VALUE_2.setDoubleSet(
new HashSet<Double>(Arrays.asList(15.0D, 7.6D, -3D, -34.2D, 0.0D)));
MIXED_TEST_VALUE_2.setHashKey(6);
MIXED_TEST_VALUE_2.setRangeKey(8);
MIXED_TEST_VALUE_2.setVersion(0);
MIXED_TEST_VALUE_2.setIntValue(123);
MIXED_TEST_VALUE_2.setStringValue("Hello world!");
MIXED_TEST_VALUE_2.setByteArrayValue(new byte[] {0, 1, 2, 3, 4, 5});
MIXED_TEST_VALUE_2.setStringSet(
new HashSet<String>(Arrays.asList("Goodbye", "Cruel", "World", "?")));
MIXED_TEST_VALUE_2.setIntSet(new HashSet<Integer>(Arrays.asList(1, 200, 10, 15, 0)));
MIXED_TEST_VALUE_2.setDoubleValue(15);
MIXED_TEST_VALUE_2.setDoubleSet(
new HashSet<Double>(Arrays.asList(15.0D, 7.6D, -3D, -34.2D, 0.0D)));
SIGNED_TEST_VALUE_2.setHashKey(8);
SIGNED_TEST_VALUE_2.setRangeKey(10);
SIGNED_TEST_VALUE_2.setVersion(0);
SIGNED_TEST_VALUE_2.setIntValue(123);
SIGNED_TEST_VALUE_2.setStringValue("Hello world!");
SIGNED_TEST_VALUE_2.setByteArrayValue(new byte[] {0, 1, 2, 3, 4, 5});
SIGNED_TEST_VALUE_2.setStringSet(
new HashSet<String>(Arrays.asList("Goodbye", "Cruel", "World", "?")));
SIGNED_TEST_VALUE_2.setIntSet(new HashSet<Integer>(Arrays.asList(1, 200, 10, 15, 0)));
SIGNED_TEST_VALUE_2.setDoubleValue(15);
SIGNED_TEST_VALUE_2.setDoubleSet(
new HashSet<Double>(Arrays.asList(15.0D, 7.6D, -3D, -34.2D, 0.0D)));
UNTOUCHED_TEST_VALUE_2.setHashKey(7);
UNTOUCHED_TEST_VALUE_2.setRangeKey(9);
UNTOUCHED_TEST_VALUE_2.setVersion(0);
UNTOUCHED_TEST_VALUE_2.setIntValue(123);
UNTOUCHED_TEST_VALUE_2.setStringValue("Hello world!");
UNTOUCHED_TEST_VALUE_2.setByteArrayValue(new byte[] {0, 1, 2, 3, 4, 5});
UNTOUCHED_TEST_VALUE_2.setStringSet(
new HashSet<String>(Arrays.asList("Goodbye", "Cruel", "World", "?")));
UNTOUCHED_TEST_VALUE_2.setIntSet(new HashSet<Integer>(Arrays.asList(1, 200, 10, 15, 0)));
UNTOUCHED_TEST_VALUE_2.setDoubleValue(15);
UNTOUCHED_TEST_VALUE_2.setDoubleSet(
new HashSet<Double>(Arrays.asList(15.0D, 7.6D, -3D, -34.2D, 0.0D)));
}
@DataProvider(name = "getEncryptTestVectors")
public static Object[][] getEncryptTestVectors() throws IOException {
ScenarioManifest scenarioManifest =
getManifestFromFile(SCENARIO_MANIFEST_PATH, new TypeReference<ScenarioManifest>() {});
loadKeyData(scenarioManifest.keyDataPath);
// Only use Java generated test vectors to dedupe the scenarios for encrypt,
// we only care that we are able to generate data using the different provider configurations
List<Object[]> dedupedScenarios =
scenarioManifest.scenarios.stream()
.filter(s -> s.ciphertextPath.contains(JAVA_DIR))
.map(s -> new Object[] {s})
.collect(Collectors.toList());
return dedupedScenarios.toArray(new Object[dedupedScenarios.size()][]);
}
@DataProvider(name = "getDecryptTestVectors")
public static Object[][] getDecryptTestVectors() throws IOException {
ScenarioManifest scenarioManifest =
getManifestFromFile(SCENARIO_MANIFEST_PATH, new TypeReference<ScenarioManifest>() {});
loadKeyData(scenarioManifest.keyDataPath);
List<Object[]> scenarios =
scenarioManifest.scenarios.stream().map(s -> new Object[] {s}).collect(Collectors.toList());
return scenarios.toArray(new Object[scenarios.size()][]);
}
// Set up for non-parameterized tests
@BeforeTest
public void setUp() {
client = DynamoDBEmbedded.create().amazonDynamoDB();
// load data into ciphertext tables
createCiphertextTables(client);
}
@Test(dataProvider = "getDecryptTestVectors")
public void decryptTestVector(Scenario scenario) throws IOException {
client = DynamoDBEmbedded.create().amazonDynamoDB();
// load data into ciphertext tables
createCiphertextTables(client);
// load data from vector file
putDataFromFile(client, scenario.ciphertextPath);
// create and load metastore table if necessary
ProviderStore metastore = null;
if (scenario.metastore != null) {
MetaStore.createTable(
client, scenario.metastore.tableName, new ProvisionedThroughput(100L, 100L));
putDataFromFile(client, scenario.metastore.path);
EncryptionMaterialsProvider metaProvider =
createProvider(
scenario.metastore.providerName,
scenario.materialName,
scenario.metastore.keys,
null);
metastore =
new MetaStore(
client, scenario.metastore.tableName, DynamoDBEncryptor.getInstance(metaProvider));
}
// Create the mapper with the provider under test
EncryptionMaterialsProvider provider =
createProvider(scenario.providerName, scenario.materialName, scenario.keys, metastore);
DynamoDBMapper mapper =
new DynamoDBMapper(
client,
new DynamoDBMapperConfig(SaveBehavior.CLOBBER),
new AttributeEncryptor(provider));
// Verify successful decryption
switch (scenario.version) {
case "v0":
assertVersionCompatibility(mapper);
break;
case "v1":
assertVersionCompatibility_2(mapper);
break;
default:
throw new IllegalStateException(
"Version " + scenario.version + " not yet implemented in test vector runner");
}
}
// This runs the test vectors
// through the front door of the DDB-EC-Dafny.
@Test(dataProvider = "getDecryptTestVectors")
public void decryptLegacyTestVector(Scenario scenario) throws IOException {
client = DynamoDBEmbedded.create().amazonDynamoDB();
// load data into ciphertext tables
createCiphertextTables(client);
// load data from vector file
putDataFromFile(client, scenario.ciphertextPath);
// create and load metastore table if necessary
ProviderStore metastore = null;
if (scenario.metastore != null) {
MetaStore.createTable(
client, scenario.metastore.tableName, new ProvisionedThroughput(100L, 100L));
putDataFromFile(client, scenario.metastore.path);
EncryptionMaterialsProvider metaProvider =
createProvider(
scenario.metastore.providerName,
scenario.materialName,
scenario.metastore.keys,
null);
metastore =
new MetaStore(
client, scenario.metastore.tableName, DynamoDBEncryptor.getInstance(metaProvider));
}
// Create the mapper with the provider under test
EncryptionMaterialsProvider provider =
createProvider(scenario.providerName, scenario.materialName, scenario.keys, metastore);
final DynamoDBEncryptor legacyEncryptor = DynamoDBEncryptor.getInstance(provider);
// Verify successful decryption
switch (scenario.version) {
case "v0":
LegacyTestVectors.decryptBaseClassTestVector(client, legacyEncryptor, ENCRYPTED_TEST_VALUE);
LegacyTestVectors.decryptBaseClassTestVector(client, legacyEncryptor, MIXED_TEST_VALUE);
LegacyTestVectors.decryptBaseClassTestVector(client, legacyEncryptor, SIGNED_TEST_VALUE);
// The Encryptor can not decrypt an unencrypted record.
// However, the mapper can.
// This is why this vector exists but is not tested.
// assertTrue(LegacyTestVectors.testDecryptionTestVector(client, legacyEncryptor, UNTOUCHED_TEST_VALUE));
break;
case "v1":
LegacyTestVectors.decryptBaseClassTestVector(client, legacyEncryptor, ENCRYPTED_TEST_VALUE_2);
LegacyTestVectors.decryptBaseClassTestVector(client, legacyEncryptor, MIXED_TEST_VALUE_2);
LegacyTestVectors.decryptBaseClassTestVector(client, legacyEncryptor, SIGNED_TEST_VALUE_2);
// The Encryptor can not decrypt an unencrypted record.
// However, the mapper can.
// This is why this vector exists but is not tested.
// assertTrue(LegacyTestVectors.testDecryptionTestVector(client, legacyEncryptor, UNTOUCHED_TEST_VALUE_2));
break;
default:
throw new IllegalStateException(
"Version " + scenario.version + " not yet implemented in test vector runner");
}
LegacyTestVectors.decryptHashKeyOnlyTestVector(client, legacyEncryptor, "Foo");
LegacyTestVectors.decryptHashKeyOnlyTestVector(client, legacyEncryptor, "Bar");
LegacyTestVectors.decryptHashKeyOnlyTestVector(client, legacyEncryptor, "Baz");
for (int x = 1; x <= 3; ++x) {
LegacyTestVectors.decryptKeysOnlyTestVector(client,legacyEncryptor,0,x);
LegacyTestVectors.decryptKeysOnlyTestVector(client,legacyEncryptor,1,x);
LegacyTestVectors.decryptKeysOnlyTestVector(client,legacyEncryptor,4 + x,x);
}
}
@Test(dataProvider = "getEncryptTestVectors")
public void encryptWithTestVector(Scenario scenario) throws IOException {
client = DynamoDBEmbedded.create().amazonDynamoDB();;
// load data into ciphertext tables
createCiphertextTables(client);
// create and load metastore table if necessary
ProviderStore metastore = null;
if (scenario.metastore != null) {
MetaStore.createTable(
client, scenario.metastore.tableName, new ProvisionedThroughput(100L, 100L));
putDataFromFile(client, scenario.metastore.path);
EncryptionMaterialsProvider metaProvider =
createProvider(
scenario.metastore.providerName,
scenario.materialName,
scenario.metastore.keys,
null);
metastore =
new MetaStore(
client, scenario.metastore.tableName, DynamoDBEncryptor.getInstance(metaProvider));
}
// Encrypt data with the provider under test, only ensure that no exception is thrown
EncryptionMaterialsProvider provider =
createProvider(scenario.providerName, scenario.materialName, scenario.keys, metastore);
generateStandardData(provider);
}
@Test(dataProvider = "getEncryptTestVectors")
public void encryptWithLegacyTestVector(Scenario scenario) throws IOException {
client = DynamoDBEmbedded.create().amazonDynamoDB();;
// load data into ciphertext tables
createCiphertextTables(client);
// create and load metastore table if necessary
ProviderStore metastore = null;
if (scenario.metastore != null) {
MetaStore.createTable(
client, scenario.metastore.tableName, new ProvisionedThroughput(100L, 100L));
putDataFromFile(client, scenario.metastore.path);
EncryptionMaterialsProvider metaProvider =
createProvider(
scenario.metastore.providerName,
scenario.materialName,
scenario.metastore.keys,
null);
metastore =
new MetaStore(
client, scenario.metastore.tableName, DynamoDBEncryptor.getInstance(metaProvider));
}
// Encrypt data with the provider under test, only ensure that no exception is thrown
EncryptionMaterialsProvider provider =
createProvider(scenario.providerName, scenario.materialName, scenario.keys, metastore);
final DynamoDBEncryptor legacyEncryptor = DynamoDBEncryptor.getInstance(provider);
// First I encrypt and put the items into the database
// that I expect to exist on the decrypt side.
LegacyTestVectors.encryptAndPut(client, legacyEncryptor, ENCRYPTED_TEST_VALUE_2);
LegacyTestVectors.encryptAndPut(client, legacyEncryptor, MIXED_TEST_VALUE_2);
LegacyTestVectors.encryptAndPut(client, legacyEncryptor, SIGNED_TEST_VALUE_2);
LegacyTestVectors.encryptAndPut(client, legacyEncryptor, new HashKeyOnly("Foo"));
LegacyTestVectors.encryptAndPut(client, legacyEncryptor, new HashKeyOnly("Bar"));
LegacyTestVectors.encryptAndPut(client, legacyEncryptor, new HashKeyOnly("Baz"));
LegacyTestVectors.encryptAndPut(client, legacyEncryptor, new KeysOnly(0, 1));
LegacyTestVectors.encryptAndPut(client, legacyEncryptor, new KeysOnly(0, 2));
LegacyTestVectors.encryptAndPut(client, legacyEncryptor, new KeysOnly(0, 3));
LegacyTestVectors.encryptAndPut(client, legacyEncryptor, new KeysOnly(1, 1));
LegacyTestVectors.encryptAndPut(client, legacyEncryptor, new KeysOnly(1, 2));
LegacyTestVectors.encryptAndPut(client, legacyEncryptor, new KeysOnly(1, 3));
LegacyTestVectors.encryptAndPut(client, legacyEncryptor, new KeysOnly(5, 1));
LegacyTestVectors.encryptAndPut(client, legacyEncryptor, new KeysOnly(6, 2));
LegacyTestVectors.encryptAndPut(client, legacyEncryptor, new KeysOnly(7, 3));
// Now that all the items exist in the database
// I decrypt them all.
// This looks exactly like the decrypt test vectors
// this is **not** an accident.
LegacyTestVectors.decryptBaseClassTestVector(client, legacyEncryptor, ENCRYPTED_TEST_VALUE_2);
LegacyTestVectors.decryptBaseClassTestVector(client, legacyEncryptor, MIXED_TEST_VALUE_2);
LegacyTestVectors.decryptBaseClassTestVector(client, legacyEncryptor, SIGNED_TEST_VALUE_2);
LegacyTestVectors.decryptHashKeyOnlyTestVector(client, legacyEncryptor, "Foo");
LegacyTestVectors.decryptHashKeyOnlyTestVector(client, legacyEncryptor, "Bar");
LegacyTestVectors.decryptHashKeyOnlyTestVector(client, legacyEncryptor, "Baz");
for (int x = 1; x <= 3; ++x) {
LegacyTestVectors.decryptKeysOnlyTestVector(client,legacyEncryptor,0,x);
LegacyTestVectors.decryptKeysOnlyTestVector(client,legacyEncryptor,1,x);
LegacyTestVectors.decryptKeysOnlyTestVector(client,legacyEncryptor,4 + x,x);
}
}
@Test
public void simpleSaveLoad() {
DynamoDBMapper mapper =
new DynamoDBMapper(client, CLOBBER_CONFIG, new AttributeEncryptor(symProv));
Mixed obj = new Mixed();
obj.setHashKey(0);
obj.setRangeKey(15);
obj.setIntSet(new HashSet<Integer>());
obj.getIntSet().add(3);
obj.getIntSet().add(5);
obj.getIntSet().add(7);
obj.setDoubleValue(15);
obj.setStringValue("Blargh!");
obj.setDoubleSet(new HashSet<Double>(Arrays.asList(15.0D, 7.6D, -3D, -34.2D, 0.0D)));
mapper.save(obj);
Mixed result = mapper.load(Mixed.class, 0, 15);
assertEquals(obj, result);
result.setStringValue("Foo");
mapper.save(result);
Mixed result2 = mapper.load(Mixed.class, 0, 15);
assertEquals(result, result2);
mapper.delete(result);
assertNull(mapper.load(Mixed.class, 0, 15));
}
/**
* This test ensures that optimistic locking can be successfully done through the {@link
* DynamoDBMapper} when combined with the {@link AttributeEncryptor}. Specifically it checks that
* {@link SaveBehavior#PUT} properly enforces versioning and will result in a {@link
* ConditionalCheckFailedException} when optimistic locking should prevent a write. Finally, it
* checks that {@link SaveBehavior#CLOBBER} properly ignores optimistic locking and overwrites the
* old value.
*/
@Test
public void optimisticLockingTest() {
DynamoDBMapper mapper =
new DynamoDBMapper(
client,
DynamoDBMapperConfig.builder().withSaveBehavior(SaveBehavior.PUT).build(),
new AttributeEncryptor(symProv));
DynamoDBMapper clobberMapper =
new DynamoDBMapper(client, CLOBBER_CONFIG, new AttributeEncryptor(symProv));
/*
* Lineage of objects
* expected -> v1 -> v2 -> v3
* |
* -> v2_2 -> clobbered
* Splitting the lineage after v1 is what should
* cause the ConditionalCheckFailedException.
*/
final int hashKey = 0;
final int rangeKey = 15;
final Mixed expected = new Mixed();
expected.setHashKey(hashKey);
expected.setRangeKey(rangeKey);
expected.setIntSet(new HashSet<Integer>());
expected.getIntSet().add(3);
expected.getIntSet().add(5);
expected.getIntSet().add(7);
expected.setDoubleValue(15);
expected.setStringValue("Blargh!");
expected.setDoubleSet(new HashSet<Double>(Arrays.asList(15.0D, 7.6D, -3D, -34.2D, 0.0D)));
mapper.save(expected);
Mixed v1 = mapper.load(Mixed.class, hashKey, rangeKey);
assertEquals(expected, v1);
v1.setStringValue("New value");
mapper.save(v1);
Mixed v2 = mapper.load(Mixed.class, hashKey, rangeKey);
assertEquals(v1, v2);
Mixed v2_2 = mapper.load(Mixed.class, hashKey, rangeKey);
v2.getIntSet().add(-37);
mapper.save(v2);
Mixed v3 = mapper.load(Mixed.class, hashKey, rangeKey);
assertEquals(v2, v3);
assertTrue(v3.getIntSet().contains(-37));
// This should fail due to optimistic locking
v2_2.getIntSet().add(38);
try {
mapper.save(v2_2);
fail("Expected ConditionalCheckFailedException");
} catch (ConditionalCheckFailedException ex) {
// Expected exception
}
// Force the update with clobber
clobberMapper.save(v2_2);
Mixed clobbered = mapper.load(Mixed.class, hashKey, rangeKey);
assertEquals(v2_2, clobbered);
assertTrue(clobbered.getIntSet().contains(38));
assertFalse(clobbered.getIntSet().contains(-37));
}
@Test
public void leadingAndTrailingZeros() {
DynamoDBMapper mapper =
new DynamoDBMapper(client, CLOBBER_CONFIG, new AttributeEncryptor(symProv));
Mixed obj = new Mixed();
obj.setHashKey(0);
obj.setRangeKey(15);
obj.setIntSet(new HashSet<Integer>());
obj.getIntSet().add(3);
obj.getIntSet().add(5);
obj.getIntSet().add(7);
obj.setStringValue("Blargh!");
obj.setDoubleValue(15);
obj.setDoubleSet(new HashSet<Double>(Arrays.asList(15.0D, 7.6D, -3D, -34.2D, 0.0D)));
mapper.save(obj);
// DynamoDb discards leading and trailing zeros from numbers
Map<String, AttributeValue> key = new HashMap<String, AttributeValue>();
key.put(HASH_KEY, new AttributeValue().withN("0"));
key.put(RANGE_KEY, new AttributeValue().withN("15"));
Map<String, AttributeValueUpdate> attributeUpdates =
new HashMap<String, AttributeValueUpdate>();
attributeUpdates.put(
"doubleValue",
new AttributeValueUpdate(new AttributeValue().withN("15"), AttributeAction.PUT));
UpdateItemRequest update = new UpdateItemRequest("TableName", key, attributeUpdates);
client.updateItem(update);
Mixed result = mapper.load(Mixed.class, 0, 15);
assertEquals(obj, result);
result.setStringValue("Foo");
mapper.save(result);
Mixed result2 = mapper.load(Mixed.class, 0, 15);
assertEquals(result, result2);
mapper.delete(result);
assertNull(mapper.load(Mixed.class, 0, 15));
}
@Test
public void simpleSaveLoadAsym() {
DynamoDBMapper mapper =
new DynamoDBMapper(client, CLOBBER_CONFIG, new AttributeEncryptor(asymProv));
BaseClass obj = new BaseClass();
obj.setHashKey(0);
obj.setRangeKey(15);
obj.setIntSet(new HashSet<Integer>());
obj.getIntSet().add(3);
obj.getIntSet().add(5);
obj.getIntSet().add(7);
obj.setDoubleValue(15);
obj.setStringValue("Blargh!");
obj.setDoubleSet(new HashSet<Double>(Arrays.asList(15.0D, 7.6D, -3D, -34.2D, 0.0D)));
mapper.save(obj);
BaseClass result = mapper.load(BaseClass.class, 0, 15);
assertEquals(obj, result);
result.setStringValue("Foo");
mapper.save(result);
BaseClass result2 = mapper.load(BaseClass.class, 0, 15);
assertEquals(result, result2);
mapper.delete(result);
assertNull(mapper.load(BaseClass.class, 0, 15));
}
@Test
public void simpleSaveLoadHashOnly() {
DynamoDBMapper mapper =
new DynamoDBMapper(client, CLOBBER_CONFIG, new AttributeEncryptor(symProv));
HashKeyOnly obj = new HashKeyOnly("");
obj.setHashKey("Foo");
mapper.save(obj);
HashKeyOnly result = mapper.load(HashKeyOnly.class, "Foo");
assertEquals(obj, result);
mapper.delete(obj);
assertNull(mapper.load(BaseClass.class, 0, 15));
}
@Test
public void simpleSaveLoadKeysOnly() {
DynamoDBMapper mapper =
new DynamoDBMapper(client, CLOBBER_CONFIG, new AttributeEncryptor(asymProv));
KeysOnly obj = new KeysOnly();
obj.setHashKey(0);
obj.setRangeKey(15);
mapper.save(obj);
KeysOnly result = mapper.load(KeysOnly.class, 0, 15);
assertEquals(obj, result);
mapper.delete(obj);
assertNull(mapper.load(BaseClass.class, 0, 15));
}
public void generateStandardData(EncryptionMaterialsProvider prov) {
DynamoDBMapper mapper =
new DynamoDBMapper(
client, new DynamoDBMapperConfig(SaveBehavior.CLOBBER), new AttributeEncryptor(prov));
mapper.save(new HashKeyOnly("Foo"));
mapper.save(new HashKeyOnly("Bar"));
mapper.save(new HashKeyOnly("Baz"));
mapper.save(new KeysOnly(0, 1));
mapper.save(new KeysOnly(0, 2));
mapper.save(new KeysOnly(0, 3));
mapper.save(new KeysOnly(1, 1));
mapper.save(new KeysOnly(1, 2));
mapper.save(new KeysOnly(1, 3));
mapper.save(new KeysOnly(5, 1));
mapper.save(new KeysOnly(6, 2));
mapper.save(new KeysOnly(7, 3));
mapper.save(ENCRYPTED_TEST_VALUE_2);
mapper.save(MIXED_TEST_VALUE_2);
mapper.save(SIGNED_TEST_VALUE_2);
mapper.save(UNTOUCHED_TEST_VALUE_2);
// Uncomment the function below to print the generated data
// in our test vector format.
// printTablesAsTestVectors();
}
private void assertVersionCompatibility(DynamoDBMapper mapper) {
assertEquals(
UNTOUCHED_TEST_VALUE,
mapper.load(
UNTOUCHED_TEST_VALUE.getClass(),
UNTOUCHED_TEST_VALUE.getHashKey(),
UNTOUCHED_TEST_VALUE.getRangeKey()));
assertEquals(
SIGNED_TEST_VALUE,
mapper.load(
SIGNED_TEST_VALUE.getClass(),
SIGNED_TEST_VALUE.getHashKey(),
SIGNED_TEST_VALUE.getRangeKey()));
assertEquals(
MIXED_TEST_VALUE,
mapper.load(
MIXED_TEST_VALUE.getClass(),
MIXED_TEST_VALUE.getHashKey(),
MIXED_TEST_VALUE.getRangeKey()));
assertEquals(
ENCRYPTED_TEST_VALUE,
mapper.load(
ENCRYPTED_TEST_VALUE.getClass(),
ENCRYPTED_TEST_VALUE.getHashKey(),
ENCRYPTED_TEST_VALUE.getRangeKey()));
assertEquals("Foo", mapper.load(HashKeyOnly.class, "Foo").getHashKey());
assertEquals("Bar", mapper.load(HashKeyOnly.class, "Bar").getHashKey());
assertEquals("Baz", mapper.load(HashKeyOnly.class, "Baz").getHashKey());
for (int x = 1; x <= 3; ++x) {
KeysOnly obj = mapper.load(KeysOnly.class, 0, x);
assertEquals(0, obj.getHashKey());
assertEquals(x, obj.getRangeKey());
obj = mapper.load(KeysOnly.class, 1, x);
assertEquals(1, obj.getHashKey());
assertEquals(x, obj.getRangeKey());
obj = mapper.load(KeysOnly.class, 4 + x, x);
assertEquals(4 + x, obj.getHashKey());
assertEquals(x, obj.getRangeKey());
}
}
private void assertVersionCompatibility_2(DynamoDBMapper mapper) {
assertEquals(
UNTOUCHED_TEST_VALUE_2,
mapper.load(
UNTOUCHED_TEST_VALUE_2.getClass(),
UNTOUCHED_TEST_VALUE_2.getHashKey(),
UNTOUCHED_TEST_VALUE_2.getRangeKey()));
assertEquals(
SIGNED_TEST_VALUE_2,
mapper.load(
SIGNED_TEST_VALUE_2.getClass(),
SIGNED_TEST_VALUE_2.getHashKey(),
SIGNED_TEST_VALUE_2.getRangeKey()));
assertEquals(
MIXED_TEST_VALUE_2,
mapper.load(
MIXED_TEST_VALUE_2.getClass(),
MIXED_TEST_VALUE_2.getHashKey(),
MIXED_TEST_VALUE_2.getRangeKey()));
assertEquals(
ENCRYPTED_TEST_VALUE_2,
mapper.load(
ENCRYPTED_TEST_VALUE_2.getClass(),
ENCRYPTED_TEST_VALUE_2.getHashKey(),
ENCRYPTED_TEST_VALUE_2.getRangeKey()));
assertEquals("Foo", mapper.load(HashKeyOnly.class, "Foo").getHashKey());
assertEquals("Bar", mapper.load(HashKeyOnly.class, "Bar").getHashKey());
assertEquals("Baz", mapper.load(HashKeyOnly.class, "Baz").getHashKey());
for (int x = 1; x <= 3; ++x) {
KeysOnly obj = mapper.load(KeysOnly.class, 0, x);
assertEquals(0, obj.getHashKey());
assertEquals(x, obj.getRangeKey());
obj = mapper.load(KeysOnly.class, 1, x);
assertEquals(1, obj.getHashKey());
assertEquals(x, obj.getRangeKey());
obj = mapper.load(KeysOnly.class, 4 + x, x);
assertEquals(4 + x, obj.getHashKey());
assertEquals(x, obj.getRangeKey());
}
}
// Prints all current tables in the expected test vector format.
// You may need to edit the output to grab the tables you care about, or
// separate the tables into separate files for test vectors (metastores e.g.).
private void printTablesAsTestVectors() throws JsonProcessingException {
ObjectMapper mapper = new ObjectMapper();
SimpleModule module = new SimpleModule();
module.addSerializer(AttributeValue.class, new AttributeValueSerializer());
mapper.registerModule(module);
Map<String, List<Map<String, AttributeValue>>> testVector = new HashMap<>();
for (String table : client.listTables().getTableNames()) {
ScanResult scanResult;
Map<String, AttributeValue> lastKey = null;
do {
scanResult =
client.scan(new ScanRequest().withTableName(table).withExclusiveStartKey(lastKey));
lastKey = scanResult.getLastEvaluatedKey();
testVector.put(table, scanResult.getItems());
} while (lastKey != null);
}
String jsonResult = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(testVector);
System.out.println(jsonResult);
}
private EncryptionMaterialsProvider createProvider(
String providerName, String materialName, Keys keys, ProviderStore metastore) {
switch (providerName) {
case ScenarioManifest.MOST_RECENT_PROVIDER_NAME:
return new CachingMostRecentProvider(metastore, materialName, 1000);
case ScenarioManifest.STATIC_PROVIDER_NAME:
KeyData decryptKeyData = keyDataMap.get(keys.decryptName);
KeyData verifyKeyData = keyDataMap.get(keys.verifyName);
SecretKey decryptKey =
new SecretKeySpec(Base64.decode(decryptKeyData.material), decryptKeyData.algorithm);
SecretKey verifyKey =
new SecretKeySpec(Base64.decode(verifyKeyData.material), verifyKeyData.algorithm);
return new SymmetricStaticProvider(decryptKey, verifyKey);
case ScenarioManifest.WRAPPED_PROVIDER_NAME:
decryptKeyData = keyDataMap.get(keys.decryptName);
verifyKeyData = keyDataMap.get(keys.verifyName);
// This can be either the asymmetric provider, where we should test using it's explicit
// constructor,
// or a wrapped symmetric where we use the wrapped materials constructor.
if (decryptKeyData.keyType.equals(ScenarioManifest.SYMMETRIC_KEY_TYPE)) {
decryptKey =
new SecretKeySpec(Base64.decode(decryptKeyData.material), decryptKeyData.algorithm);
verifyKey =
new SecretKeySpec(Base64.decode(verifyKeyData.material), verifyKeyData.algorithm);
return new WrappedMaterialsProvider(decryptKey, decryptKey, verifyKey);
} else {
KeyData encryptKeyData = keyDataMap.get(keys.encryptName);
KeyData signKeyData = keyDataMap.get(keys.signName);
try {
// Hardcoded to use RSA for asymmetric keys. If we include vectors with a different
// asymmetric scheme this will need to be updated.
KeyFactory rsaFact = KeyFactory.getInstance(RSA);
PublicKey encryptMaterial =
rsaFact.generatePublic(
new X509EncodedKeySpec(Base64.decode(encryptKeyData.material)));
PrivateKey decryptMaterial =
rsaFact.generatePrivate(
new PKCS8EncodedKeySpec(Base64.decode(decryptKeyData.material)));
KeyPair decryptPair = new KeyPair(encryptMaterial, decryptMaterial);
PublicKey verifyMaterial =
rsaFact.generatePublic(
new X509EncodedKeySpec(Base64.decode(verifyKeyData.material)));
PrivateKey signingMaterial =
rsaFact.generatePrivate(
new PKCS8EncodedKeySpec(Base64.decode(signKeyData.material)));
KeyPair sigPair = new KeyPair(verifyMaterial, signingMaterial);
return new AsymmetricStaticProvider(decryptPair, sigPair);
} catch (GeneralSecurityException ex) {
throw new RuntimeException(ex);
}
}
case ScenarioManifest.AWS_KMS_PROVIDER_NAME:
return new DirectKmsMaterialProvider(kmsClient, keyDataMap.get(keys.decryptName).keyId);
default:
throw new IllegalStateException(
"Provider " + providerName + " not yet implemented in test vector runner");
}
}
// Create empty tables for the ciphertext.
// The underlying structure to these tables is hardcoded,
// and we run all test vectors assuming the ciphertext matches the key schema for these tables.
private void createCiphertextTables(AmazonDynamoDB client) {
ArrayList<AttributeDefinition> attrDef = new ArrayList<AttributeDefinition>();
attrDef.add(
new AttributeDefinition()
.withAttributeName(HASH_KEY)
.withAttributeType(ScalarAttributeType.N));
attrDef.add(
new AttributeDefinition()
.withAttributeName(RANGE_KEY)
.withAttributeType(ScalarAttributeType.N));
ArrayList<KeySchemaElement> keySchema = new ArrayList<KeySchemaElement>();
keySchema.add(new KeySchemaElement().withAttributeName(HASH_KEY).withKeyType(KeyType.HASH));
keySchema.add(new KeySchemaElement().withAttributeName(RANGE_KEY).withKeyType(KeyType.RANGE));
client.createTable(
new CreateTableRequest()
.withTableName("TableName")
.withAttributeDefinitions(attrDef)
.withKeySchema(keySchema)
.withProvisionedThroughput(new ProvisionedThroughput(100L, 100L)));
attrDef = new ArrayList<AttributeDefinition>();
attrDef.add(
new AttributeDefinition()
.withAttributeName(HASH_KEY)
.withAttributeType(ScalarAttributeType.S));
keySchema = new ArrayList<KeySchemaElement>();
keySchema.add(new KeySchemaElement().withAttributeName(HASH_KEY).withKeyType(KeyType.HASH));
client.createTable(
new CreateTableRequest()
.withTableName("HashKeyOnly")
.withAttributeDefinitions(attrDef)
.withKeySchema(keySchema)
.withProvisionedThroughput(new ProvisionedThroughput(100L, 100L)));
attrDef = new ArrayList<AttributeDefinition>();
attrDef.add(
new AttributeDefinition()
.withAttributeName(HASH_KEY)
.withAttributeType(ScalarAttributeType.B));
attrDef.add(
new AttributeDefinition()
.withAttributeName(RANGE_KEY)
.withAttributeType(ScalarAttributeType.N));
keySchema = new ArrayList<KeySchemaElement>();
keySchema.add(new KeySchemaElement().withAttributeName(HASH_KEY).withKeyType(KeyType.HASH));
keySchema.add(new KeySchemaElement().withAttributeName(RANGE_KEY).withKeyType(KeyType.RANGE));
client.createTable(
new CreateTableRequest()
.withTableName("DeterministicTable")
.withAttributeDefinitions(attrDef)
.withKeySchema(keySchema)
.withProvisionedThroughput(new ProvisionedThroughput(100L, 100L)));
}
// Given a file in the test vector ciphertext format, put those entries into their tables.
// This assumes the expected tables have already been created.
private void putDataFromFile(AmazonDynamoDB client, String filename) throws IOException {
Map<String, List<Map<String, AttributeValue>>> manifest =
getCiphertextManifestFromFile(filename);
for (String tableName : manifest.keySet()) {
for (Map<String, AttributeValue> attributes : manifest.get(tableName)) {
client.putItem(new PutItemRequest(tableName, attributes));
}
}
}
private Map<String, List<Map<String, AttributeValue>>> getCiphertextManifestFromFile(
String filename) throws IOException {
return getManifestFromFile(
TEST_VECTOR_MANIFEST_DIR + stripFilePath(filename),
new TypeReference<Map<String, List<Map<String, DeserializedAttributeValue>>>>() {});
}
private static <T> T getManifestFromFile(String filename, TypeReference typeRef)
throws IOException {
final URL url = TransformerHolisticIT.class.getResource(filename);
if (url == null) {
throw new IllegalStateException("Missing file " + filename + " in src/test/resources.");
}
final File manifestFile = new File(url.getPath());
final ObjectMapper manifestMapper = new ObjectMapper();
return (T) manifestMapper.readValue(manifestFile, typeRef);
}
private static void loadKeyData(String filename) throws IOException {
keyDataMap =
getManifestFromFile(
TEST_VECTOR_MANIFEST_DIR + stripFilePath(filename),
new TypeReference<Map<String, KeyData>>() {});
}
private static String stripFilePath(String path) {
return path.replaceFirst("file://", "");
}
@JsonDeserialize(using = AttributeValueDeserializer.class)
public static class DeserializedAttributeValue extends AttributeValue {}
}
| 5,004 |
0 | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/sdkv1/com/amazonaws/services/dynamodbv2 | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/sdkv1/com/amazonaws/services/dynamodbv2/datamodeling/AttributeEncryptorTest.java | /*
* Copyright 2014 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.services.dynamodbv2.datamodeling;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertNotNull;
import static org.testng.AssertJUnit.assertNull;
import static org.testng.AssertJUnit.assertTrue;
import com.amazonaws.services.dynamodbv2.datamodeling.AttributeTransformer.Parameters;
import com.amazonaws.services.dynamodbv2.datamodeling.encryption.providers.EncryptionMaterialsProvider;
import com.amazonaws.services.dynamodbv2.datamodeling.encryption.providers.SymmetricStaticProvider;
import com.amazonaws.services.dynamodbv2.datamodeling.internal.Utils;
import com.amazonaws.services.dynamodbv2.model.AttributeValue;
import com.amazonaws.services.dynamodbv2.testing.AttrMatcher;
import com.amazonaws.services.dynamodbv2.testing.FakeParameters;
import com.amazonaws.services.dynamodbv2.testing.types.BaseClass;
import com.amazonaws.services.dynamodbv2.testing.types.BaseClassWithNewAttribute;
import com.amazonaws.services.dynamodbv2.testing.types.BaseClassWithUnknownAttributeAnnotation;
import com.amazonaws.services.dynamodbv2.testing.types.DoNotEncryptField;
import com.amazonaws.services.dynamodbv2.testing.types.DoNotTouchField;
import com.amazonaws.services.dynamodbv2.testing.types.Mixed;
import com.amazonaws.services.dynamodbv2.testing.types.SignOnly;
import com.amazonaws.services.dynamodbv2.testing.types.SignOnlyWithUnknownAttributeAnnotation;
import com.amazonaws.services.dynamodbv2.testing.types.SignOnlyWithUnknownAttributeAnnotationWithNewAttribute;
import com.amazonaws.services.dynamodbv2.testing.types.TableOverride;
import com.amazonaws.services.dynamodbv2.testing.types.Untouched;
import com.amazonaws.services.dynamodbv2.testing.types.UntouchedWithNewAttribute;
import com.amazonaws.services.dynamodbv2.testing.types.UntouchedWithUnknownAttributeAnnotation;
import com.amazonaws.services.dynamodbv2.testing.types.UntouchedWithUnknownAttributeAnnotationWithNewAttribute;
import java.nio.ByteBuffer;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import org.testng.Assert;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
public class AttributeEncryptorTest {
private static final String RANGE_KEY = "rangeKey";
private static final String HASH_KEY = "hashKey";
private static final String TABLE_NAME = "TableName";
private static SecretKey encryptionKey;
private static SecretKey macKey;
private EncryptionMaterialsProvider prov;
private AttributeEncryptor encryptor;
private Map<String, AttributeValue> attribs;
@BeforeClass
public static void setUpClass() throws Exception {
KeyGenerator aesGen = KeyGenerator.getInstance("AES");
aesGen.init(128, Utils.getRng());
encryptionKey = aesGen.generateKey();
KeyGenerator macGen = KeyGenerator.getInstance("HmacSHA256");
macGen.init(256, Utils.getRng());
macKey = macGen.generateKey();
}
@BeforeMethod
public void setUp() throws Exception {
prov =
new SymmetricStaticProvider(encryptionKey, macKey, Collections.<String, String>emptyMap());
encryptor = new AttributeEncryptor(prov);
attribs = new HashMap<String, AttributeValue>();
attribs.put("intValue", new AttributeValue().withN("123"));
attribs.put("stringValue", new AttributeValue().withS("Hello world!"));
attribs.put(
"byteArrayValue",
new AttributeValue().withB(ByteBuffer.wrap(new byte[] {0, 1, 2, 3, 4, 5})));
attribs.put("stringSet", new AttributeValue().withSS("Goodbye", "Cruel", "World", "?"));
attribs.put("intSet", new AttributeValue().withNS("1", "200", "10", "15", "0"));
attribs.put(HASH_KEY, new AttributeValue().withN("5"));
attribs.put(RANGE_KEY, new AttributeValue().withN("7"));
attribs.put("version", new AttributeValue().withN("0"));
}
@Test
public void testUnaffected() {
Parameters<Untouched> params =
FakeParameters.getInstance(Untouched.class, attribs, null, TABLE_NAME, HASH_KEY, RANGE_KEY);
Map<String, AttributeValue> encryptedAttributes = encryptor.transform(params);
assertEquals(attribs, encryptedAttributes);
}
@Test
public void fullEncryption() {
Parameters<BaseClass> params =
FakeParameters.getInstance(BaseClass.class, attribs, null, TABLE_NAME, HASH_KEY, RANGE_KEY);
Map<String, AttributeValue> encryptedAttributes = encryptor.transform(params);
assertThat(encryptedAttributes, AttrMatcher.invert(attribs));
params =
FakeParameters.getInstance(
BaseClass.class, encryptedAttributes, null, TABLE_NAME, HASH_KEY, RANGE_KEY);
Map<String, AttributeValue> decryptedAttributes = encryptor.untransform(params);
assertThat(decryptedAttributes, AttrMatcher.match(attribs));
// Make sure keys and version are not encrypted
assertAttrEquals(attribs.get(HASH_KEY), encryptedAttributes.get(HASH_KEY));
assertAttrEquals(attribs.get(RANGE_KEY), encryptedAttributes.get(RANGE_KEY));
assertAttrEquals(attribs.get("version"), encryptedAttributes.get("version"));
// Make sure String has been encrypted (we'll assume the others are correct as well)
assertTrue(encryptedAttributes.containsKey("stringValue"));
assertNull(encryptedAttributes.get("stringValue").getS());
assertNotNull(encryptedAttributes.get("stringValue").getB());
}
@Test(expectedExceptions = DynamoDBMappingException.class)
public void rejectsPartialUpdate() {
Parameters<BaseClass> params =
FakeParameters.getInstance(
BaseClass.class, attribs, null, TABLE_NAME, HASH_KEY, RANGE_KEY, true);
encryptor.transform(params);
}
@Test(expectedExceptions = DynamoDBMappingException.class)
public void fullEncryptionBadSignature() {
Parameters<BaseClass> params =
FakeParameters.getInstance(BaseClass.class, attribs, null, TABLE_NAME, HASH_KEY, RANGE_KEY);
Map<String, AttributeValue> encryptedAttributes = encryptor.transform(params);
assertThat(encryptedAttributes, AttrMatcher.invert(attribs));
encryptedAttributes.get(HASH_KEY).setN("666");
params =
FakeParameters.getInstance(
BaseClass.class, encryptedAttributes, null, TABLE_NAME, HASH_KEY, RANGE_KEY);
encryptor.untransform(params);
}
@Test(expectedExceptions = DynamoDBMappingException.class)
public void badVersionNumber() {
Parameters<BaseClass> params =
FakeParameters.getInstance(BaseClass.class, attribs, null, TABLE_NAME, HASH_KEY, RANGE_KEY);
Map<String, AttributeValue> encryptedAttributes = encryptor.transform(params);
ByteBuffer materialDescription =
encryptedAttributes.get(encryptor.getEncryptor().getMaterialDescriptionFieldName()).getB();
byte[] rawArray = materialDescription.array();
assertEquals(0, rawArray[0]); // This will need to be kept in sync with the current version.
rawArray[0] = 100;
encryptedAttributes.put(
encryptor.getEncryptor().getMaterialDescriptionFieldName(),
new AttributeValue().withB(ByteBuffer.wrap(rawArray)));
params =
FakeParameters.getInstance(
BaseClass.class, encryptedAttributes, null, TABLE_NAME, HASH_KEY, RANGE_KEY);
encryptor.untransform(params);
}
@Test
public void signedOnly() {
Parameters<SignOnly> params =
FakeParameters.getInstance(SignOnly.class, attribs, null, TABLE_NAME, HASH_KEY, RANGE_KEY);
Map<String, AttributeValue> encryptedAttributes = encryptor.transform(params);
assertThat(encryptedAttributes, AttrMatcher.invert(attribs));
params =
FakeParameters.getInstance(
SignOnly.class, encryptedAttributes, null, TABLE_NAME, HASH_KEY, RANGE_KEY);
Map<String, AttributeValue> decryptedAttributes = encryptor.untransform(params);
assertThat(decryptedAttributes, AttrMatcher.match(attribs));
// Make sure keys and version are not encrypted
assertAttrEquals(attribs.get(HASH_KEY), encryptedAttributes.get(HASH_KEY));
assertAttrEquals(attribs.get(RANGE_KEY), encryptedAttributes.get(RANGE_KEY));
assertAttrEquals(attribs.get("version"), encryptedAttributes.get("version"));
// Make sure String has not been encrypted (we'll assume the others are correct as well)
assertAttrEquals(attribs.get("stringValue"), encryptedAttributes.get("stringValue"));
}
@Test
public void signedOnlyNullCryptoKey() {
prov = new SymmetricStaticProvider(null, macKey, Collections.<String, String>emptyMap());
encryptor = new AttributeEncryptor(prov);
Parameters<SignOnly> params =
FakeParameters.getInstance(SignOnly.class, attribs, null, TABLE_NAME, HASH_KEY, RANGE_KEY);
Map<String, AttributeValue> encryptedAttributes = encryptor.transform(params);
assertThat(encryptedAttributes, AttrMatcher.invert(attribs));
params =
FakeParameters.getInstance(
SignOnly.class, encryptedAttributes, null, TABLE_NAME, HASH_KEY, RANGE_KEY);
Map<String, AttributeValue> decryptedAttributes = encryptor.untransform(params);
assertThat(decryptedAttributes, AttrMatcher.match(attribs));
// Make sure keys and version are not encrypted
assertAttrEquals(attribs.get(HASH_KEY), encryptedAttributes.get(HASH_KEY));
assertAttrEquals(attribs.get(RANGE_KEY), encryptedAttributes.get(RANGE_KEY));
assertAttrEquals(attribs.get("version"), encryptedAttributes.get("version"));
// Make sure String has not been encrypted (we'll assume the others are correct as well)
assertAttrEquals(attribs.get("stringValue"), encryptedAttributes.get("stringValue"));
}
@Test(expectedExceptions = DynamoDBMappingException.class)
public void signedOnlyBadSignature() {
Parameters<SignOnly> params =
FakeParameters.getInstance(SignOnly.class, attribs, null, TABLE_NAME, HASH_KEY, RANGE_KEY);
Map<String, AttributeValue> encryptedAttributes = encryptor.transform(params);
assertThat(encryptedAttributes, AttrMatcher.invert(attribs));
encryptedAttributes.get(HASH_KEY).setN("666");
params =
FakeParameters.getInstance(
SignOnly.class, encryptedAttributes, null, TABLE_NAME, HASH_KEY, RANGE_KEY);
encryptor.untransform(params);
}
@Test(expectedExceptions = DynamoDBMappingException.class)
public void signedOnlyNoSignature() {
Parameters<SignOnly> params =
FakeParameters.getInstance(SignOnly.class, attribs, null, TABLE_NAME, HASH_KEY, RANGE_KEY);
Map<String, AttributeValue> encryptedAttributes = encryptor.transform(params);
assertThat(encryptedAttributes, AttrMatcher.invert(attribs));
encryptedAttributes.remove(encryptor.getEncryptor().getSignatureFieldName());
encryptor.untransform(params);
}
@Test
public void RsaSignedOnly() throws NoSuchAlgorithmException {
KeyPairGenerator rsaGen = KeyPairGenerator.getInstance("RSA");
rsaGen.initialize(2048, Utils.getRng());
KeyPair sigPair = rsaGen.generateKeyPair();
encryptor =
new AttributeEncryptor(
new SymmetricStaticProvider(
encryptionKey, sigPair, Collections.<String, String>emptyMap()));
Parameters<SignOnly> params =
FakeParameters.getInstance(SignOnly.class, attribs, null, TABLE_NAME, HASH_KEY, RANGE_KEY);
Map<String, AttributeValue> encryptedAttributes = encryptor.transform(params);
assertThat(encryptedAttributes, AttrMatcher.invert(attribs));
params =
FakeParameters.getInstance(
SignOnly.class, encryptedAttributes, null, TABLE_NAME, HASH_KEY, RANGE_KEY);
Map<String, AttributeValue> decryptedAttributes = encryptor.untransform(params);
assertThat(decryptedAttributes, AttrMatcher.match(attribs));
// Make sure keys and version are not encrypted
assertAttrEquals(attribs.get(HASH_KEY), encryptedAttributes.get(HASH_KEY));
assertAttrEquals(attribs.get(RANGE_KEY), encryptedAttributes.get(RANGE_KEY));
assertAttrEquals(attribs.get("version"), encryptedAttributes.get("version"));
// Make sure String has not been encrypted (we'll assume the others are correct as well)
assertAttrEquals(attribs.get("stringValue"), encryptedAttributes.get("stringValue"));
}
@Test(expectedExceptions = DynamoDBMappingException.class)
public void RsaSignedOnlyBadSignature() throws NoSuchAlgorithmException {
KeyPairGenerator rsaGen = KeyPairGenerator.getInstance("RSA");
rsaGen.initialize(2048, Utils.getRng());
KeyPair sigPair = rsaGen.generateKeyPair();
encryptor =
new AttributeEncryptor(
new SymmetricStaticProvider(
encryptionKey, sigPair, Collections.<String, String>emptyMap()));
Parameters<SignOnly> params =
FakeParameters.getInstance(SignOnly.class, attribs, null, TABLE_NAME, HASH_KEY, RANGE_KEY);
Map<String, AttributeValue> encryptedAttributes = encryptor.transform(params);
assertThat(encryptedAttributes, AttrMatcher.invert(attribs));
encryptedAttributes.get(HASH_KEY).setN("666");
params =
FakeParameters.getInstance(
SignOnly.class, encryptedAttributes, null, TABLE_NAME, HASH_KEY, RANGE_KEY);
encryptor.untransform(params);
}
@Test
public void mixed() {
Parameters<Mixed> params =
FakeParameters.getInstance(Mixed.class, attribs, null, TABLE_NAME, HASH_KEY, RANGE_KEY);
Map<String, AttributeValue> encryptedAttributes = encryptor.transform(params);
assertThat(encryptedAttributes, AttrMatcher.invert(attribs));
params =
FakeParameters.getInstance(
Mixed.class, encryptedAttributes, null, TABLE_NAME, HASH_KEY, RANGE_KEY);
Map<String, AttributeValue> decryptedAttributes = encryptor.untransform(params);
assertThat(decryptedAttributes, AttrMatcher.match(attribs));
// Make sure keys and version are not encrypted
assertAttrEquals(attribs.get(HASH_KEY), encryptedAttributes.get(HASH_KEY));
assertAttrEquals(attribs.get(RANGE_KEY), encryptedAttributes.get(RANGE_KEY));
assertAttrEquals(attribs.get("version"), encryptedAttributes.get("version"));
// Make sure StringSet has been encrypted (we'll assume the others are correct as well)
assertTrue(encryptedAttributes.containsKey("stringSet"));
assertNull(encryptedAttributes.get("stringSet").getSS());
assertNotNull(encryptedAttributes.get("stringSet").getB());
// Test those not encrypted
assertAttrEquals(attribs.get("stringValue"), encryptedAttributes.get("stringValue"));
assertAttrEquals(attribs.get("intValue"), encryptedAttributes.get("intValue"));
// intValue is not signed, make sure we can modify it and still decrypt
encryptedAttributes.get("intValue").setN("666");
params =
FakeParameters.getInstance(
Mixed.class, encryptedAttributes, null, TABLE_NAME, HASH_KEY, RANGE_KEY);
decryptedAttributes = encryptor.untransform(params);
assertThat(decryptedAttributes, AttrMatcher.match(attribs));
}
@Test(expectedExceptions = DynamoDBMappingException.class)
public void mixedBadSignature() {
Parameters<Mixed> params =
FakeParameters.getInstance(Mixed.class, attribs, null, TABLE_NAME, HASH_KEY, RANGE_KEY);
Map<String, AttributeValue> encryptedAttributes = encryptor.transform(params);
assertThat(encryptedAttributes, AttrMatcher.invert(attribs));
encryptedAttributes.get("stringValue").setS("666");
params =
FakeParameters.getInstance(
Mixed.class, encryptedAttributes, null, TABLE_NAME, HASH_KEY, RANGE_KEY);
encryptor.untransform(params);
}
@Test(expectedExceptions = DynamoDBMappingException.class)
public void tableNameRespected() {
Parameters<BaseClass> params =
FakeParameters.getInstance(
BaseClass.class, attribs, null, "firstTable", HASH_KEY, RANGE_KEY);
Map<String, AttributeValue> encryptedAttributes = encryptor.transform(params);
assertThat(encryptedAttributes, AttrMatcher.invert(attribs));
params =
FakeParameters.getInstance(
BaseClass.class, encryptedAttributes, null, "secondTable", HASH_KEY, RANGE_KEY);
encryptor.untransform(params);
}
@Test
public void tableNameOverridden() {
Parameters<TableOverride> params =
FakeParameters.getInstance(
TableOverride.class, attribs, null, "firstTable", HASH_KEY, RANGE_KEY);
Map<String, AttributeValue> encryptedAttributes = encryptor.transform(params);
assertThat(encryptedAttributes, AttrMatcher.invert(attribs));
params =
FakeParameters.getInstance(
TableOverride.class, encryptedAttributes, null, "secondTable", HASH_KEY, RANGE_KEY);
encryptor.untransform(params);
Map<String, AttributeValue> decryptedAttributes = encryptor.untransform(params);
assertThat(decryptedAttributes, AttrMatcher.match(attribs));
}
@Test(expectedExceptions = DynamoDBMappingException.class)
public void testUnknownAttributeFails() {
Map<String, AttributeValue> attributes = new HashMap<>(attribs);
attributes.put("newAttribute", new AttributeValue().withS("foobar"));
Parameters<? extends BaseClass> params =
FakeParameters.getInstance(
BaseClassWithNewAttribute.class, attributes, null, TABLE_NAME, HASH_KEY, RANGE_KEY);
Map<String, AttributeValue> encryptedAttributes = encryptor.transform(params);
assertThat(encryptedAttributes, AttrMatcher.invert(attributes));
params =
FakeParameters.getInstance(
BaseClass.class, encryptedAttributes, null, TABLE_NAME, HASH_KEY, RANGE_KEY);
encryptor.untransform(params);
}
@Test
public void testUntouchedWithUnknownAttribute() {
Map<String, AttributeValue> attributes = new HashMap<>(attribs);
attributes.put("newAttribute", new AttributeValue().withS("foobar"));
Parameters<? extends Untouched> params =
FakeParameters.getInstance(
UntouchedWithNewAttribute.class, attributes, null, TABLE_NAME, HASH_KEY, RANGE_KEY);
Map<String, AttributeValue> encryptedAttributes = encryptor.transform(params);
assertThat(encryptedAttributes, AttrMatcher.match(attributes));
params =
FakeParameters.getInstance(
Untouched.class, encryptedAttributes, null, TABLE_NAME, HASH_KEY, RANGE_KEY);
Map<String, AttributeValue> decryptedAttributes = encryptor.untransform(params);
assertThat(decryptedAttributes, AttrMatcher.match(attributes));
}
@Test
public void testUntouchedWithUnknownAttributeAnnotation() {
Map<String, AttributeValue> attributes = new HashMap<>(attribs);
attributes.put("newAttribute", new AttributeValue().withS("foobar"));
Parameters<? extends UntouchedWithUnknownAttributeAnnotation> params =
FakeParameters.getInstance(
UntouchedWithUnknownAttributeAnnotationWithNewAttribute.class,
attributes,
null,
TABLE_NAME,
HASH_KEY,
RANGE_KEY);
Map<String, AttributeValue> encryptedAttributes = encryptor.transform(params);
assertThat(encryptedAttributes, AttrMatcher.match(attributes));
params =
FakeParameters.getInstance(
UntouchedWithUnknownAttributeAnnotation.class,
encryptedAttributes,
null,
TABLE_NAME,
HASH_KEY,
RANGE_KEY);
Map<String, AttributeValue> decryptedAttributes = encryptor.untransform(params);
assertThat(decryptedAttributes, AttrMatcher.match(attributes));
}
@Test
public void testSignOnlyWithUnknownAttributeAnnotation() {
Map<String, AttributeValue> attributes = new HashMap<>(attribs);
attributes.put("newAttribute", new AttributeValue().withS("foobar"));
Parameters<? extends SignOnlyWithUnknownAttributeAnnotation> params =
FakeParameters.getInstance(
SignOnlyWithUnknownAttributeAnnotationWithNewAttribute.class,
attributes,
null,
TABLE_NAME,
HASH_KEY,
RANGE_KEY);
Map<String, AttributeValue> encryptedAttributes = encryptor.transform(params);
assertThat(encryptedAttributes, AttrMatcher.invert(attributes));
assertAttrEquals(new AttributeValue().withS("foobar"), encryptedAttributes.get("newAttribute"));
params =
FakeParameters.getInstance(
SignOnlyWithUnknownAttributeAnnotation.class,
encryptedAttributes,
null,
TABLE_NAME,
HASH_KEY,
RANGE_KEY);
Map<String, AttributeValue> decryptedAttributes = encryptor.untransform(params);
assertThat(decryptedAttributes, AttrMatcher.match(attributes));
}
@Test(expectedExceptions = DynamoDBMappingException.class)
public void testSignOnlyWithUnknownAttributeAnnotationBadSignature() {
Map<String, AttributeValue> attributes = new HashMap<>(attribs);
attributes.put("newAttribute", new AttributeValue().withS("foo"));
Parameters<? extends SignOnlyWithUnknownAttributeAnnotation> params =
FakeParameters.getInstance(
SignOnlyWithUnknownAttributeAnnotationWithNewAttribute.class,
attributes,
null,
TABLE_NAME,
HASH_KEY,
RANGE_KEY);
Map<String, AttributeValue> encryptedAttributes = encryptor.transform(params);
assertThat(encryptedAttributes, AttrMatcher.invert(attributes));
assertAttrEquals(new AttributeValue().withS("foo"), encryptedAttributes.get("newAttribute"));
params =
FakeParameters.getInstance(
SignOnlyWithUnknownAttributeAnnotation.class,
encryptedAttributes,
null,
TABLE_NAME,
HASH_KEY,
RANGE_KEY);
encryptedAttributes.get("newAttribute").setS("bar");
encryptor.untransform(params);
}
@Test
public void testEncryptWithUnknownAttributeAnnotation() {
Map<String, AttributeValue> attributes = new HashMap<>(attribs);
attributes.put("newAttribute", new AttributeValue().withS("foo"));
Parameters<? extends BaseClassWithUnknownAttributeAnnotation> params =
FakeParameters.getInstance(
BaseClassWithNewAttribute.class, attributes, null, TABLE_NAME, HASH_KEY, RANGE_KEY);
Map<String, AttributeValue> encryptedAttributes = encryptor.transform(params);
assertThat(encryptedAttributes, AttrMatcher.invert(attributes));
params =
FakeParameters.getInstance(
BaseClassWithUnknownAttributeAnnotation.class,
encryptedAttributes,
null,
TABLE_NAME,
HASH_KEY,
RANGE_KEY);
Map<String, AttributeValue> decryptedAttributes = encryptor.untransform(params);
assertThat(decryptedAttributes, AttrMatcher.match(attributes));
}
@Test(expectedExceptions = DynamoDBMappingException.class)
public void testEncryptWithUnknownAttributeAnnotationBadSignature() {
Map<String, AttributeValue> attributes = new HashMap<>(attribs);
attributes.put("newAttribute", new AttributeValue().withS("foo"));
Parameters<? extends BaseClassWithUnknownAttributeAnnotation> params =
FakeParameters.getInstance(
BaseClassWithNewAttribute.class, attributes, null, TABLE_NAME, HASH_KEY, RANGE_KEY);
Map<String, AttributeValue> encryptedAttributes = encryptor.transform(params);
assertThat(encryptedAttributes, AttrMatcher.invert(attributes));
params =
FakeParameters.getInstance(
BaseClassWithUnknownAttributeAnnotation.class,
encryptedAttributes,
null,
TABLE_NAME,
HASH_KEY,
RANGE_KEY);
encryptedAttributes.get("newAttribute").setB(ByteBuffer.allocate(0));
encryptor.untransform(params);
}
@Test
public void testEncryptWithFieldLevelDoNotEncryptAnnotation() {
Map<String, AttributeValue> attributes = new HashMap<>(attribs);
attributes.put("value", new AttributeValue().withN("100"));
Parameters<? extends DoNotEncryptField> params =
FakeParameters.getInstance(
DoNotEncryptField.class, attributes, null, TABLE_NAME, HASH_KEY, RANGE_KEY);
Map<String, AttributeValue> encryptedAttributes = encryptor.transform(params);
assertThat(encryptedAttributes, AttrMatcher.invert(attributes));
assertAttrEquals(attributes.get("value"), encryptedAttributes.get("value"));
params =
FakeParameters.getInstance(
DoNotEncryptField.class, encryptedAttributes, null, TABLE_NAME, HASH_KEY, RANGE_KEY);
Map<String, AttributeValue> decryptedAttributes = encryptor.untransform(params);
assertThat(decryptedAttributes, AttrMatcher.match(attributes));
}
@Test
public void testEncryptWithFieldLevelDoNotEncryptAnnotationWithChangedDoNotTouchSuperClass() {
Map<String, AttributeValue> attributes = new HashMap<>(attribs);
attributes.put("value", new AttributeValue().withN("100"));
Parameters<? extends DoNotEncryptField> params =
FakeParameters.getInstance(
DoNotEncryptField.class, attributes, null, TABLE_NAME, HASH_KEY, RANGE_KEY);
Map<String, AttributeValue> encryptedAttributes = encryptor.transform(params);
assertThat(encryptedAttributes, AttrMatcher.invert(attributes));
assertAttrEquals(attributes.get("value"), encryptedAttributes.get("value"));
params =
FakeParameters.getInstance(
DoNotEncryptField.class, encryptedAttributes, null, TABLE_NAME, HASH_KEY, RANGE_KEY);
// Change a DoNotTouch value on Mixed super class
encryptedAttributes.put("intValue", new AttributeValue().withN("666"));
Map<String, AttributeValue> decryptedAttributes = encryptor.untransform(params);
Map<String, AttributeValue> modifiedAttributes = new HashMap<>(attributes);
modifiedAttributes.put("intValue", new AttributeValue().withN("666"));
assertThat(decryptedAttributes, AttrMatcher.match(modifiedAttributes));
}
@Test(expectedExceptions = DynamoDBMappingException.class)
public void testEncryptWithFieldLevelDoNotEncryptAnnotationBadSignature() {
Map<String, AttributeValue> attributes = new HashMap<>(attribs);
attributes.put("value", new AttributeValue().withN("100"));
Parameters<? extends DoNotEncryptField> params =
FakeParameters.getInstance(
DoNotEncryptField.class, attributes, null, TABLE_NAME, HASH_KEY, RANGE_KEY);
Map<String, AttributeValue> encryptedAttributes = encryptor.transform(params);
assertThat(encryptedAttributes, AttrMatcher.invert(attributes));
assertAttrEquals(attributes.get("value"), encryptedAttributes.get("value"));
params =
FakeParameters.getInstance(
DoNotEncryptField.class, encryptedAttributes, null, TABLE_NAME, HASH_KEY, RANGE_KEY);
encryptedAttributes.put("value", new AttributeValue().withN("200"));
encryptor.untransform(params);
}
@Test(expectedExceptions = DynamoDBMappingException.class)
public void testEncryptWithFieldLevelDoNotEncryptAnnotationBadSignatureSuperClass() {
Map<String, AttributeValue> attributes = new HashMap<>(attribs);
attributes.put("value", new AttributeValue().withN("100"));
Parameters<? extends DoNotEncryptField> params =
FakeParameters.getInstance(
DoNotEncryptField.class, attributes, null, TABLE_NAME, HASH_KEY, RANGE_KEY);
Map<String, AttributeValue> encryptedAttributes = encryptor.transform(params);
assertThat(encryptedAttributes, AttrMatcher.invert(attributes));
assertAttrEquals(attributes.get("value"), encryptedAttributes.get("value"));
params =
FakeParameters.getInstance(
DoNotEncryptField.class, encryptedAttributes, null, TABLE_NAME, HASH_KEY, RANGE_KEY);
// Change DoNotEncrypt value on Mixed super class
encryptedAttributes.put("doubleValue", new AttributeValue().withN("200"));
encryptor.untransform(params);
}
@Test
public void testEncryptWithFieldLevelDoNotTouchAnnotation() {
Map<String, AttributeValue> attributes = new HashMap<>(attribs);
attributes.put("value", new AttributeValue().withN("100"));
Parameters<? extends DoNotTouchField> params =
FakeParameters.getInstance(
DoNotTouchField.class, attributes, null, TABLE_NAME, HASH_KEY, RANGE_KEY);
Map<String, AttributeValue> encryptedAttributes = encryptor.transform(params);
assertThat(encryptedAttributes, AttrMatcher.invert(attributes));
assertAttrEquals(attributes.get("value"), encryptedAttributes.get("value"));
params =
FakeParameters.getInstance(
DoNotTouchField.class, encryptedAttributes, null, TABLE_NAME, HASH_KEY, RANGE_KEY);
Map<String, AttributeValue> decryptedAttributes = encryptor.untransform(params);
assertThat(decryptedAttributes, AttrMatcher.match(attributes));
}
@Test
public void testEncryptWithFieldLevelDoNotTouchAnnotationChangeValue() {
Map<String, AttributeValue> attributes = new HashMap<>(attribs);
attributes.put("value", new AttributeValue().withN("100"));
Parameters<? extends DoNotTouchField> params =
FakeParameters.getInstance(
DoNotTouchField.class, attributes, null, TABLE_NAME, HASH_KEY, RANGE_KEY);
Map<String, AttributeValue> encryptedAttributes = encryptor.transform(params);
assertThat(encryptedAttributes, AttrMatcher.invert(attributes));
assertAttrEquals(attributes.get("value"), encryptedAttributes.get("value"));
params =
FakeParameters.getInstance(
DoNotTouchField.class, encryptedAttributes, null, TABLE_NAME, HASH_KEY, RANGE_KEY);
encryptedAttributes.put("value", new AttributeValue().withN("200"));
Map<String, AttributeValue> decryptedAttributes = encryptor.untransform(params);
assertThat(decryptedAttributes, AttrMatcher.invert(attributes));
assertAttrEquals(new AttributeValue().withN("200"), decryptedAttributes.get("value"));
// Change a DoNotTouch value on Mixed super class
encryptedAttributes.put("intValue", new AttributeValue().withN("666"));
decryptedAttributes = encryptor.untransform(params);
Map<String, AttributeValue> modifiedAttributes = new HashMap<>(attributes);
modifiedAttributes.put("intValue", new AttributeValue().withN("666"));
modifiedAttributes.put("value", new AttributeValue().withN("200"));
assertThat(decryptedAttributes, AttrMatcher.match(modifiedAttributes));
}
@Test(expectedExceptions = DynamoDBMappingException.class)
public void testEncryptWithFieldLevelDoNotTouchAnnotationBadSignatureSuperClass() {
Map<String, AttributeValue> attributes = new HashMap<>(attribs);
attributes.put("value", new AttributeValue().withN("100"));
Parameters<? extends DoNotTouchField> params =
FakeParameters.getInstance(
DoNotTouchField.class, attributes, null, TABLE_NAME, HASH_KEY, RANGE_KEY);
Map<String, AttributeValue> encryptedAttributes = encryptor.transform(params);
assertThat(encryptedAttributes, AttrMatcher.invert(attributes));
assertAttrEquals(attributes.get("value"), encryptedAttributes.get("value"));
params =
FakeParameters.getInstance(
DoNotTouchField.class, encryptedAttributes, null, TABLE_NAME, HASH_KEY, RANGE_KEY);
Map<String, AttributeValue> decryptedAttributes = encryptor.untransform(params);
assertThat(decryptedAttributes, AttrMatcher.match(attributes));
// Change DoNotEncrypt value on Mixed super class
encryptedAttributes.put("doubleValue", new AttributeValue().withN("200"));
encryptor.untransform(params);
}
private void assertAttrEquals(AttributeValue o1, AttributeValue o2) {
Assert.assertEquals(o1.getB(), o2.getB());
assertSetsEqual(o1.getBS(), o2.getBS());
Assert.assertEquals(o1.getN(), o2.getN());
assertSetsEqual(o1.getNS(), o2.getNS());
Assert.assertEquals(o1.getS(), o2.getS());
assertSetsEqual(o1.getSS(), o2.getSS());
}
private <T> void assertSetsEqual(Collection<T> c1, Collection<T> c2) {
Assert.assertFalse(c1 == null ^ c2 == null);
if (c1 != null) {
Set<T> s1 = new HashSet<T>(c1);
Set<T> s2 = new HashSet<T>(c2);
Assert.assertEquals(s1, s2);
}
}
}
| 5,005 |
0 | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/sdkv1/com/amazonaws/services/dynamodbv2/datamodeling | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/sdkv1/com/amazonaws/services/dynamodbv2/datamodeling/encryption/DynamoDBSignerTest.java | /*
* Copyright 2014 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.services.dynamodbv2.datamodeling.encryption;
import com.amazonaws.services.dynamodbv2.datamodeling.internal.Utils;
import com.amazonaws.services.dynamodbv2.model.AttributeValue;
import java.nio.ByteBuffer;
import java.security.GeneralSecurityException;
import java.security.Key;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.Security;
import java.security.SignatureException;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import javax.crypto.KeyGenerator;
import org.bouncycastle.jce.ECNamedCurveTable;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.jce.spec.ECParameterSpec;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
public class DynamoDBSignerTest {
// These use the Key type (rather than PublicKey, PrivateKey, and SecretKey)
// to test the routing logic within the signer.
private static Key pubKeyRsa;
private static Key privKeyRsa;
private static Key macKey;
private DynamoDBSigner signerRsa;
private DynamoDBSigner signerEcdsa;
private static Key pubKeyEcdsa;
private static Key privKeyEcdsa;
@BeforeClass
public static void setUpClass() throws Exception {
// RSA key generation
KeyPairGenerator rsaGen = KeyPairGenerator.getInstance("RSA");
rsaGen.initialize(2048, Utils.getRng());
KeyPair sigPair = rsaGen.generateKeyPair();
pubKeyRsa = sigPair.getPublic();
privKeyRsa = sigPair.getPrivate();
KeyGenerator macGen = KeyGenerator.getInstance("HmacSHA256");
macGen.init(256, Utils.getRng());
macKey = macGen.generateKey();
Security.addProvider(new BouncyCastleProvider());
ECParameterSpec ecSpec = ECNamedCurveTable.getParameterSpec("secp384r1");
KeyPairGenerator g = KeyPairGenerator.getInstance("ECDSA", "BC");
g.initialize(ecSpec, Utils.getRng());
KeyPair keypair = g.generateKeyPair();
pubKeyEcdsa = keypair.getPublic();
privKeyEcdsa = keypair.getPrivate();
}
@BeforeMethod
public void setUp() {
signerRsa = DynamoDBSigner.getInstance("SHA256withRSA", Utils.getRng());
signerEcdsa = DynamoDBSigner.getInstance("SHA384withECDSA", Utils.getRng());
}
@Test
public void mac() throws GeneralSecurityException {
Map<String, AttributeValue> itemAttributes = new HashMap<String, AttributeValue>();
Map<String, Set<EncryptionFlags>> attributeActionsOnEncrypt = new HashMap<String, Set<EncryptionFlags>>();
itemAttributes.put("Key1", new AttributeValue().withS("Value1"));
attributeActionsOnEncrypt.put("Key1", EnumSet.of(EncryptionFlags.SIGN));
itemAttributes.put("Key2", new AttributeValue().withN("100"));
attributeActionsOnEncrypt.put("Key2", EnumSet.of(EncryptionFlags.SIGN));
itemAttributes.put(
"Key3", new AttributeValue().withB(ByteBuffer.wrap(new byte[] {0, 1, 2, 3})));
attributeActionsOnEncrypt.put("Key3", EnumSet.of(EncryptionFlags.SIGN, EncryptionFlags.ENCRYPT));
byte[] signature =
signerRsa.calculateSignature(itemAttributes, attributeActionsOnEncrypt, new byte[0], macKey);
signerRsa.verifySignature(
itemAttributes, attributeActionsOnEncrypt, new byte[0], macKey, ByteBuffer.wrap(signature));
}
@Test
public void macLists() throws GeneralSecurityException {
Map<String, AttributeValue> itemAttributes = new HashMap<String, AttributeValue>();
Map<String, Set<EncryptionFlags>> attributeActionsOnEncrypt = new HashMap<String, Set<EncryptionFlags>>();
itemAttributes.put("Key1", new AttributeValue().withSS("Value1", "Value2", "Value3"));
attributeActionsOnEncrypt.put("Key1", EnumSet.of(EncryptionFlags.SIGN));
itemAttributes.put("Key2", new AttributeValue().withNS("100", "200", "300"));
attributeActionsOnEncrypt.put("Key2", EnumSet.of(EncryptionFlags.SIGN));
itemAttributes.put(
"Key3",
new AttributeValue()
.withBS(
ByteBuffer.wrap(new byte[] {0, 1, 2, 3}), ByteBuffer.wrap(new byte[] {3, 2, 1})));
attributeActionsOnEncrypt.put("Key3", EnumSet.of(EncryptionFlags.SIGN, EncryptionFlags.ENCRYPT));
byte[] signature =
signerRsa.calculateSignature(itemAttributes, attributeActionsOnEncrypt, new byte[0], macKey);
signerRsa.verifySignature(
itemAttributes, attributeActionsOnEncrypt, new byte[0], macKey, ByteBuffer.wrap(signature));
}
@Test
public void macListsUnsorted() throws GeneralSecurityException {
Map<String, AttributeValue> itemAttributes = new HashMap<String, AttributeValue>();
Map<String, Set<EncryptionFlags>> attributeActionsOnEncrypt = new HashMap<String, Set<EncryptionFlags>>();
itemAttributes.put("Key1", new AttributeValue().withSS("Value3", "Value1", "Value2"));
attributeActionsOnEncrypt.put("Key1", EnumSet.of(EncryptionFlags.SIGN));
itemAttributes.put("Key2", new AttributeValue().withNS("100", "300", "200"));
attributeActionsOnEncrypt.put("Key2", EnumSet.of(EncryptionFlags.SIGN));
itemAttributes.put(
"Key3",
new AttributeValue()
.withBS(
ByteBuffer.wrap(new byte[] {3, 2, 1}), ByteBuffer.wrap(new byte[] {0, 1, 2, 3})));
attributeActionsOnEncrypt.put("Key3", EnumSet.of(EncryptionFlags.SIGN, EncryptionFlags.ENCRYPT));
byte[] signature =
signerRsa.calculateSignature(itemAttributes, attributeActionsOnEncrypt, new byte[0], macKey);
Map<String, AttributeValue> scrambledAttributes = new HashMap<String, AttributeValue>();
scrambledAttributes.put("Key1", new AttributeValue().withSS("Value1", "Value2", "Value3"));
scrambledAttributes.put("Key2", new AttributeValue().withNS("100", "200", "300"));
scrambledAttributes.put(
"Key3",
new AttributeValue()
.withBS(
ByteBuffer.wrap(new byte[] {0, 1, 2, 3}), ByteBuffer.wrap(new byte[] {3, 2, 1})));
signerRsa.verifySignature(
scrambledAttributes, attributeActionsOnEncrypt, new byte[0], macKey, ByteBuffer.wrap(signature));
}
@Test
public void macNoAdMatchesEmptyAd() throws GeneralSecurityException {
Map<String, AttributeValue> itemAttributes = new HashMap<String, AttributeValue>();
Map<String, Set<EncryptionFlags>> attributeActionsOnEncrypt = new HashMap<String, Set<EncryptionFlags>>();
itemAttributes.put("Key1", new AttributeValue().withS("Value1"));
attributeActionsOnEncrypt.put("Key1", EnumSet.of(EncryptionFlags.SIGN));
itemAttributes.put("Key2", new AttributeValue().withN("100"));
attributeActionsOnEncrypt.put("Key2", EnumSet.of(EncryptionFlags.SIGN));
itemAttributes.put(
"Key3", new AttributeValue().withB(ByteBuffer.wrap(new byte[] {0, 1, 2, 3})));
attributeActionsOnEncrypt.put("Key3", EnumSet.of(EncryptionFlags.SIGN, EncryptionFlags.ENCRYPT));
byte[] signature = signerRsa.calculateSignature(itemAttributes, attributeActionsOnEncrypt, null, macKey);
signerRsa.verifySignature(
itemAttributes, attributeActionsOnEncrypt, new byte[0], macKey, ByteBuffer.wrap(signature));
}
@Test
public void macWithIgnoredChange() throws GeneralSecurityException {
Map<String, AttributeValue> itemAttributes = new HashMap<String, AttributeValue>();
Map<String, Set<EncryptionFlags>> attributeActionsOnEncrypt = new HashMap<String, Set<EncryptionFlags>>();
itemAttributes.put("Key1", new AttributeValue().withS("Value1"));
attributeActionsOnEncrypt.put("Key1", EnumSet.of(EncryptionFlags.SIGN));
itemAttributes.put("Key2", new AttributeValue().withN("100"));
attributeActionsOnEncrypt.put("Key2", EnumSet.of(EncryptionFlags.SIGN));
itemAttributes.put(
"Key3", new AttributeValue().withB(ByteBuffer.wrap(new byte[] {0, 1, 2, 3})));
attributeActionsOnEncrypt.put("Key3", EnumSet.of(EncryptionFlags.SIGN, EncryptionFlags.ENCRYPT));
itemAttributes.put("Key4", new AttributeValue().withS("Ignored Value"));
byte[] signature =
signerRsa.calculateSignature(itemAttributes, attributeActionsOnEncrypt, new byte[0], macKey);
itemAttributes.put("Key4", new AttributeValue().withS("New Ignored Value"));
signerRsa.verifySignature(
itemAttributes, attributeActionsOnEncrypt, new byte[0], macKey, ByteBuffer.wrap(signature));
}
@Test(expectedExceptions = SignatureException.class)
public void macChangedValue() throws GeneralSecurityException {
Map<String, AttributeValue> itemAttributes = new HashMap<String, AttributeValue>();
Map<String, Set<EncryptionFlags>> attributeActionsOnEncrypt = new HashMap<String, Set<EncryptionFlags>>();
itemAttributes.put("Key1", new AttributeValue().withS("Value1"));
attributeActionsOnEncrypt.put("Key1", EnumSet.of(EncryptionFlags.SIGN));
itemAttributes.put("Key2", new AttributeValue().withN("100"));
attributeActionsOnEncrypt.put("Key2", EnumSet.of(EncryptionFlags.SIGN));
itemAttributes.put(
"Key3", new AttributeValue().withB(ByteBuffer.wrap(new byte[] {0, 1, 2, 3})));
attributeActionsOnEncrypt.put("Key3", EnumSet.of(EncryptionFlags.SIGN, EncryptionFlags.ENCRYPT));
byte[] signature =
signerRsa.calculateSignature(itemAttributes, attributeActionsOnEncrypt, new byte[0], macKey);
itemAttributes.get("Key2").setN("99");
signerRsa.verifySignature(
itemAttributes, attributeActionsOnEncrypt, new byte[0], macKey, ByteBuffer.wrap(signature));
}
@Test(expectedExceptions = SignatureException.class)
public void macChangedFlag() throws GeneralSecurityException {
Map<String, AttributeValue> itemAttributes = new HashMap<String, AttributeValue>();
Map<String, Set<EncryptionFlags>> attributeActionsOnEncrypt = new HashMap<String, Set<EncryptionFlags>>();
itemAttributes.put("Key1", new AttributeValue().withS("Value1"));
attributeActionsOnEncrypt.put("Key1", EnumSet.of(EncryptionFlags.SIGN));
itemAttributes.put("Key2", new AttributeValue().withN("100"));
attributeActionsOnEncrypt.put("Key2", EnumSet.of(EncryptionFlags.SIGN));
itemAttributes.put(
"Key3", new AttributeValue().withB(ByteBuffer.wrap(new byte[] {0, 1, 2, 3})));
attributeActionsOnEncrypt.put("Key3", EnumSet.of(EncryptionFlags.SIGN, EncryptionFlags.ENCRYPT));
byte[] signature =
signerRsa.calculateSignature(itemAttributes, attributeActionsOnEncrypt, new byte[0], macKey);
attributeActionsOnEncrypt.put("Key3", EnumSet.of(EncryptionFlags.SIGN));
signerRsa.verifySignature(
itemAttributes, attributeActionsOnEncrypt, new byte[0], macKey, ByteBuffer.wrap(signature));
}
@Test(expectedExceptions = SignatureException.class)
public void macChangedAssociatedData() throws GeneralSecurityException {
Map<String, AttributeValue> itemAttributes = new HashMap<String, AttributeValue>();
Map<String, Set<EncryptionFlags>> attributeActionsOnEncrypt = new HashMap<String, Set<EncryptionFlags>>();
itemAttributes.put("Key1", new AttributeValue().withS("Value1"));
attributeActionsOnEncrypt.put("Key1", EnumSet.of(EncryptionFlags.SIGN));
itemAttributes.put("Key2", new AttributeValue().withN("100"));
attributeActionsOnEncrypt.put("Key2", EnumSet.of(EncryptionFlags.SIGN));
itemAttributes.put(
"Key3", new AttributeValue().withB(ByteBuffer.wrap(new byte[] {0, 1, 2, 3})));
attributeActionsOnEncrypt.put("Key3", EnumSet.of(EncryptionFlags.SIGN, EncryptionFlags.ENCRYPT));
byte[] signature =
signerRsa.calculateSignature(itemAttributes, attributeActionsOnEncrypt, new byte[] {3, 2, 1}, macKey);
signerRsa.verifySignature(
itemAttributes, attributeActionsOnEncrypt, new byte[] {1, 2, 3}, macKey, ByteBuffer.wrap(signature));
}
@Test
public void sig() throws GeneralSecurityException {
Map<String, AttributeValue> itemAttributes = new HashMap<String, AttributeValue>();
Map<String, Set<EncryptionFlags>> attributeActionsOnEncrypt = new HashMap<String, Set<EncryptionFlags>>();
itemAttributes.put("Key1", new AttributeValue().withS("Value1"));
attributeActionsOnEncrypt.put("Key1", EnumSet.of(EncryptionFlags.SIGN));
itemAttributes.put("Key2", new AttributeValue().withN("100"));
attributeActionsOnEncrypt.put("Key2", EnumSet.of(EncryptionFlags.SIGN));
itemAttributes.put(
"Key3", new AttributeValue().withB(ByteBuffer.wrap(new byte[] {0, 1, 2, 3})));
attributeActionsOnEncrypt.put("Key3", EnumSet.of(EncryptionFlags.SIGN, EncryptionFlags.ENCRYPT));
byte[] signature =
signerRsa.calculateSignature(itemAttributes, attributeActionsOnEncrypt, new byte[0], privKeyRsa);
signerRsa.verifySignature(
itemAttributes, attributeActionsOnEncrypt, new byte[0], pubKeyRsa, ByteBuffer.wrap(signature));
}
@Test
public void sigWithReadOnlySignature() throws GeneralSecurityException {
Map<String, AttributeValue> itemAttributes = new HashMap<String, AttributeValue>();
Map<String, Set<EncryptionFlags>> attributeActionsOnEncrypt = new HashMap<String, Set<EncryptionFlags>>();
itemAttributes.put("Key1", new AttributeValue().withS("Value1"));
attributeActionsOnEncrypt.put("Key1", EnumSet.of(EncryptionFlags.SIGN));
itemAttributes.put("Key2", new AttributeValue().withN("100"));
attributeActionsOnEncrypt.put("Key2", EnumSet.of(EncryptionFlags.SIGN));
itemAttributes.put(
"Key3", new AttributeValue().withB(ByteBuffer.wrap(new byte[] {0, 1, 2, 3})));
attributeActionsOnEncrypt.put("Key3", EnumSet.of(EncryptionFlags.SIGN, EncryptionFlags.ENCRYPT));
byte[] signature =
signerRsa.calculateSignature(itemAttributes, attributeActionsOnEncrypt, new byte[0], privKeyRsa);
signerRsa.verifySignature(
itemAttributes,
attributeActionsOnEncrypt,
new byte[0],
pubKeyRsa,
ByteBuffer.wrap(signature).asReadOnlyBuffer());
}
@Test
public void sigNoAdMatchesEmptyAd() throws GeneralSecurityException {
Map<String, AttributeValue> itemAttributes = new HashMap<String, AttributeValue>();
Map<String, Set<EncryptionFlags>> attributeActionsOnEncrypt = new HashMap<String, Set<EncryptionFlags>>();
itemAttributes.put("Key1", new AttributeValue().withS("Value1"));
attributeActionsOnEncrypt.put("Key1", EnumSet.of(EncryptionFlags.SIGN));
itemAttributes.put("Key2", new AttributeValue().withN("100"));
attributeActionsOnEncrypt.put("Key2", EnumSet.of(EncryptionFlags.SIGN));
itemAttributes.put(
"Key3", new AttributeValue().withB(ByteBuffer.wrap(new byte[] {0, 1, 2, 3})));
attributeActionsOnEncrypt.put("Key3", EnumSet.of(EncryptionFlags.SIGN, EncryptionFlags.ENCRYPT));
byte[] signature =
signerRsa.calculateSignature(itemAttributes, attributeActionsOnEncrypt, null, privKeyRsa);
signerRsa.verifySignature(
itemAttributes, attributeActionsOnEncrypt, new byte[0], pubKeyRsa, ByteBuffer.wrap(signature));
}
@Test
public void sigWithIgnoredChange() throws GeneralSecurityException {
Map<String, AttributeValue> itemAttributes = new HashMap<String, AttributeValue>();
Map<String, Set<EncryptionFlags>> attributeActionsOnEncrypt = new HashMap<String, Set<EncryptionFlags>>();
itemAttributes.put("Key1", new AttributeValue().withS("Value1"));
attributeActionsOnEncrypt.put("Key1", EnumSet.of(EncryptionFlags.SIGN));
itemAttributes.put("Key2", new AttributeValue().withN("100"));
attributeActionsOnEncrypt.put("Key2", EnumSet.of(EncryptionFlags.SIGN));
itemAttributes.put(
"Key3", new AttributeValue().withB(ByteBuffer.wrap(new byte[] {0, 1, 2, 3})));
attributeActionsOnEncrypt.put("Key3", EnumSet.of(EncryptionFlags.SIGN, EncryptionFlags.ENCRYPT));
itemAttributes.put("Key4", new AttributeValue().withS("Ignored Value"));
byte[] signature =
signerRsa.calculateSignature(itemAttributes, attributeActionsOnEncrypt, new byte[0], privKeyRsa);
itemAttributes.put("Key4", new AttributeValue().withS("New Ignored Value"));
signerRsa.verifySignature(
itemAttributes, attributeActionsOnEncrypt, new byte[0], pubKeyRsa, ByteBuffer.wrap(signature));
}
@Test(expectedExceptions = SignatureException.class)
public void sigChangedValue() throws GeneralSecurityException {
Map<String, AttributeValue> itemAttributes = new HashMap<String, AttributeValue>();
Map<String, Set<EncryptionFlags>> attributeActionsOnEncrypt = new HashMap<String, Set<EncryptionFlags>>();
itemAttributes.put("Key1", new AttributeValue().withS("Value1"));
attributeActionsOnEncrypt.put("Key1", EnumSet.of(EncryptionFlags.SIGN));
itemAttributes.put("Key2", new AttributeValue().withN("100"));
attributeActionsOnEncrypt.put("Key2", EnumSet.of(EncryptionFlags.SIGN));
itemAttributes.put(
"Key3", new AttributeValue().withB(ByteBuffer.wrap(new byte[] {0, 1, 2, 3})));
attributeActionsOnEncrypt.put("Key3", EnumSet.of(EncryptionFlags.SIGN, EncryptionFlags.ENCRYPT));
byte[] signature =
signerRsa.calculateSignature(itemAttributes, attributeActionsOnEncrypt, new byte[0], privKeyRsa);
itemAttributes.get("Key2").setN("99");
signerRsa.verifySignature(
itemAttributes, attributeActionsOnEncrypt, new byte[0], pubKeyRsa, ByteBuffer.wrap(signature));
}
@Test(expectedExceptions = SignatureException.class)
public void sigChangedFlag() throws GeneralSecurityException {
Map<String, AttributeValue> itemAttributes = new HashMap<String, AttributeValue>();
Map<String, Set<EncryptionFlags>> attributeActionsOnEncrypt = new HashMap<String, Set<EncryptionFlags>>();
itemAttributes.put("Key1", new AttributeValue().withS("Value1"));
attributeActionsOnEncrypt.put("Key1", EnumSet.of(EncryptionFlags.SIGN));
itemAttributes.put("Key2", new AttributeValue().withN("100"));
attributeActionsOnEncrypt.put("Key2", EnumSet.of(EncryptionFlags.SIGN));
itemAttributes.put(
"Key3", new AttributeValue().withB(ByteBuffer.wrap(new byte[] {0, 1, 2, 3})));
attributeActionsOnEncrypt.put("Key3", EnumSet.of(EncryptionFlags.SIGN, EncryptionFlags.ENCRYPT));
byte[] signature =
signerRsa.calculateSignature(itemAttributes, attributeActionsOnEncrypt, new byte[0], privKeyRsa);
attributeActionsOnEncrypt.put("Key3", EnumSet.of(EncryptionFlags.SIGN));
signerRsa.verifySignature(
itemAttributes, attributeActionsOnEncrypt, new byte[0], pubKeyRsa, ByteBuffer.wrap(signature));
}
@Test(expectedExceptions = SignatureException.class)
public void sigChangedAssociatedData() throws GeneralSecurityException {
Map<String, AttributeValue> itemAttributes = new HashMap<String, AttributeValue>();
Map<String, Set<EncryptionFlags>> attributeActionsOnEncrypt = new HashMap<String, Set<EncryptionFlags>>();
itemAttributes.put("Key1", new AttributeValue().withS("Value1"));
attributeActionsOnEncrypt.put("Key1", EnumSet.of(EncryptionFlags.SIGN));
itemAttributes.put("Key2", new AttributeValue().withN("100"));
attributeActionsOnEncrypt.put("Key2", EnumSet.of(EncryptionFlags.SIGN));
itemAttributes.put(
"Key3", new AttributeValue().withB(ByteBuffer.wrap(new byte[] {0, 1, 2, 3})));
attributeActionsOnEncrypt.put("Key3", EnumSet.of(EncryptionFlags.SIGN, EncryptionFlags.ENCRYPT));
byte[] signature =
signerRsa.calculateSignature(itemAttributes, attributeActionsOnEncrypt, new byte[0], privKeyRsa);
signerRsa.verifySignature(
itemAttributes,
attributeActionsOnEncrypt,
new byte[] {1, 2, 3},
pubKeyRsa,
ByteBuffer.wrap(signature));
}
@Test
public void sigEcdsa() throws GeneralSecurityException {
Map<String, AttributeValue> itemAttributes = new HashMap<String, AttributeValue>();
Map<String, Set<EncryptionFlags>> attributeActionsOnEncrypt = new HashMap<String, Set<EncryptionFlags>>();
itemAttributes.put("Key1", new AttributeValue().withS("Value1"));
attributeActionsOnEncrypt.put("Key1", EnumSet.of(EncryptionFlags.SIGN));
itemAttributes.put("Key2", new AttributeValue().withN("100"));
attributeActionsOnEncrypt.put("Key2", EnumSet.of(EncryptionFlags.SIGN));
itemAttributes.put(
"Key3", new AttributeValue().withB(ByteBuffer.wrap(new byte[] {0, 1, 2, 3})));
attributeActionsOnEncrypt.put("Key3", EnumSet.of(EncryptionFlags.SIGN));
byte[] signature =
signerEcdsa.calculateSignature(itemAttributes, attributeActionsOnEncrypt, new byte[0], privKeyEcdsa);
signerEcdsa.verifySignature(
itemAttributes, attributeActionsOnEncrypt, new byte[0], pubKeyEcdsa, ByteBuffer.wrap(signature));
}
@Test
public void sigEcdsaWithReadOnlySignature() throws GeneralSecurityException {
Map<String, AttributeValue> itemAttributes = new HashMap<String, AttributeValue>();
Map<String, Set<EncryptionFlags>> attributeActionsOnEncrypt = new HashMap<String, Set<EncryptionFlags>>();
itemAttributes.put("Key1", new AttributeValue().withS("Value1"));
attributeActionsOnEncrypt.put("Key1", EnumSet.of(EncryptionFlags.SIGN));
itemAttributes.put("Key2", new AttributeValue().withN("100"));
attributeActionsOnEncrypt.put("Key2", EnumSet.of(EncryptionFlags.SIGN));
itemAttributes.put(
"Key3", new AttributeValue().withB(ByteBuffer.wrap(new byte[] {0, 1, 2, 3})));
attributeActionsOnEncrypt.put("Key3", EnumSet.of(EncryptionFlags.SIGN));
byte[] signature =
signerEcdsa.calculateSignature(itemAttributes, attributeActionsOnEncrypt, new byte[0], privKeyEcdsa);
signerEcdsa.verifySignature(
itemAttributes,
attributeActionsOnEncrypt,
new byte[0],
pubKeyEcdsa,
ByteBuffer.wrap(signature).asReadOnlyBuffer());
}
@Test
public void sigEcdsaNoAdMatchesEmptyAd() throws GeneralSecurityException {
Map<String, AttributeValue> itemAttributes = new HashMap<String, AttributeValue>();
Map<String, Set<EncryptionFlags>> attributeActionsOnEncrypt = new HashMap<String, Set<EncryptionFlags>>();
itemAttributes.put("Key1", new AttributeValue().withS("Value1"));
attributeActionsOnEncrypt.put("Key1", EnumSet.of(EncryptionFlags.SIGN));
itemAttributes.put("Key2", new AttributeValue().withN("100"));
attributeActionsOnEncrypt.put("Key2", EnumSet.of(EncryptionFlags.SIGN));
itemAttributes.put(
"Key3", new AttributeValue().withB(ByteBuffer.wrap(new byte[] {0, 1, 2, 3})));
attributeActionsOnEncrypt.put("Key3", EnumSet.of(EncryptionFlags.SIGN));
byte[] signature =
signerEcdsa.calculateSignature(itemAttributes, attributeActionsOnEncrypt, null, privKeyEcdsa);
signerEcdsa.verifySignature(
itemAttributes, attributeActionsOnEncrypt, new byte[0], pubKeyEcdsa, ByteBuffer.wrap(signature));
}
@Test
public void sigEcdsaWithIgnoredChange() throws GeneralSecurityException {
Map<String, AttributeValue> itemAttributes = new HashMap<String, AttributeValue>();
Map<String, Set<EncryptionFlags>> attributeActionsOnEncrypt = new HashMap<String, Set<EncryptionFlags>>();
itemAttributes.put("Key1", new AttributeValue().withS("Value1"));
attributeActionsOnEncrypt.put("Key1", EnumSet.of(EncryptionFlags.SIGN));
itemAttributes.put("Key2", new AttributeValue().withN("100"));
attributeActionsOnEncrypt.put("Key2", EnumSet.of(EncryptionFlags.SIGN));
itemAttributes.put(
"Key3", new AttributeValue().withB(ByteBuffer.wrap(new byte[] {0, 1, 2, 3})));
attributeActionsOnEncrypt.put("Key3", EnumSet.of(EncryptionFlags.SIGN));
itemAttributes.put("Key4", new AttributeValue().withS("Ignored Value"));
byte[] signature =
signerEcdsa.calculateSignature(itemAttributes, attributeActionsOnEncrypt, new byte[0], privKeyEcdsa);
itemAttributes.put("Key4", new AttributeValue().withS("New Ignored Value"));
signerEcdsa.verifySignature(
itemAttributes, attributeActionsOnEncrypt, new byte[0], pubKeyEcdsa, ByteBuffer.wrap(signature));
}
@Test(expectedExceptions = SignatureException.class)
public void sigEcdsaChangedValue() throws GeneralSecurityException {
Map<String, AttributeValue> itemAttributes = new HashMap<String, AttributeValue>();
Map<String, Set<EncryptionFlags>> attributeActionsOnEncrypt = new HashMap<String, Set<EncryptionFlags>>();
itemAttributes.put("Key1", new AttributeValue().withS("Value1"));
attributeActionsOnEncrypt.put("Key1", EnumSet.of(EncryptionFlags.SIGN));
itemAttributes.put("Key2", new AttributeValue().withN("100"));
attributeActionsOnEncrypt.put("Key2", EnumSet.of(EncryptionFlags.SIGN));
itemAttributes.put(
"Key3", new AttributeValue().withB(ByteBuffer.wrap(new byte[] {0, 1, 2, 3})));
attributeActionsOnEncrypt.put("Key3", EnumSet.of(EncryptionFlags.SIGN));
byte[] signature =
signerEcdsa.calculateSignature(itemAttributes, attributeActionsOnEncrypt, new byte[0], privKeyEcdsa);
itemAttributes.get("Key2").setN("99");
signerEcdsa.verifySignature(
itemAttributes, attributeActionsOnEncrypt, new byte[0], pubKeyEcdsa, ByteBuffer.wrap(signature));
}
@Test(expectedExceptions = SignatureException.class)
public void sigEcdsaChangedAssociatedData() throws GeneralSecurityException {
Map<String, AttributeValue> itemAttributes = new HashMap<String, AttributeValue>();
Map<String, Set<EncryptionFlags>> attributeActionsOnEncrypt = new HashMap<String, Set<EncryptionFlags>>();
itemAttributes.put("Key1", new AttributeValue().withS("Value1"));
attributeActionsOnEncrypt.put("Key1", EnumSet.of(EncryptionFlags.SIGN));
itemAttributes.put("Key2", new AttributeValue().withN("100"));
attributeActionsOnEncrypt.put("Key2", EnumSet.of(EncryptionFlags.SIGN));
itemAttributes.put(
"Key3", new AttributeValue().withB(ByteBuffer.wrap(new byte[] {0, 1, 2, 3})));
attributeActionsOnEncrypt.put("Key3", EnumSet.of(EncryptionFlags.SIGN));
byte[] signature =
signerEcdsa.calculateSignature(itemAttributes, attributeActionsOnEncrypt, new byte[0], privKeyEcdsa);
signerEcdsa.verifySignature(
itemAttributes,
attributeActionsOnEncrypt,
new byte[] {1, 2, 3},
pubKeyEcdsa,
ByteBuffer.wrap(signature));
}
}
| 5,006 |
0 | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/sdkv1/com/amazonaws/services/dynamodbv2/datamodeling | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/sdkv1/com/amazonaws/services/dynamodbv2/datamodeling/encryption/DelegatedEnvelopeEncryptionTest.java | /*
* Copyright 2014 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.services.dynamodbv2.datamodeling.encryption;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertNotNull;
import static org.testng.AssertJUnit.assertNull;
import static org.testng.AssertJUnit.assertTrue;
import com.amazonaws.services.dynamodbv2.datamodeling.encryption.providers.EncryptionMaterialsProvider;
import com.amazonaws.services.dynamodbv2.datamodeling.encryption.providers.SymmetricStaticProvider;
import com.amazonaws.services.dynamodbv2.datamodeling.encryption.providers.WrappedMaterialsProvider;
import com.amazonaws.services.dynamodbv2.datamodeling.internal.Utils;
import com.amazonaws.services.dynamodbv2.model.AttributeValue;
import com.amazonaws.services.dynamodbv2.testing.AttrMatcher;
import com.amazonaws.services.dynamodbv2.testing.TestDelegatedKey;
import java.nio.ByteBuffer;
import java.security.GeneralSecurityException;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.SignatureException;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import javax.crypto.spec.SecretKeySpec;
import org.testng.Assert;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
public class DelegatedEnvelopeEncryptionTest {
private static SecretKeySpec rawEncryptionKey;
private static SecretKeySpec rawMacKey;
private static DelegatedKey encryptionKey;
private static DelegatedKey macKey;
private EncryptionMaterialsProvider prov;
private DynamoDBEncryptor encryptor;
private Map<String, AttributeValue> attribs;
private EncryptionContext context;
@BeforeClass
public static void setupClass() throws Exception {
rawEncryptionKey = new SecretKeySpec(Utils.getRandom(32), "AES");
encryptionKey = new TestDelegatedKey(rawEncryptionKey);
rawMacKey = new SecretKeySpec(Utils.getRandom(32), "HmacSHA256");
macKey = new TestDelegatedKey(rawMacKey);
}
@BeforeMethod
public void setUp() throws Exception {
prov =
new WrappedMaterialsProvider(
encryptionKey, encryptionKey, macKey, Collections.<String, String>emptyMap());
encryptor = DynamoDBEncryptor.getInstance(prov, "encryptor-");
attribs = new HashMap<String, AttributeValue>();
attribs.put("intValue", new AttributeValue().withN("123"));
attribs.put("stringValue", new AttributeValue().withS("Hello world!"));
attribs.put(
"byteArrayValue",
new AttributeValue().withB(ByteBuffer.wrap(new byte[] {0, 1, 2, 3, 4, 5})));
attribs.put("stringSet", new AttributeValue().withSS("Goodbye", "Cruel", "World", "?"));
attribs.put("intSet", new AttributeValue().withNS("1", "200", "10", "15", "0"));
attribs.put("hashKey", new AttributeValue().withN("5"));
attribs.put("rangeKey", new AttributeValue().withN("7"));
attribs.put("version", new AttributeValue().withN("0"));
context =
new EncryptionContext.Builder()
.withTableName("TableName")
.withHashKeyName("hashKey")
.withRangeKeyName("rangeKey")
.build();
}
@Test
public void testSetSignatureFieldName() {
assertNotNull(encryptor.getSignatureFieldName());
encryptor.setSignatureFieldName("A different value");
assertEquals("A different value", encryptor.getSignatureFieldName());
}
@Test
public void testSetMaterialDescriptionFieldName() {
assertNotNull(encryptor.getMaterialDescriptionFieldName());
encryptor.setMaterialDescriptionFieldName("A different value");
assertEquals("A different value", encryptor.getMaterialDescriptionFieldName());
}
@Test
public void fullEncryption() throws GeneralSecurityException {
Map<String, AttributeValue> encryptedAttributes =
encryptor.encryptAllFieldsExcept(
Collections.unmodifiableMap(attribs), context, "hashKey", "rangeKey", "version");
assertThat(encryptedAttributes, AttrMatcher.invert(attribs));
Map<String, AttributeValue> decryptedAttributes =
encryptor.decryptAllFieldsExcept(
Collections.unmodifiableMap(encryptedAttributes),
context,
"hashKey",
"rangeKey",
"version");
assertThat(decryptedAttributes, AttrMatcher.match(attribs));
// Make sure keys and version are not encrypted
assertAttrEquals(attribs.get("hashKey"), encryptedAttributes.get("hashKey"));
assertAttrEquals(attribs.get("rangeKey"), encryptedAttributes.get("rangeKey"));
assertAttrEquals(attribs.get("version"), encryptedAttributes.get("version"));
// Make sure String has been encrypted (we'll assume the others are correct as well)
assertTrue(encryptedAttributes.containsKey("stringValue"));
assertNull(encryptedAttributes.get("stringValue").getS());
assertNotNull(encryptedAttributes.get("stringValue").getB());
}
@Test(expectedExceptions = SignatureException.class)
public void fullEncryptionBadSignature() throws GeneralSecurityException {
Map<String, AttributeValue> encryptedAttributes =
encryptor.encryptAllFieldsExcept(
Collections.unmodifiableMap(attribs), context, "hashKey", "rangeKey", "version");
assertThat(encryptedAttributes, AttrMatcher.invert(attribs));
encryptedAttributes.get("hashKey").setN("666");
encryptor.decryptAllFieldsExcept(
Collections.unmodifiableMap(encryptedAttributes),
context,
"hashKey",
"rangeKey",
"version");
}
@Test(expectedExceptions = IllegalArgumentException.class)
public void badVersionNumber() throws GeneralSecurityException {
Map<String, AttributeValue> encryptedAttributes =
encryptor.encryptAllFieldsExcept(
Collections.unmodifiableMap(attribs), context, "hashKey", "rangeKey", "version");
ByteBuffer materialDescription =
encryptedAttributes.get(encryptor.getMaterialDescriptionFieldName()).getB();
byte[] rawArray = materialDescription.array();
assertEquals(0, rawArray[0]); // This will need to be kept in sync with the current version.
rawArray[0] = 100;
encryptedAttributes.put(
encryptor.getMaterialDescriptionFieldName(),
new AttributeValue().withB(ByteBuffer.wrap(rawArray)));
encryptor.decryptAllFieldsExcept(
Collections.unmodifiableMap(encryptedAttributes),
context,
"hashKey",
"rangeKey",
"version");
}
@Test
public void signedOnly() throws GeneralSecurityException {
Map<String, AttributeValue> encryptedAttributes =
encryptor.encryptAllFieldsExcept(attribs, context, attribs.keySet().toArray(new String[0]));
assertThat(encryptedAttributes, AttrMatcher.invert(attribs));
Map<String, AttributeValue> decryptedAttributes =
encryptor.decryptAllFieldsExcept(
encryptedAttributes, context, attribs.keySet().toArray(new String[0]));
assertThat(decryptedAttributes, AttrMatcher.match(attribs));
// Make sure keys and version are not encrypted
assertAttrEquals(attribs.get("hashKey"), encryptedAttributes.get("hashKey"));
assertAttrEquals(attribs.get("rangeKey"), encryptedAttributes.get("rangeKey"));
assertAttrEquals(attribs.get("version"), encryptedAttributes.get("version"));
// Make sure String has not been encrypted (we'll assume the others are correct as well)
assertAttrEquals(attribs.get("stringValue"), encryptedAttributes.get("stringValue"));
}
@Test
public void signedOnlyNullCryptoKey() throws GeneralSecurityException {
prov = new SymmetricStaticProvider(null, macKey, Collections.<String, String>emptyMap());
encryptor = DynamoDBEncryptor.getInstance(prov, "encryptor-");
Map<String, AttributeValue> encryptedAttributes =
encryptor.encryptAllFieldsExcept(attribs, context, attribs.keySet().toArray(new String[0]));
assertThat(encryptedAttributes, AttrMatcher.invert(attribs));
Map<String, AttributeValue> decryptedAttributes =
encryptor.decryptAllFieldsExcept(
encryptedAttributes, context, attribs.keySet().toArray(new String[0]));
assertThat(decryptedAttributes, AttrMatcher.match(attribs));
// Make sure keys and version are not encrypted
assertAttrEquals(attribs.get("hashKey"), encryptedAttributes.get("hashKey"));
assertAttrEquals(attribs.get("rangeKey"), encryptedAttributes.get("rangeKey"));
assertAttrEquals(attribs.get("version"), encryptedAttributes.get("version"));
// Make sure String has not been encrypted (we'll assume the others are correct as well)
assertAttrEquals(attribs.get("stringValue"), encryptedAttributes.get("stringValue"));
}
@Test(expectedExceptions = SignatureException.class)
public void signedOnlyBadSignature() throws GeneralSecurityException {
Map<String, AttributeValue> encryptedAttributes =
encryptor.encryptAllFieldsExcept(attribs, context, attribs.keySet().toArray(new String[0]));
assertThat(encryptedAttributes, AttrMatcher.invert(attribs));
encryptedAttributes.get("hashKey").setN("666");
encryptor.decryptAllFieldsExcept(
encryptedAttributes, context, attribs.keySet().toArray(new String[0]));
}
@Test(expectedExceptions = SignatureException.class)
public void signedOnlyNoSignature() throws GeneralSecurityException {
Map<String, AttributeValue> encryptedAttributes =
encryptor.encryptAllFieldsExcept(attribs, context, attribs.keySet().toArray(new String[0]));
assertThat(encryptedAttributes, AttrMatcher.invert(attribs));
encryptedAttributes.remove(encryptor.getSignatureFieldName());
encryptor.decryptAllFieldsExcept(
encryptedAttributes, context, attribs.keySet().toArray(new String[0]));
}
@Test
public void RsaSignedOnly() throws GeneralSecurityException {
KeyPairGenerator rsaGen = KeyPairGenerator.getInstance("RSA");
rsaGen.initialize(2048, Utils.getRng());
KeyPair sigPair = rsaGen.generateKeyPair();
encryptor =
DynamoDBEncryptor.getInstance(
new SymmetricStaticProvider(
encryptionKey, sigPair, Collections.<String, String>emptyMap()),
"encryptor-");
Map<String, AttributeValue> encryptedAttributes =
encryptor.encryptAllFieldsExcept(attribs, context, attribs.keySet().toArray(new String[0]));
assertThat(encryptedAttributes, AttrMatcher.invert(attribs));
Map<String, AttributeValue> decryptedAttributes =
encryptor.decryptAllFieldsExcept(
encryptedAttributes, context, attribs.keySet().toArray(new String[0]));
assertThat(decryptedAttributes, AttrMatcher.match(attribs));
// Make sure keys and version are not encrypted
assertAttrEquals(attribs.get("hashKey"), encryptedAttributes.get("hashKey"));
assertAttrEquals(attribs.get("rangeKey"), encryptedAttributes.get("rangeKey"));
assertAttrEquals(attribs.get("version"), encryptedAttributes.get("version"));
// Make sure String has not been encrypted (we'll assume the others are correct as well)
assertAttrEquals(attribs.get("stringValue"), encryptedAttributes.get("stringValue"));
}
@Test(expectedExceptions = SignatureException.class)
public void RsaSignedOnlyBadSignature() throws GeneralSecurityException {
KeyPairGenerator rsaGen = KeyPairGenerator.getInstance("RSA");
rsaGen.initialize(2048, Utils.getRng());
KeyPair sigPair = rsaGen.generateKeyPair();
encryptor =
DynamoDBEncryptor.getInstance(
new SymmetricStaticProvider(
encryptionKey, sigPair, Collections.<String, String>emptyMap()),
"encryptor-");
Map<String, AttributeValue> encryptedAttributes =
encryptor.encryptAllFieldsExcept(attribs, context, attribs.keySet().toArray(new String[0]));
assertThat(encryptedAttributes, AttrMatcher.invert(attribs));
encryptedAttributes.get("hashKey").setN("666");
encryptor.decryptAllFieldsExcept(
encryptedAttributes, context, attribs.keySet().toArray(new String[0]));
}
private void assertAttrEquals(AttributeValue o1, AttributeValue o2) {
Assert.assertEquals(o1.getB(), o2.getB());
assertSetsEqual(o1.getBS(), o2.getBS());
Assert.assertEquals(o1.getN(), o2.getN());
assertSetsEqual(o1.getNS(), o2.getNS());
Assert.assertEquals(o1.getS(), o2.getS());
assertSetsEqual(o1.getSS(), o2.getSS());
}
private <T> void assertSetsEqual(Collection<T> c1, Collection<T> c2) {
Assert.assertFalse(c1 == null ^ c2 == null);
if (c1 != null) {
Set<T> s1 = new HashSet<T>(c1);
Set<T> s2 = new HashSet<T>(c2);
Assert.assertEquals(s1, s2);
}
}
}
| 5,007 |
0 | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/sdkv1/com/amazonaws/services/dynamodbv2/datamodeling | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/sdkv1/com/amazonaws/services/dynamodbv2/datamodeling/encryption/DynamoDBEncryptorTest.java | /*
* Copyright 2014 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.services.dynamodbv2.datamodeling.encryption;
import static com.amazonaws.services.dynamodbv2.datamodeling.encryption.utils.EncryptionContextOperators.overrideEncryptionContextTableName;
import static java.util.stream.Collectors.toMap;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.not;
import static org.testng.AssertJUnit.assertArrayEquals;
import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertNotNull;
import static org.testng.AssertJUnit.assertNull;
import static org.testng.AssertJUnit.assertTrue;
import static org.testng.collections.Sets.newHashSet;
import com.amazonaws.services.dynamodbv2.datamodeling.encryption.materials.DecryptionMaterials;
import com.amazonaws.services.dynamodbv2.datamodeling.encryption.materials.EncryptionMaterials;
import com.amazonaws.services.dynamodbv2.datamodeling.encryption.providers.EncryptionMaterialsProvider;
import com.amazonaws.services.dynamodbv2.datamodeling.encryption.providers.SymmetricStaticProvider;
import com.amazonaws.services.dynamodbv2.datamodeling.internal.Utils;
import com.amazonaws.services.dynamodbv2.model.AttributeValue;
import com.amazonaws.services.dynamodbv2.testing.AttrMatcher;
import java.lang.reflect.Method;
import java.nio.ByteBuffer;
import java.security.GeneralSecurityException;
import java.security.InvalidAlgorithmParameterException;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.Security;
import java.security.SignatureException;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import org.bouncycastle.jce.ECNamedCurveTable;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.jce.spec.ECParameterSpec;
import org.mockito.internal.util.collections.Sets;
import org.testng.Assert;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
public class DynamoDBEncryptorTest {
private static SecretKey encryptionKey;
private static SecretKey macKey;
private InstrumentedEncryptionMaterialsProvider prov;
private DynamoDBEncryptor encryptor;
private Map<String, AttributeValue> attribs;
private EncryptionContext context;
private static final String OVERRIDDEN_TABLE_NAME = "TheBestTableName";
@BeforeClass
public static void setUpClass() throws Exception {
KeyGenerator aesGen = KeyGenerator.getInstance("AES");
aesGen.init(128, Utils.getRng());
encryptionKey = aesGen.generateKey();
KeyGenerator macGen = KeyGenerator.getInstance("HmacSHA256");
macGen.init(256, Utils.getRng());
macKey = macGen.generateKey();
}
@BeforeMethod
public void setUp() throws Exception {
prov =
new InstrumentedEncryptionMaterialsProvider(
new SymmetricStaticProvider(
encryptionKey, macKey, Collections.<String, String>emptyMap()));
encryptor = DynamoDBEncryptor.getInstance(prov, "encryptor-");
attribs = new HashMap<String, AttributeValue>();
attribs.put("intValue", new AttributeValue().withN("123"));
attribs.put("stringValue", new AttributeValue().withS("Hello world!"));
attribs.put(
"byteArrayValue",
new AttributeValue().withB(ByteBuffer.wrap(new byte[] {0, 1, 2, 3, 4, 5})));
attribs.put("stringSet", new AttributeValue().withSS("Goodbye", "Cruel", "World", "?"));
attribs.put("intSet", new AttributeValue().withNS("1", "200", "10", "15", "0"));
attribs.put("hashKey", new AttributeValue().withN("5"));
attribs.put("rangeKey", new AttributeValue().withN("7"));
attribs.put("version", new AttributeValue().withN("0"));
// New(er) data types
attribs.put("booleanTrue", new AttributeValue().withBOOL(true));
attribs.put("booleanFalse", new AttributeValue().withBOOL(false));
attribs.put("nullValue", new AttributeValue().withNULL(true));
Map<String, AttributeValue> tmpMap = new HashMap<>(attribs);
attribs.put(
"listValue",
new AttributeValue()
.withL(
new AttributeValue().withS("I'm a string"),
new AttributeValue().withN("42"),
new AttributeValue().withS("Another string"),
new AttributeValue().withNS("1", "4", "7"),
new AttributeValue().withM(tmpMap),
new AttributeValue()
.withL(
new AttributeValue().withN("123"),
new AttributeValue().withNS("1", "200", "10", "15", "0"),
new AttributeValue().withSS("Goodbye", "Cruel", "World", "!"))));
tmpMap = new HashMap<>();
tmpMap.put("another string", new AttributeValue().withS("All around the cobbler's bench"));
tmpMap.put("next line", new AttributeValue().withSS("the monkey", "chased", "the weasel"));
tmpMap.put(
"more lyrics",
new AttributeValue()
.withL(
new AttributeValue().withS("the monkey"),
new AttributeValue().withS("thought twas"),
new AttributeValue().withS("all in fun")));
tmpMap.put(
"weasel",
new AttributeValue()
.withM(Collections.singletonMap("pop", new AttributeValue().withBOOL(true))));
attribs.put("song", new AttributeValue().withM(tmpMap));
context =
new EncryptionContext.Builder()
.withTableName("TableName")
.withHashKeyName("hashKey")
.withRangeKeyName("rangeKey")
.build();
}
@Test
public void testSetSignatureFieldName() {
assertNotNull(encryptor.getSignatureFieldName());
encryptor.setSignatureFieldName("A different value");
assertEquals("A different value", encryptor.getSignatureFieldName());
}
@Test
public void testSetMaterialDescriptionFieldName() {
assertNotNull(encryptor.getMaterialDescriptionFieldName());
encryptor.setMaterialDescriptionFieldName("A different value");
assertEquals("A different value", encryptor.getMaterialDescriptionFieldName());
}
@Test
public void fullEncryption() throws GeneralSecurityException {
Map<String, AttributeValue> encryptedAttributes =
encryptor.encryptAllFieldsExcept(
Collections.unmodifiableMap(attribs), context, "hashKey", "rangeKey", "version");
assertThat(encryptedAttributes, AttrMatcher.invert(attribs));
Map<String, AttributeValue> decryptedAttributes =
encryptor.decryptAllFieldsExcept(
Collections.unmodifiableMap(encryptedAttributes),
context,
"hashKey",
"rangeKey",
"version");
assertThat(decryptedAttributes, AttrMatcher.match(attribs));
// Make sure keys and version are not encrypted
assertAttrEquals(attribs.get("hashKey"), encryptedAttributes.get("hashKey"));
assertAttrEquals(attribs.get("rangeKey"), encryptedAttributes.get("rangeKey"));
assertAttrEquals(attribs.get("version"), encryptedAttributes.get("version"));
// Make sure String has been encrypted (we'll assume the others are correct as well)
assertTrue(encryptedAttributes.containsKey("stringValue"));
assertNull(encryptedAttributes.get("stringValue").getS());
assertNotNull(encryptedAttributes.get("stringValue").getB());
// Make sure we're calling the proper getEncryptionMaterials method
assertEquals(
"Wrong getEncryptionMaterials() called",
1,
prov.getCallCount("getEncryptionMaterials(EncryptionContext context)"));
}
@Test
public void ensureEncryptedAttributesUnmodified() throws GeneralSecurityException {
Map<String, AttributeValue> encryptedAttributes =
encryptor.encryptAllFieldsExcept(
Collections.unmodifiableMap(attribs), context, "hashKey", "rangeKey", "version");
// Using TreeMap before casting to string to avoid nondeterministic key orders.
String encryptedString = new TreeMap<>(encryptedAttributes).toString();
encryptor.decryptAllFieldsExcept(
Collections.unmodifiableMap(encryptedAttributes),
context,
"hashKey",
"rangeKey",
"version");
assertEquals(encryptedString, new TreeMap<>(encryptedAttributes).toString());
}
@Test(expectedExceptions = SignatureException.class)
public void fullEncryptionBadSignature() throws GeneralSecurityException {
Map<String, AttributeValue> encryptedAttributes =
encryptor.encryptAllFieldsExcept(
Collections.unmodifiableMap(attribs), context, "hashKey", "rangeKey", "version");
assertThat(encryptedAttributes, AttrMatcher.invert(attribs));
encryptedAttributes.get("hashKey").setN("666");
encryptor.decryptAllFieldsExcept(
Collections.unmodifiableMap(encryptedAttributes),
context,
"hashKey",
"rangeKey",
"version");
}
@Test(expectedExceptions = IllegalArgumentException.class)
public void badVersionNumber() throws GeneralSecurityException {
Map<String, AttributeValue> encryptedAttributes =
encryptor.encryptAllFieldsExcept(
Collections.unmodifiableMap(attribs), context, "hashKey", "rangeKey", "version");
ByteBuffer materialDescription =
encryptedAttributes.get(encryptor.getMaterialDescriptionFieldName()).getB();
byte[] rawArray = materialDescription.array();
assertEquals(0, rawArray[0]); // This will need to be kept in sync with the current version.
rawArray[0] = 100;
encryptedAttributes.put(
encryptor.getMaterialDescriptionFieldName(),
new AttributeValue().withB(ByteBuffer.wrap(rawArray)));
encryptor.decryptAllFieldsExcept(
Collections.unmodifiableMap(encryptedAttributes),
context,
"hashKey",
"rangeKey",
"version");
}
@Test
public void signedOnly() throws GeneralSecurityException {
Map<String, AttributeValue> encryptedAttributes =
encryptor.encryptAllFieldsExcept(attribs, context, attribs.keySet().toArray(new String[0]));
assertThat(encryptedAttributes, AttrMatcher.invert(attribs));
Map<String, AttributeValue> decryptedAttributes =
encryptor.decryptAllFieldsExcept(
encryptedAttributes, context, attribs.keySet().toArray(new String[0]));
assertThat(decryptedAttributes, AttrMatcher.match(attribs));
// Make sure keys and version are not encrypted
assertAttrEquals(attribs.get("hashKey"), encryptedAttributes.get("hashKey"));
assertAttrEquals(attribs.get("rangeKey"), encryptedAttributes.get("rangeKey"));
assertAttrEquals(attribs.get("version"), encryptedAttributes.get("version"));
// Make sure String has not been encrypted (we'll assume the others are correct as well)
assertAttrEquals(attribs.get("stringValue"), encryptedAttributes.get("stringValue"));
}
@Test
public void signedOnlyNullCryptoKey() throws GeneralSecurityException {
prov =
new InstrumentedEncryptionMaterialsProvider(
new SymmetricStaticProvider(null, macKey, Collections.<String, String>emptyMap()));
encryptor = DynamoDBEncryptor.getInstance(prov, "encryptor-");
Map<String, AttributeValue> encryptedAttributes =
encryptor.encryptAllFieldsExcept(attribs, context, attribs.keySet().toArray(new String[0]));
assertThat(encryptedAttributes, AttrMatcher.invert(attribs));
Map<String, AttributeValue> decryptedAttributes =
encryptor.decryptAllFieldsExcept(
encryptedAttributes, context, attribs.keySet().toArray(new String[0]));
assertThat(decryptedAttributes, AttrMatcher.match(attribs));
// Make sure keys and version are not encrypted
assertAttrEquals(attribs.get("hashKey"), encryptedAttributes.get("hashKey"));
assertAttrEquals(attribs.get("rangeKey"), encryptedAttributes.get("rangeKey"));
assertAttrEquals(attribs.get("version"), encryptedAttributes.get("version"));
// Make sure String has not been encrypted (we'll assume the others are correct as well)
assertAttrEquals(attribs.get("stringValue"), encryptedAttributes.get("stringValue"));
}
@Test(expectedExceptions = SignatureException.class)
public void signedOnlyBadSignature() throws GeneralSecurityException {
Map<String, AttributeValue> encryptedAttributes =
encryptor.encryptAllFieldsExcept(attribs, context, attribs.keySet().toArray(new String[0]));
assertThat(encryptedAttributes, AttrMatcher.invert(attribs));
encryptedAttributes.get("hashKey").setN("666");
encryptor.decryptAllFieldsExcept(
encryptedAttributes, context, attribs.keySet().toArray(new String[0]));
}
@Test(expectedExceptions = SignatureException.class)
public void signedOnlyNoSignature() throws GeneralSecurityException {
Map<String, AttributeValue> encryptedAttributes =
encryptor.encryptAllFieldsExcept(attribs, context, attribs.keySet().toArray(new String[0]));
assertThat(encryptedAttributes, AttrMatcher.invert(attribs));
encryptedAttributes.remove(encryptor.getSignatureFieldName());
encryptor.decryptAllFieldsExcept(
encryptedAttributes, context, attribs.keySet().toArray(new String[0]));
}
@Test
public void RsaSignedOnly() throws GeneralSecurityException {
KeyPairGenerator rsaGen = KeyPairGenerator.getInstance("RSA");
rsaGen.initialize(2048, Utils.getRng());
KeyPair sigPair = rsaGen.generateKeyPair();
encryptor =
DynamoDBEncryptor.getInstance(
new SymmetricStaticProvider(
encryptionKey, sigPair, Collections.<String, String>emptyMap()),
"encryptor-");
Map<String, AttributeValue> encryptedAttributes =
encryptor.encryptAllFieldsExcept(attribs, context, attribs.keySet().toArray(new String[0]));
assertThat(encryptedAttributes, AttrMatcher.invert(attribs));
Map<String, AttributeValue> decryptedAttributes =
encryptor.decryptAllFieldsExcept(
encryptedAttributes, context, attribs.keySet().toArray(new String[0]));
assertThat(decryptedAttributes, AttrMatcher.match(attribs));
// Make sure keys and version are not encrypted
assertAttrEquals(attribs.get("hashKey"), encryptedAttributes.get("hashKey"));
assertAttrEquals(attribs.get("rangeKey"), encryptedAttributes.get("rangeKey"));
assertAttrEquals(attribs.get("version"), encryptedAttributes.get("version"));
// Make sure String has not been encrypted (we'll assume the others are correct as well)
assertAttrEquals(attribs.get("stringValue"), encryptedAttributes.get("stringValue"));
}
@Test(expectedExceptions = SignatureException.class)
public void RsaSignedOnlyBadSignature() throws GeneralSecurityException {
KeyPairGenerator rsaGen = KeyPairGenerator.getInstance("RSA");
rsaGen.initialize(2048, Utils.getRng());
KeyPair sigPair = rsaGen.generateKeyPair();
encryptor =
DynamoDBEncryptor.getInstance(
new SymmetricStaticProvider(
encryptionKey, sigPair, Collections.<String, String>emptyMap()),
"encryptor-");
Map<String, AttributeValue> encryptedAttributes =
encryptor.encryptAllFieldsExcept(attribs, context, attribs.keySet().toArray(new String[0]));
assertThat(encryptedAttributes, AttrMatcher.invert(attribs));
encryptedAttributes.get("hashKey").setN("666");
encryptor.decryptAllFieldsExcept(
encryptedAttributes, context, attribs.keySet().toArray(new String[0]));
}
/**
* Tests that no exception is thrown when the encryption context override operator is null
*
* @throws GeneralSecurityException
*/
@Test
public void testNullEncryptionContextOperator() throws GeneralSecurityException {
DynamoDBEncryptor encryptor = DynamoDBEncryptor.getInstance(prov);
encryptor.setEncryptionContextOverrideOperator(null);
encryptor.encryptAllFieldsExcept(attribs, context, Collections.emptyList());
}
/**
* Tests decrypt and encrypt with an encryption context override operator
*
* @throws GeneralSecurityException
*/
@Test
public void testTableNameOverriddenEncryptionContextOperator() throws GeneralSecurityException {
// Ensure that the table name is different from what we override the table to.
assertThat(context.getTableName(), not(equalTo(OVERRIDDEN_TABLE_NAME)));
DynamoDBEncryptor encryptor = DynamoDBEncryptor.getInstance(prov);
encryptor.setEncryptionContextOverrideOperator(
overrideEncryptionContextTableName(context.getTableName(), OVERRIDDEN_TABLE_NAME));
Map<String, AttributeValue> encryptedItems =
encryptor.encryptAllFieldsExcept(attribs, context, Collections.emptyList());
Map<String, AttributeValue> decryptedItems =
encryptor.decryptAllFieldsExcept(encryptedItems, context, Collections.emptyList());
assertThat(decryptedItems, AttrMatcher.match(attribs));
}
/**
* Tests encrypt with an encryption context override operator, and a second encryptor without an
* override
*
* @throws GeneralSecurityException
*/
@Test
public void testTableNameOverriddenEncryptionContextOperatorWithSecondEncryptor()
throws GeneralSecurityException {
// Ensure that the table name is different from what we override the table to.
assertThat(context.getTableName(), not(equalTo(OVERRIDDEN_TABLE_NAME)));
DynamoDBEncryptor encryptor = DynamoDBEncryptor.getInstance(prov);
DynamoDBEncryptor encryptorWithoutOverride = DynamoDBEncryptor.getInstance(prov);
encryptor.setEncryptionContextOverrideOperator(
overrideEncryptionContextTableName(context.getTableName(), OVERRIDDEN_TABLE_NAME));
Map<String, AttributeValue> encryptedItems =
encryptor.encryptAllFieldsExcept(attribs, context, Collections.emptyList());
EncryptionContext expectedOverriddenContext =
new EncryptionContext.Builder(context).withTableName("TheBestTableName").build();
Map<String, AttributeValue> decryptedItems =
encryptorWithoutOverride.decryptAllFieldsExcept(
encryptedItems, expectedOverriddenContext, Collections.emptyList());
assertThat(decryptedItems, AttrMatcher.match(attribs));
}
/**
* Tests encrypt with an encryption context override operator, and a second encryptor without an
* override
*
* @throws GeneralSecurityException
*/
@Test(expectedExceptions = SignatureException.class)
public void
testTableNameOverriddenEncryptionContextOperatorWithSecondEncryptorButTheOriginalEncryptionContext()
throws GeneralSecurityException {
// Ensure that the table name is different from what we override the table to.
assertThat(context.getTableName(), not(equalTo(OVERRIDDEN_TABLE_NAME)));
DynamoDBEncryptor encryptor = DynamoDBEncryptor.getInstance(prov);
DynamoDBEncryptor encryptorWithoutOverride = DynamoDBEncryptor.getInstance(prov);
encryptor.setEncryptionContextOverrideOperator(
overrideEncryptionContextTableName(context.getTableName(), OVERRIDDEN_TABLE_NAME));
Map<String, AttributeValue> encryptedItems =
encryptor.encryptAllFieldsExcept(attribs, context, Collections.emptyList());
// Use the original encryption context, and expect a signature failure
Map<String, AttributeValue> decryptedItems =
encryptorWithoutOverride.decryptAllFieldsExcept(
encryptedItems, context, Collections.emptyList());
}
@Test
public void EcdsaSignedOnly() throws GeneralSecurityException {
encryptor = DynamoDBEncryptor.getInstance(getMaterialProviderwithECDSA());
Map<String, AttributeValue> encryptedAttributes =
encryptor.encryptAllFieldsExcept(attribs, context, attribs.keySet().toArray(new String[0]));
assertThat(encryptedAttributes, AttrMatcher.invert(attribs));
Map<String, AttributeValue> decryptedAttributes =
encryptor.decryptAllFieldsExcept(
encryptedAttributes, context, attribs.keySet().toArray(new String[0]));
assertThat(decryptedAttributes, AttrMatcher.match(attribs));
// Make sure keys and version are not encrypted
assertAttrEquals(attribs.get("hashKey"), encryptedAttributes.get("hashKey"));
assertAttrEquals(attribs.get("rangeKey"), encryptedAttributes.get("rangeKey"));
assertAttrEquals(attribs.get("version"), encryptedAttributes.get("version"));
// Make sure String has not been encrypted (we'll assume the others are correct as well)
assertAttrEquals(attribs.get("stringValue"), encryptedAttributes.get("stringValue"));
}
@Test(expectedExceptions = SignatureException.class)
public void EcdsaSignedOnlyBadSignature() throws GeneralSecurityException {
encryptor = DynamoDBEncryptor.getInstance(getMaterialProviderwithECDSA());
Map<String, AttributeValue> encryptedAttributes =
encryptor.encryptAllFieldsExcept(attribs, context, attribs.keySet().toArray(new String[0]));
assertThat(encryptedAttributes, AttrMatcher.invert(attribs));
encryptedAttributes.get("hashKey").setN("666");
encryptor.decryptAllFieldsExcept(
encryptedAttributes, context, attribs.keySet().toArray(new String[0]));
}
@Test
public void toByteArray() throws ReflectiveOperationException {
final byte[] expected = new byte[] {0, 1, 2, 3, 4, 5};
assertToByteArray("Wrap", expected, ByteBuffer.wrap(expected));
assertToByteArray("Wrap-RO", expected, ByteBuffer.wrap(expected).asReadOnlyBuffer());
assertToByteArray(
"Wrap-Truncated-Sliced",
expected,
ByteBuffer.wrap(new byte[] {0, 1, 2, 3, 4, 5, 6}, 0, 6).slice());
assertToByteArray(
"Wrap-Offset-Sliced",
expected,
ByteBuffer.wrap(new byte[] {6, 0, 1, 2, 3, 4, 5, 6}, 1, 6).slice());
assertToByteArray(
"Wrap-Truncated", expected, ByteBuffer.wrap(new byte[] {0, 1, 2, 3, 4, 5, 6}, 0, 6));
assertToByteArray(
"Wrap-Offset", expected, ByteBuffer.wrap(new byte[] {6, 0, 1, 2, 3, 4, 5, 6}, 1, 6));
ByteBuffer buff = ByteBuffer.allocate(expected.length + 10);
buff.put(expected);
buff.flip();
assertToByteArray("Normal", expected, buff);
buff = ByteBuffer.allocateDirect(expected.length + 10);
buff.put(expected);
buff.flip();
assertToByteArray("Direct", expected, buff);
}
@Test
public void testDecryptWithPlaintextItem() throws GeneralSecurityException {
Map<String, Set<EncryptionFlags>> attributeWithEmptyEncryptionFlags =
attribs.keySet().stream().collect(toMap(k -> k, k -> newHashSet()));
Map<String, AttributeValue> decryptedAttributes =
encryptor.decryptRecord(attribs, attributeWithEmptyEncryptionFlags, context);
assertThat(decryptedAttributes, AttrMatcher.match(attribs));
}
/*
Test decrypt with a map that contains a new key (not included in attribs) with an encryption flag set that contains ENCRYPT and SIGN.
*/
@Test
public void testDecryptWithPlainTextItemAndAdditionNewAttributeHavingEncryptionFlag()
throws GeneralSecurityException {
Map<String, Set<EncryptionFlags>> attributeWithEmptyEncryptionFlags =
attribs.keySet().stream().collect(toMap(k -> k, k -> newHashSet()));
attributeWithEmptyEncryptionFlags.put(
"newAttribute", Sets.newSet(EncryptionFlags.ENCRYPT, EncryptionFlags.SIGN));
Map<String, AttributeValue> decryptedAttributes =
encryptor.decryptRecord(attribs, attributeWithEmptyEncryptionFlags, context);
assertThat(decryptedAttributes, AttrMatcher.match(attribs));
}
private void assertToByteArray(
final String msg, final byte[] expected, final ByteBuffer testValue)
throws ReflectiveOperationException {
Method m = DynamoDBEncryptor.class.getDeclaredMethod("toByteArray", ByteBuffer.class);
m.setAccessible(true);
int oldPosition = testValue.position();
int oldLimit = testValue.limit();
assertArrayEquals(msg + ":Array", expected, (byte[]) m.invoke(null, testValue));
assertEquals(msg + ":Position", oldPosition, testValue.position());
assertEquals(msg + ":Limit", oldLimit, testValue.limit());
}
private void assertAttrEquals(AttributeValue o1, AttributeValue o2) {
Assert.assertEquals(o1.getB(), o2.getB());
assertSetsEqual(o1.getBS(), o2.getBS());
Assert.assertEquals(o1.getN(), o2.getN());
assertSetsEqual(o1.getNS(), o2.getNS());
Assert.assertEquals(o1.getS(), o2.getS());
assertSetsEqual(o1.getSS(), o2.getSS());
}
private <T> void assertSetsEqual(Collection<T> c1, Collection<T> c2) {
Assert.assertFalse(c1 == null ^ c2 == null);
if (c1 != null) {
Set<T> s1 = new HashSet<T>(c1);
Set<T> s2 = new HashSet<T>(c2);
Assert.assertEquals(s1, s2);
}
}
private EncryptionMaterialsProvider getMaterialProviderwithECDSA()
throws NoSuchAlgorithmException, InvalidAlgorithmParameterException, NoSuchProviderException {
Security.addProvider(new BouncyCastleProvider());
ECParameterSpec ecSpec = ECNamedCurveTable.getParameterSpec("secp384r1");
KeyPairGenerator g = KeyPairGenerator.getInstance("ECDSA", "BC");
g.initialize(ecSpec, Utils.getRng());
KeyPair keypair = g.generateKeyPair();
Map<String, String> description = new HashMap<String, String>();
description.put(DynamoDBEncryptor.DEFAULT_SIGNING_ALGORITHM_HEADER, "SHA384withECDSA");
return new SymmetricStaticProvider(null, keypair, description);
}
private static final class InstrumentedEncryptionMaterialsProvider
implements EncryptionMaterialsProvider {
private final EncryptionMaterialsProvider delegate;
private final ConcurrentHashMap<String, AtomicInteger> calls = new ConcurrentHashMap<>();
public InstrumentedEncryptionMaterialsProvider(EncryptionMaterialsProvider delegate) {
this.delegate = delegate;
}
@Override
public DecryptionMaterials getDecryptionMaterials(EncryptionContext context) {
incrementMethodCount("getDecryptionMaterials()");
return delegate.getDecryptionMaterials(context);
}
@Override
public EncryptionMaterials getEncryptionMaterials(EncryptionContext context) {
incrementMethodCount("getEncryptionMaterials(EncryptionContext context)");
return delegate.getEncryptionMaterials(context);
}
@Override
public void refresh() {
incrementMethodCount("refresh()");
delegate.refresh();
}
public int getCallCount(String method) {
AtomicInteger count = calls.get(method);
if (count != null) {
return count.intValue();
} else {
return 0;
}
}
@SuppressWarnings("unused")
public void resetCallCounts() {
calls.clear();
}
private void incrementMethodCount(String method) {
AtomicInteger oldValue = calls.putIfAbsent(method, new AtomicInteger(1));
if (oldValue != null) {
oldValue.incrementAndGet();
}
}
}
}
| 5,008 |
0 | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/sdkv1/com/amazonaws/services/dynamodbv2/datamodeling | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/sdkv1/com/amazonaws/services/dynamodbv2/datamodeling/encryption/DelegatedEncryptionTest.java | /*
* Copyright 2014 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.services.dynamodbv2.datamodeling.encryption;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertNotNull;
import static org.testng.AssertJUnit.assertNull;
import static org.testng.AssertJUnit.assertTrue;
import com.amazonaws.services.dynamodbv2.datamodeling.encryption.providers.EncryptionMaterialsProvider;
import com.amazonaws.services.dynamodbv2.datamodeling.encryption.providers.SymmetricStaticProvider;
import com.amazonaws.services.dynamodbv2.datamodeling.internal.Utils;
import com.amazonaws.services.dynamodbv2.model.AttributeValue;
import com.amazonaws.services.dynamodbv2.testing.AttrMatcher;
import com.amazonaws.services.dynamodbv2.testing.TestDelegatedKey;
import java.nio.ByteBuffer;
import java.security.GeneralSecurityException;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.SignatureException;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import javax.crypto.spec.SecretKeySpec;
import org.testng.Assert;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
public class DelegatedEncryptionTest {
private static SecretKeySpec rawEncryptionKey;
private static SecretKeySpec rawMacKey;
private static DelegatedKey encryptionKey;
private static DelegatedKey macKey;
private EncryptionMaterialsProvider prov;
private DynamoDBEncryptor encryptor;
private Map<String, AttributeValue> attribs;
private EncryptionContext context;
@BeforeClass
public static void setupClass() throws Exception {
rawEncryptionKey = new SecretKeySpec(Utils.getRandom(32), "AES");
encryptionKey = new TestDelegatedKey(rawEncryptionKey);
rawMacKey = new SecretKeySpec(Utils.getRandom(32), "HmacSHA256");
macKey = new TestDelegatedKey(rawMacKey);
}
@BeforeMethod
public void setUp() throws Exception {
prov =
new SymmetricStaticProvider(encryptionKey, macKey, Collections.<String, String>emptyMap());
encryptor = DynamoDBEncryptor.getInstance(prov, "encryptor-");
attribs = new HashMap<String, AttributeValue>();
attribs.put("intValue", new AttributeValue().withN("123"));
attribs.put("stringValue", new AttributeValue().withS("Hello world!"));
attribs.put(
"byteArrayValue",
new AttributeValue().withB(ByteBuffer.wrap(new byte[] {0, 1, 2, 3, 4, 5})));
attribs.put("stringSet", new AttributeValue().withSS("Goodbye", "Cruel", "World", "?"));
attribs.put("intSet", new AttributeValue().withNS("1", "200", "10", "15", "0"));
attribs.put("hashKey", new AttributeValue().withN("5"));
attribs.put("rangeKey", new AttributeValue().withN("7"));
attribs.put("version", new AttributeValue().withN("0"));
context =
new EncryptionContext.Builder()
.withTableName("TableName")
.withHashKeyName("hashKey")
.withRangeKeyName("rangeKey")
.build();
}
@Test
public void testSetSignatureFieldName() {
assertNotNull(encryptor.getSignatureFieldName());
encryptor.setSignatureFieldName("A different value");
assertEquals("A different value", encryptor.getSignatureFieldName());
}
@Test
public void testSetMaterialDescriptionFieldName() {
assertNotNull(encryptor.getMaterialDescriptionFieldName());
encryptor.setMaterialDescriptionFieldName("A different value");
assertEquals("A different value", encryptor.getMaterialDescriptionFieldName());
}
@Test
public void fullEncryption() throws GeneralSecurityException {
Map<String, AttributeValue> encryptedAttributes =
encryptor.encryptAllFieldsExcept(
Collections.unmodifiableMap(attribs), context, "hashKey", "rangeKey", "version");
assertThat(encryptedAttributes, AttrMatcher.invert(attribs));
Map<String, AttributeValue> decryptedAttributes =
encryptor.decryptAllFieldsExcept(
Collections.unmodifiableMap(encryptedAttributes),
context,
"hashKey",
"rangeKey",
"version");
assertThat(decryptedAttributes, AttrMatcher.match(attribs));
// Make sure keys and version are not encrypted
assertAttrEquals(attribs.get("hashKey"), encryptedAttributes.get("hashKey"));
assertAttrEquals(attribs.get("rangeKey"), encryptedAttributes.get("rangeKey"));
assertAttrEquals(attribs.get("version"), encryptedAttributes.get("version"));
// Make sure String has been encrypted (we'll assume the others are correct as well)
assertTrue(encryptedAttributes.containsKey("stringValue"));
assertNull(encryptedAttributes.get("stringValue").getS());
assertNotNull(encryptedAttributes.get("stringValue").getB());
}
@Test(expectedExceptions = SignatureException.class)
public void fullEncryptionBadSignature() throws GeneralSecurityException {
Map<String, AttributeValue> encryptedAttributes =
encryptor.encryptAllFieldsExcept(
Collections.unmodifiableMap(attribs), context, "hashKey", "rangeKey", "version");
assertThat(encryptedAttributes, AttrMatcher.invert(attribs));
encryptedAttributes.get("hashKey").setN("666");
encryptor.decryptAllFieldsExcept(
Collections.unmodifiableMap(encryptedAttributes),
context,
"hashKey",
"rangeKey",
"version");
}
@Test(expectedExceptions = IllegalArgumentException.class)
public void badVersionNumber() throws GeneralSecurityException {
Map<String, AttributeValue> encryptedAttributes =
encryptor.encryptAllFieldsExcept(
Collections.unmodifiableMap(attribs), context, "hashKey", "rangeKey", "version");
ByteBuffer materialDescription =
encryptedAttributes.get(encryptor.getMaterialDescriptionFieldName()).getB();
byte[] rawArray = materialDescription.array();
assertEquals(0, rawArray[0]); // This will need to be kept in sync with the current version.
rawArray[0] = 100;
encryptedAttributes.put(
encryptor.getMaterialDescriptionFieldName(),
new AttributeValue().withB(ByteBuffer.wrap(rawArray)));
encryptor.decryptAllFieldsExcept(
Collections.unmodifiableMap(encryptedAttributes),
context,
"hashKey",
"rangeKey",
"version");
}
@Test
public void signedOnly() throws GeneralSecurityException {
Map<String, AttributeValue> encryptedAttributes =
encryptor.encryptAllFieldsExcept(attribs, context, attribs.keySet().toArray(new String[0]));
assertThat(encryptedAttributes, AttrMatcher.invert(attribs));
Map<String, AttributeValue> decryptedAttributes =
encryptor.decryptAllFieldsExcept(
encryptedAttributes, context, attribs.keySet().toArray(new String[0]));
assertThat(decryptedAttributes, AttrMatcher.match(attribs));
// Make sure keys and version are not encrypted
assertAttrEquals(attribs.get("hashKey"), encryptedAttributes.get("hashKey"));
assertAttrEquals(attribs.get("rangeKey"), encryptedAttributes.get("rangeKey"));
assertAttrEquals(attribs.get("version"), encryptedAttributes.get("version"));
// Make sure String has not been encrypted (we'll assume the others are correct as well)
assertAttrEquals(attribs.get("stringValue"), encryptedAttributes.get("stringValue"));
}
@Test
public void signedOnlyNullCryptoKey() throws GeneralSecurityException {
prov = new SymmetricStaticProvider(null, macKey, Collections.<String, String>emptyMap());
encryptor = DynamoDBEncryptor.getInstance(prov, "encryptor-");
Map<String, AttributeValue> encryptedAttributes =
encryptor.encryptAllFieldsExcept(attribs, context, attribs.keySet().toArray(new String[0]));
assertThat(encryptedAttributes, AttrMatcher.invert(attribs));
Map<String, AttributeValue> decryptedAttributes =
encryptor.decryptAllFieldsExcept(
encryptedAttributes, context, attribs.keySet().toArray(new String[0]));
assertThat(decryptedAttributes, AttrMatcher.match(attribs));
// Make sure keys and version are not encrypted
assertAttrEquals(attribs.get("hashKey"), encryptedAttributes.get("hashKey"));
assertAttrEquals(attribs.get("rangeKey"), encryptedAttributes.get("rangeKey"));
assertAttrEquals(attribs.get("version"), encryptedAttributes.get("version"));
// Make sure String has not been encrypted (we'll assume the others are correct as well)
assertAttrEquals(attribs.get("stringValue"), encryptedAttributes.get("stringValue"));
}
@Test(expectedExceptions = SignatureException.class)
public void signedOnlyBadSignature() throws GeneralSecurityException {
Map<String, AttributeValue> encryptedAttributes =
encryptor.encryptAllFieldsExcept(attribs, context, attribs.keySet().toArray(new String[0]));
assertThat(encryptedAttributes, AttrMatcher.invert(attribs));
encryptedAttributes.get("hashKey").setN("666");
encryptor.decryptAllFieldsExcept(
encryptedAttributes, context, attribs.keySet().toArray(new String[0]));
}
@Test(expectedExceptions = SignatureException.class)
public void signedOnlyNoSignature() throws GeneralSecurityException {
Map<String, AttributeValue> encryptedAttributes =
encryptor.encryptAllFieldsExcept(attribs, context, attribs.keySet().toArray(new String[0]));
assertThat(encryptedAttributes, AttrMatcher.invert(attribs));
encryptedAttributes.remove(encryptor.getSignatureFieldName());
encryptor.decryptAllFieldsExcept(
encryptedAttributes, context, attribs.keySet().toArray(new String[0]));
}
@Test
public void RsaSignedOnly() throws GeneralSecurityException {
KeyPairGenerator rsaGen = KeyPairGenerator.getInstance("RSA");
rsaGen.initialize(2048, Utils.getRng());
KeyPair sigPair = rsaGen.generateKeyPair();
encryptor =
DynamoDBEncryptor.getInstance(
new SymmetricStaticProvider(
encryptionKey, sigPair, Collections.<String, String>emptyMap()),
"encryptor-");
Map<String, AttributeValue> encryptedAttributes =
encryptor.encryptAllFieldsExcept(attribs, context, attribs.keySet().toArray(new String[0]));
assertThat(encryptedAttributes, AttrMatcher.invert(attribs));
Map<String, AttributeValue> decryptedAttributes =
encryptor.decryptAllFieldsExcept(
encryptedAttributes, context, attribs.keySet().toArray(new String[0]));
assertThat(decryptedAttributes, AttrMatcher.match(attribs));
// Make sure keys and version are not encrypted
assertAttrEquals(attribs.get("hashKey"), encryptedAttributes.get("hashKey"));
assertAttrEquals(attribs.get("rangeKey"), encryptedAttributes.get("rangeKey"));
assertAttrEquals(attribs.get("version"), encryptedAttributes.get("version"));
// Make sure String has not been encrypted (we'll assume the others are correct as well)
assertAttrEquals(attribs.get("stringValue"), encryptedAttributes.get("stringValue"));
}
@Test(expectedExceptions = SignatureException.class)
public void RsaSignedOnlyBadSignature() throws GeneralSecurityException {
KeyPairGenerator rsaGen = KeyPairGenerator.getInstance("RSA");
rsaGen.initialize(2048, Utils.getRng());
KeyPair sigPair = rsaGen.generateKeyPair();
encryptor =
DynamoDBEncryptor.getInstance(
new SymmetricStaticProvider(
encryptionKey, sigPair, Collections.<String, String>emptyMap()),
"encryptor-");
Map<String, AttributeValue> encryptedAttributes =
encryptor.encryptAllFieldsExcept(attribs, context, attribs.keySet().toArray(new String[0]));
assertThat(encryptedAttributes, AttrMatcher.invert(attribs));
encryptedAttributes.get("hashKey").setN("666");
encryptor.decryptAllFieldsExcept(
encryptedAttributes, context, attribs.keySet().toArray(new String[0]));
}
private void assertAttrEquals(AttributeValue o1, AttributeValue o2) {
Assert.assertEquals(o1.getB(), o2.getB());
assertSetsEqual(o1.getBS(), o2.getBS());
Assert.assertEquals(o1.getN(), o2.getN());
assertSetsEqual(o1.getNS(), o2.getNS());
Assert.assertEquals(o1.getS(), o2.getS());
assertSetsEqual(o1.getSS(), o2.getSS());
}
private <T> void assertSetsEqual(Collection<T> c1, Collection<T> c2) {
Assert.assertFalse(c1 == null ^ c2 == null);
if (c1 != null) {
Set<T> s1 = new HashSet<T>(c1);
Set<T> s2 = new HashSet<T>(c2);
Assert.assertEquals(s1, s2);
}
}
}
| 5,009 |
0 | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/sdkv1/com/amazonaws/services/dynamodbv2/datamodeling/encryption | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/sdkv1/com/amazonaws/services/dynamodbv2/datamodeling/encryption/materials/AsymmetricRawMaterialsTest.java | /*
* Copyright 2014 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.services.dynamodbv2.datamodeling.encryption.materials;
import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertFalse;
import java.security.GeneralSecurityException;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.HashMap;
import java.util.Map;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
public class AsymmetricRawMaterialsTest {
private static SecureRandom rnd;
private static KeyPair encryptionPair;
private static SecretKey macKey;
private static KeyPair sigPair;
private Map<String, String> description;
@BeforeClass
public static void setUpClass() throws NoSuchAlgorithmException {
rnd = new SecureRandom();
KeyPairGenerator rsaGen = KeyPairGenerator.getInstance("RSA");
rsaGen.initialize(2048, rnd);
encryptionPair = rsaGen.generateKeyPair();
sigPair = rsaGen.generateKeyPair();
KeyGenerator macGen = KeyGenerator.getInstance("HmacSHA256");
macGen.init(256, rnd);
macKey = macGen.generateKey();
}
@BeforeMethod
public void setUp() {
description = new HashMap<String, String>();
description.put("TestKey", "test value");
}
@Test
public void macNoDescription() throws GeneralSecurityException {
AsymmetricRawMaterials matEncryption = new AsymmetricRawMaterials(encryptionPair, macKey);
assertEquals(macKey, matEncryption.getSigningKey());
assertEquals(macKey, matEncryption.getVerificationKey());
assertFalse(matEncryption.getMaterialDescription().isEmpty());
SecretKey envelopeKey = matEncryption.getEncryptionKey();
assertEquals(envelopeKey, matEncryption.getDecryptionKey());
AsymmetricRawMaterials matDecryption =
new AsymmetricRawMaterials(encryptionPair, macKey, matEncryption.getMaterialDescription());
assertEquals(macKey, matDecryption.getSigningKey());
assertEquals(macKey, matDecryption.getVerificationKey());
assertEquals(envelopeKey, matDecryption.getEncryptionKey());
assertEquals(envelopeKey, matDecryption.getDecryptionKey());
}
@Test
public void macWithDescription() throws GeneralSecurityException {
AsymmetricRawMaterials matEncryption =
new AsymmetricRawMaterials(encryptionPair, macKey, description);
assertEquals(macKey, matEncryption.getSigningKey());
assertEquals(macKey, matEncryption.getVerificationKey());
assertFalse(matEncryption.getMaterialDescription().isEmpty());
assertEquals("test value", matEncryption.getMaterialDescription().get("TestKey"));
SecretKey envelopeKey = matEncryption.getEncryptionKey();
assertEquals(envelopeKey, matEncryption.getDecryptionKey());
AsymmetricRawMaterials matDecryption =
new AsymmetricRawMaterials(encryptionPair, macKey, matEncryption.getMaterialDescription());
assertEquals(macKey, matDecryption.getSigningKey());
assertEquals(macKey, matDecryption.getVerificationKey());
assertEquals(envelopeKey, matDecryption.getEncryptionKey());
assertEquals(envelopeKey, matDecryption.getDecryptionKey());
assertEquals("test value", matDecryption.getMaterialDescription().get("TestKey"));
}
@Test
public void sigNoDescription() throws GeneralSecurityException {
AsymmetricRawMaterials matEncryption = new AsymmetricRawMaterials(encryptionPair, sigPair);
assertEquals(sigPair.getPrivate(), matEncryption.getSigningKey());
assertEquals(sigPair.getPublic(), matEncryption.getVerificationKey());
assertFalse(matEncryption.getMaterialDescription().isEmpty());
SecretKey envelopeKey = matEncryption.getEncryptionKey();
assertEquals(envelopeKey, matEncryption.getDecryptionKey());
AsymmetricRawMaterials matDecryption =
new AsymmetricRawMaterials(encryptionPair, sigPair, matEncryption.getMaterialDescription());
assertEquals(sigPair.getPrivate(), matDecryption.getSigningKey());
assertEquals(sigPair.getPublic(), matDecryption.getVerificationKey());
assertEquals(envelopeKey, matDecryption.getEncryptionKey());
assertEquals(envelopeKey, matDecryption.getDecryptionKey());
}
@Test
public void sigWithDescription() throws GeneralSecurityException {
AsymmetricRawMaterials matEncryption =
new AsymmetricRawMaterials(encryptionPair, sigPair, description);
assertEquals(sigPair.getPrivate(), matEncryption.getSigningKey());
assertEquals(sigPair.getPublic(), matEncryption.getVerificationKey());
assertFalse(matEncryption.getMaterialDescription().isEmpty());
assertEquals("test value", matEncryption.getMaterialDescription().get("TestKey"));
SecretKey envelopeKey = matEncryption.getEncryptionKey();
assertEquals(envelopeKey, matEncryption.getDecryptionKey());
AsymmetricRawMaterials matDecryption =
new AsymmetricRawMaterials(encryptionPair, sigPair, matEncryption.getMaterialDescription());
assertEquals(sigPair.getPrivate(), matDecryption.getSigningKey());
assertEquals(sigPair.getPublic(), matDecryption.getVerificationKey());
assertEquals(envelopeKey, matDecryption.getEncryptionKey());
assertEquals(envelopeKey, matDecryption.getDecryptionKey());
assertEquals("test value", matDecryption.getMaterialDescription().get("TestKey"));
}
}
| 5,010 |
0 | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/sdkv1/com/amazonaws/services/dynamodbv2/datamodeling/encryption | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/sdkv1/com/amazonaws/services/dynamodbv2/datamodeling/encryption/materials/SymmetricRawMaterialsTest.java | /*
* Copyright 2014 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.services.dynamodbv2.datamodeling.encryption.materials;
import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertTrue;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.HashMap;
import java.util.Map;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
public class SymmetricRawMaterialsTest {
private static SecretKey encryptionKey;
private static SecretKey macKey;
private static KeyPair sigPair;
private static SecureRandom rnd;
private Map<String, String> description;
@BeforeClass
public static void setUpClass() throws NoSuchAlgorithmException {
rnd = new SecureRandom();
KeyPairGenerator rsaGen = KeyPairGenerator.getInstance("RSA");
rsaGen.initialize(2048, rnd);
sigPair = rsaGen.generateKeyPair();
KeyGenerator aesGen = KeyGenerator.getInstance("AES");
aesGen.init(128, rnd);
encryptionKey = aesGen.generateKey();
KeyGenerator macGen = KeyGenerator.getInstance("HmacSHA256");
macGen.init(256, rnd);
macKey = macGen.generateKey();
}
@BeforeMethod
public void setUp() {
description = new HashMap<String, String>();
description.put("TestKey", "test value");
}
@Test
public void macNoDescription() throws NoSuchAlgorithmException {
SymmetricRawMaterials mat = new SymmetricRawMaterials(encryptionKey, macKey);
assertEquals(encryptionKey, mat.getEncryptionKey());
assertEquals(encryptionKey, mat.getDecryptionKey());
assertEquals(macKey, mat.getSigningKey());
assertEquals(macKey, mat.getVerificationKey());
assertTrue(mat.getMaterialDescription().isEmpty());
}
@Test
public void macWithDescription() throws NoSuchAlgorithmException {
SymmetricRawMaterials mat = new SymmetricRawMaterials(encryptionKey, macKey, description);
assertEquals(encryptionKey, mat.getEncryptionKey());
assertEquals(encryptionKey, mat.getDecryptionKey());
assertEquals(macKey, mat.getSigningKey());
assertEquals(macKey, mat.getVerificationKey());
assertEquals(description, mat.getMaterialDescription());
assertEquals("test value", mat.getMaterialDescription().get("TestKey"));
}
@Test
public void sigNoDescription() throws NoSuchAlgorithmException {
SymmetricRawMaterials mat = new SymmetricRawMaterials(encryptionKey, sigPair);
assertEquals(encryptionKey, mat.getEncryptionKey());
assertEquals(encryptionKey, mat.getDecryptionKey());
assertEquals(sigPair.getPrivate(), mat.getSigningKey());
assertEquals(sigPair.getPublic(), mat.getVerificationKey());
assertTrue(mat.getMaterialDescription().isEmpty());
}
@Test
public void sigWithDescription() throws NoSuchAlgorithmException {
SymmetricRawMaterials mat = new SymmetricRawMaterials(encryptionKey, sigPair, description);
assertEquals(encryptionKey, mat.getEncryptionKey());
assertEquals(encryptionKey, mat.getDecryptionKey());
assertEquals(sigPair.getPrivate(), mat.getSigningKey());
assertEquals(sigPair.getPublic(), mat.getVerificationKey());
assertEquals(description, mat.getMaterialDescription());
assertEquals("test value", mat.getMaterialDescription().get("TestKey"));
}
}
| 5,011 |
0 | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/sdkv1/com/amazonaws/services/dynamodbv2/datamodeling/encryption | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/sdkv1/com/amazonaws/services/dynamodbv2/datamodeling/encryption/providers/DirectKmsMaterialProviderTest.java | /*
* Copyright 2014 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.services.dynamodbv2.datamodeling.encryption.providers;
import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertFalse;
import static org.testng.AssertJUnit.assertNotNull;
import static org.testng.AssertJUnit.assertNull;
import static org.testng.AssertJUnit.assertTrue;
import com.amazonaws.RequestClientOptions;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMappingException;
import com.amazonaws.services.dynamodbv2.datamodeling.encryption.EncryptionContext;
import com.amazonaws.services.dynamodbv2.datamodeling.encryption.materials.DecryptionMaterials;
import com.amazonaws.services.dynamodbv2.datamodeling.encryption.materials.EncryptionMaterials;
import com.amazonaws.services.dynamodbv2.datamodeling.encryption.materials.WrappedRawMaterials;
import com.amazonaws.services.dynamodbv2.model.AttributeValue;
import com.amazonaws.services.dynamodbv2.testing.FakeKMS;
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.GenerateDataKeyRequest;
import com.amazonaws.services.kms.model.GenerateDataKeyResult;
import com.amazonaws.util.Base64;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.security.GeneralSecurityException;
import java.security.Key;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
import javax.crypto.SecretKey;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
public class DirectKmsMaterialProviderTest {
private FakeKMS kms;
private String keyId;
private Map<String, String> description;
private EncryptionContext ctx;
@BeforeMethod
public void setUp() {
description = new HashMap<>();
description.put("TestKey", "test value");
description = Collections.unmodifiableMap(description);
ctx = new EncryptionContext.Builder().build();
kms = new FakeKMS();
keyId = kms.createKey().getKeyMetadata().getKeyId();
}
@Test
public void simple() throws GeneralSecurityException {
DirectKmsMaterialProvider prov = new DirectKmsMaterialProvider(kms, keyId);
EncryptionMaterials eMat = prov.getEncryptionMaterials(ctx);
SecretKey encryptionKey = eMat.getEncryptionKey();
assertNotNull(encryptionKey);
Key signingKey = eMat.getSigningKey();
assertNotNull(signingKey);
DecryptionMaterials dMat = prov.getDecryptionMaterials(ctx(eMat));
assertEquals(encryptionKey, dMat.getDecryptionKey());
assertEquals(signingKey, dMat.getVerificationKey());
String expectedEncAlg =
encryptionKey.getAlgorithm() + "/" + (encryptionKey.getEncoded().length * 8);
String expectedSigAlg = signingKey.getAlgorithm() + "/" + (signingKey.getEncoded().length * 8);
Map<String, String> kmsCtx = kms.getSingleEc();
assertEquals(expectedEncAlg, kmsCtx.get("*" + WrappedRawMaterials.CONTENT_KEY_ALGORITHM + "*"));
assertEquals(expectedSigAlg, kmsCtx.get("*amzn-ddb-sig-alg*"));
}
@Test
public void simpleWithKmsEc() throws GeneralSecurityException {
DirectKmsMaterialProvider prov = new DirectKmsMaterialProvider(kms, keyId);
Map<String, AttributeValue> attrVals = new HashMap<>();
attrVals.put("hk", new AttributeValue("HashKeyValue"));
attrVals.put("rk", new AttributeValue("RangeKeyValue"));
ctx =
new EncryptionContext.Builder()
.withHashKeyName("hk")
.withRangeKeyName("rk")
.withTableName("KmsTableName")
.withAttributeValues(attrVals)
.build();
EncryptionMaterials eMat = prov.getEncryptionMaterials(ctx);
SecretKey encryptionKey = eMat.getEncryptionKey();
assertNotNull(encryptionKey);
Key signingKey = eMat.getSigningKey();
assertNotNull(signingKey);
Map<String, String> kmsCtx = kms.getSingleEc();
assertEquals("HashKeyValue", kmsCtx.get("hk"));
assertEquals("RangeKeyValue", kmsCtx.get("rk"));
assertEquals("KmsTableName", kmsCtx.get("*aws-kms-table*"));
EncryptionContext dCtx =
new EncryptionContext.Builder(ctx(eMat))
.withHashKeyName("hk")
.withRangeKeyName("rk")
.withTableName("KmsTableName")
.withAttributeValues(attrVals)
.build();
DecryptionMaterials dMat = prov.getDecryptionMaterials(dCtx);
assertEquals(encryptionKey, dMat.getDecryptionKey());
assertEquals(signingKey, dMat.getVerificationKey());
}
@Test
public void simpleWithKmsEc2() throws GeneralSecurityException {
DirectKmsMaterialProvider prov = new DirectKmsMaterialProvider(kms, keyId);
Map<String, AttributeValue> attrVals = new HashMap<>();
attrVals.put("hk", new AttributeValue().withN("10"));
attrVals.put("rk", new AttributeValue().withN("20"));
ctx =
new EncryptionContext.Builder()
.withHashKeyName("hk")
.withRangeKeyName("rk")
.withTableName("KmsTableName")
.withAttributeValues(attrVals)
.build();
EncryptionMaterials eMat = prov.getEncryptionMaterials(ctx);
SecretKey encryptionKey = eMat.getEncryptionKey();
assertNotNull(encryptionKey);
Key signingKey = eMat.getSigningKey();
assertNotNull(signingKey);
Map<String, String> kmsCtx = kms.getSingleEc();
assertEquals("10", kmsCtx.get("hk"));
assertEquals("20", kmsCtx.get("rk"));
assertEquals("KmsTableName", kmsCtx.get("*aws-kms-table*"));
EncryptionContext dCtx =
new EncryptionContext.Builder(ctx(eMat))
.withHashKeyName("hk")
.withRangeKeyName("rk")
.withTableName("KmsTableName")
.withAttributeValues(attrVals)
.build();
DecryptionMaterials dMat = prov.getDecryptionMaterials(dCtx);
assertEquals(encryptionKey, dMat.getDecryptionKey());
assertEquals(signingKey, dMat.getVerificationKey());
}
@Test
public void simpleWithKmsEc3() throws GeneralSecurityException {
DirectKmsMaterialProvider prov = new DirectKmsMaterialProvider(kms, keyId);
Map<String, AttributeValue> attrVals = new HashMap<>();
attrVals.put(
"hk", new AttributeValue().withB(ByteBuffer.wrap("Foo".getBytes(StandardCharsets.UTF_8))));
attrVals.put(
"rk", new AttributeValue().withB(ByteBuffer.wrap("Bar".getBytes(StandardCharsets.UTF_8))));
ctx =
new EncryptionContext.Builder()
.withHashKeyName("hk")
.withRangeKeyName("rk")
.withTableName("KmsTableName")
.withAttributeValues(attrVals)
.build();
EncryptionMaterials eMat = prov.getEncryptionMaterials(ctx);
SecretKey encryptionKey = eMat.getEncryptionKey();
assertNotNull(encryptionKey);
Key signingKey = eMat.getSigningKey();
assertNotNull(signingKey);
assertNotNull(signingKey);
Map<String, String> kmsCtx = kms.getSingleEc();
assertEquals(Base64.encodeAsString("Foo".getBytes(StandardCharsets.UTF_8)), kmsCtx.get("hk"));
assertEquals(Base64.encodeAsString("Bar".getBytes(StandardCharsets.UTF_8)), kmsCtx.get("rk"));
assertEquals("KmsTableName", kmsCtx.get("*aws-kms-table*"));
EncryptionContext dCtx =
new EncryptionContext.Builder(ctx(eMat))
.withHashKeyName("hk")
.withRangeKeyName("rk")
.withTableName("KmsTableName")
.withAttributeValues(attrVals)
.build();
DecryptionMaterials dMat = prov.getDecryptionMaterials(dCtx);
assertEquals(encryptionKey, dMat.getDecryptionKey());
assertEquals(signingKey, dMat.getVerificationKey());
}
@Test
public void randomEnvelopeKeys() throws GeneralSecurityException {
DirectKmsMaterialProvider prov = new DirectKmsMaterialProvider(kms, keyId);
EncryptionMaterials eMat = prov.getEncryptionMaterials(ctx);
SecretKey encryptionKey = eMat.getEncryptionKey();
assertNotNull(encryptionKey);
EncryptionMaterials eMat2 = prov.getEncryptionMaterials(ctx);
SecretKey encryptionKey2 = eMat2.getEncryptionKey();
assertFalse("Envelope keys must be different", encryptionKey.equals(encryptionKey2));
}
@Test
public void testRefresh() {
// This does nothing, make sure we don't throw and exception.
DirectKmsMaterialProvider prov = new DirectKmsMaterialProvider(kms, keyId);
prov.refresh();
}
@Test
public void explicitContentKeyAlgorithm() throws GeneralSecurityException {
Map<String, String> desc = new HashMap<>();
desc.put(WrappedRawMaterials.CONTENT_KEY_ALGORITHM, "AES");
DirectKmsMaterialProvider prov = new DirectKmsMaterialProvider(kms, keyId, desc);
EncryptionMaterials eMat = prov.getEncryptionMaterials(ctx);
SecretKey encryptionKey = eMat.getEncryptionKey();
assertNotNull(encryptionKey);
DecryptionMaterials dMat = prov.getDecryptionMaterials(ctx(eMat));
assertEquals(
"AES", eMat.getMaterialDescription().get(WrappedRawMaterials.CONTENT_KEY_ALGORITHM));
assertEquals(encryptionKey, dMat.getDecryptionKey());
}
@Test
public void explicitContentKeyLength128() throws GeneralSecurityException {
Map<String, String> desc = new HashMap<>();
desc.put(WrappedRawMaterials.CONTENT_KEY_ALGORITHM, "AES/128");
DirectKmsMaterialProvider prov = new DirectKmsMaterialProvider(kms, keyId, desc);
EncryptionMaterials eMat = prov.getEncryptionMaterials(ctx);
SecretKey encryptionKey = eMat.getEncryptionKey();
assertNotNull(encryptionKey);
assertEquals(16, encryptionKey.getEncoded().length); // 128 Bits
DecryptionMaterials dMat = prov.getDecryptionMaterials(ctx(eMat));
assertEquals(
"AES/128", eMat.getMaterialDescription().get(WrappedRawMaterials.CONTENT_KEY_ALGORITHM));
assertEquals("AES", eMat.getEncryptionKey().getAlgorithm());
assertEquals(encryptionKey, dMat.getDecryptionKey());
}
@Test
public void explicitContentKeyLength256() throws GeneralSecurityException {
Map<String, String> desc = new HashMap<>();
desc.put(WrappedRawMaterials.CONTENT_KEY_ALGORITHM, "AES/256");
DirectKmsMaterialProvider prov = new DirectKmsMaterialProvider(kms, keyId, desc);
EncryptionMaterials eMat = prov.getEncryptionMaterials(ctx);
SecretKey encryptionKey = eMat.getEncryptionKey();
assertNotNull(encryptionKey);
assertEquals(32, encryptionKey.getEncoded().length); // 256 Bits
DecryptionMaterials dMat = prov.getDecryptionMaterials(ctx(eMat));
assertEquals(
"AES/256", eMat.getMaterialDescription().get(WrappedRawMaterials.CONTENT_KEY_ALGORITHM));
assertEquals("AES", eMat.getEncryptionKey().getAlgorithm());
assertEquals(encryptionKey, dMat.getDecryptionKey());
}
@Test
public void extendedWithDerivedEncryptionKeyId() throws GeneralSecurityException {
ExtendedKmsMaterialProvider prov =
new ExtendedKmsMaterialProvider(kms, keyId, "encryptionKeyId");
String customKeyId = kms.createKey().getKeyMetadata().getKeyId();
Map<String, AttributeValue> attrVals = new HashMap<>();
attrVals.put("hk", new AttributeValue().withN("10"));
attrVals.put("rk", new AttributeValue().withN("20"));
attrVals.put("encryptionKeyId", new AttributeValue().withS(customKeyId));
ctx =
new EncryptionContext.Builder()
.withHashKeyName("hk")
.withRangeKeyName("rk")
.withTableName("KmsTableName")
.withAttributeValues(attrVals)
.build();
EncryptionMaterials eMat = prov.getEncryptionMaterials(ctx);
SecretKey encryptionKey = eMat.getEncryptionKey();
assertNotNull(encryptionKey);
Key signingKey = eMat.getSigningKey();
assertNotNull(signingKey);
Map<String, String> kmsCtx = kms.getSingleEc();
assertEquals("10", kmsCtx.get("hk"));
assertEquals("20", kmsCtx.get("rk"));
assertEquals("KmsTableName", kmsCtx.get("*aws-kms-table*"));
EncryptionContext dCtx =
new EncryptionContext.Builder(ctx(eMat))
.withHashKeyName("hk")
.withRangeKeyName("rk")
.withTableName("KmsTableName")
.withAttributeValues(attrVals)
.build();
DecryptionMaterials dMat = prov.getDecryptionMaterials(dCtx);
assertEquals(encryptionKey, dMat.getDecryptionKey());
assertEquals(signingKey, dMat.getVerificationKey());
}
@Test(expectedExceptions = DynamoDBMappingException.class)
public void encryptionKeyIdMismatch() throws GeneralSecurityException {
DirectKmsMaterialProvider directProvider = new DirectKmsMaterialProvider(kms, keyId);
String customKeyId = kms.createKey().getKeyMetadata().getKeyId();
Map<String, AttributeValue> attrVals = new HashMap<>();
attrVals.put("hk", new AttributeValue().withN("10"));
attrVals.put("rk", new AttributeValue().withN("20"));
attrVals.put("encryptionKeyId", new AttributeValue().withS(customKeyId));
ctx =
new EncryptionContext.Builder()
.withHashKeyName("hk")
.withRangeKeyName("rk")
.withTableName("KmsTableName")
.withAttributeValues(attrVals)
.build();
EncryptionMaterials eMat = directProvider.getEncryptionMaterials(ctx);
EncryptionContext dCtx =
new EncryptionContext.Builder(ctx(eMat))
.withHashKeyName("hk")
.withRangeKeyName("rk")
.withTableName("KmsTableName")
.withAttributeValues(attrVals)
.build();
ExtendedKmsMaterialProvider extendedProvider =
new ExtendedKmsMaterialProvider(kms, keyId, "encryptionKeyId");
extendedProvider.getDecryptionMaterials(dCtx);
}
@Test(expectedExceptions = DynamoDBMappingException.class)
public void missingEncryptionKeyId() throws GeneralSecurityException {
ExtendedKmsMaterialProvider prov =
new ExtendedKmsMaterialProvider(kms, keyId, "encryptionKeyId");
Map<String, AttributeValue> attrVals = new HashMap<>();
attrVals.put("hk", new AttributeValue().withN("10"));
attrVals.put("rk", new AttributeValue().withN("20"));
ctx =
new EncryptionContext.Builder()
.withHashKeyName("hk")
.withRangeKeyName("rk")
.withTableName("KmsTableName")
.withAttributeValues(attrVals)
.build();
prov.getEncryptionMaterials(ctx);
}
@Test
public void generateDataKeyIsCalledWith256NumberOfBits() {
final AtomicBoolean gdkCalled = new AtomicBoolean(false);
AWSKMS kmsSpy =
new FakeKMS() {
@Override
public GenerateDataKeyResult generateDataKey(GenerateDataKeyRequest r) {
gdkCalled.set(true);
assertEquals((Integer) 32, r.getNumberOfBytes());
assertNull(r.getKeySpec());
return super.generateDataKey(r);
}
};
assertFalse(gdkCalled.get());
new DirectKmsMaterialProvider(kmsSpy, keyId).getEncryptionMaterials(ctx);
assertTrue(gdkCalled.get());
}
@Test
public void userAgentIsAdded() {
AWSKMS kmsSpy =
new FakeKMS() {
@Override
public GenerateDataKeyResult generateDataKey(GenerateDataKeyRequest r) {
assertTrue(
r.getRequestClientOptions()
.getClientMarker(RequestClientOptions.Marker.USER_AGENT)
.contains(DirectKmsMaterialProvider.USER_AGENT_PREFIX));
return super.generateDataKey(r);
}
};
new DirectKmsMaterialProvider(kmsSpy, keyId).getEncryptionMaterials(ctx);
}
private static class ExtendedKmsMaterialProvider extends DirectKmsMaterialProvider {
private final String encryptionKeyIdAttributeName;
public ExtendedKmsMaterialProvider(
AWSKMS kms, String encryptionKeyId, String encryptionKeyIdAttributeName) {
super(kms, encryptionKeyId);
this.encryptionKeyIdAttributeName = encryptionKeyIdAttributeName;
}
@Override
protected String selectEncryptionKeyId(EncryptionContext context)
throws DynamoDBMappingException {
if (!context.getAttributeValues().containsKey(encryptionKeyIdAttributeName)) {
throw new DynamoDBMappingException("encryption key attribute is not provided");
}
return context.getAttributeValues().get(encryptionKeyIdAttributeName).getS();
}
@Override
protected void validateEncryptionKeyId(String encryptionKeyId, EncryptionContext context)
throws DynamoDBMappingException {
if (!context.getAttributeValues().containsKey(encryptionKeyIdAttributeName)) {
throw new DynamoDBMappingException("encryption key attribute is not provided");
}
String customEncryptionKeyId =
context.getAttributeValues().get(encryptionKeyIdAttributeName).getS();
if (!customEncryptionKeyId.equals(encryptionKeyId)) {
throw new DynamoDBMappingException("encryption key ids do not match.");
}
}
@Override
protected DecryptResult decrypt(DecryptRequest request, EncryptionContext context) {
return super.decrypt(request, context);
}
@Override
protected GenerateDataKeyResult generateDataKey(
GenerateDataKeyRequest request, EncryptionContext context) {
return super.generateDataKey(request, context);
}
}
private static EncryptionContext ctx(EncryptionMaterials mat) {
return new EncryptionContext.Builder()
.withMaterialDescription(mat.getMaterialDescription())
.build();
}
}
| 5,012 |
0 | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/sdkv1/com/amazonaws/services/dynamodbv2/datamodeling/encryption | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/sdkv1/com/amazonaws/services/dynamodbv2/datamodeling/encryption/providers/KeyStoreMaterialsProviderTest.java | /*
* Copyright 2014 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.services.dynamodbv2.datamodeling.encryption.providers;
import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertNotNull;
import static org.testng.AssertJUnit.assertNull;
import static org.testng.AssertJUnit.fail;
import com.amazonaws.services.dynamodbv2.datamodeling.encryption.EncryptionContext;
import com.amazonaws.services.dynamodbv2.datamodeling.encryption.materials.DecryptionMaterials;
import com.amazonaws.services.dynamodbv2.datamodeling.encryption.materials.EncryptionMaterials;
import com.amazonaws.services.dynamodbv2.datamodeling.internal.Utils;
import com.amazonaws.util.Base64;
import java.io.ByteArrayInputStream;
import java.security.KeyFactory;
import java.security.KeyStore;
import java.security.KeyStore.PasswordProtection;
import java.security.KeyStore.PrivateKeyEntry;
import java.security.KeyStore.SecretKeyEntry;
import java.security.PrivateKey;
import java.security.cert.Certificate;
import java.security.cert.CertificateFactory;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
public class KeyStoreMaterialsProviderTest {
private static final String certPem =
"MIIDbTCCAlWgAwIBAgIJANdRvzVsW1CIMA0GCSqGSIb3DQEBBQUAME0xCzAJBgNV"
+ "BAYTAlVTMRMwEQYDVQQIDApXYXNoaW5ndG9uMQwwCgYDVQQKDANBV1MxGzAZBgNV"
+ "BAMMEktleVN0b3JlIFRlc3QgQ2VydDAeFw0xMzA1MDgyMzMyMjBaFw0xMzA2MDcy"
+ "MzMyMjBaME0xCzAJBgNVBAYTAlVTMRMwEQYDVQQIDApXYXNoaW5ndG9uMQwwCgYD"
+ "VQQKDANBV1MxGzAZBgNVBAMMEktleVN0b3JlIFRlc3QgQ2VydDCCASIwDQYJKoZI"
+ "hvcNAQEBBQADggEPADCCAQoCggEBAJ8+umOX8x/Ma4OZishtYpcA676bwK5KScf3"
+ "w+YGM37L12KTdnOyieiGtRW8p0fS0YvnhmVTvaky09I33bH+qy9gliuNL2QkyMxp"
+ "uu1IwkTKKuB67CaKT6osYJLFxV/OwHcaZnTszzDgbAVg/Z+8IZxhPgxMzMa+7nDn"
+ "hEm9Jd+EONq3PnRagnFeLNbMIePprdJzXHyNNiZKRRGQ/Mo9rr7mqMLSKnFNsmzB"
+ "OIfeZM8nXeg+cvlmtXl72obwnGGw2ksJfaxTPm4eEhzRoAgkbjPPLHbwiJlc+GwF"
+ "i8kh0Y3vQTj/gOFE4nzipkm7ux1lsGHNRVpVDWpjNd8Fl9JFELkCAwEAAaNQME4w"
+ "HQYDVR0OBBYEFM0oGUuFAWlLXZaMXoJgGZxWqfOxMB8GA1UdIwQYMBaAFM0oGUuF"
+ "AWlLXZaMXoJgGZxWqfOxMAwGA1UdEwQFMAMBAf8wDQYJKoZIhvcNAQEFBQADggEB"
+ "AAXCsXeC8ZRxovP0Wc6C5qv3d7dtgJJVzHwoIRt2YR3yScBa1XI40GKT80jP3MYH"
+ "8xMu3mBQtcYrgRKZBy4GpHAyxoFTnPcuzq5Fg7dw7fx4E4OKIbWOahdxwtbVxQfZ"
+ "UHnGG88Z0bq2twj7dALGyJhUDdiccckJGmJPOFMzjqsvoAu0n/p7eS6y5WZ5ewqw"
+ "p7VwYOP3N9wVV7Podmkh1os+eCcp9GoFf0MHBMFXi2Ps2azKx8wHRIA5D1MZv/Va"
+ "4L4/oTBKCjORpFlP7EhMksHBYnjqXLDP6awPMAgQNYB5J9zX6GfJsAgly3t4Rjr5"
+ "cLuNYBmRuByFGo+SOdrj6D8=";
private static final String keyPem =
"MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCfPrpjl/MfzGuD"
+ "mYrIbWKXAOu+m8CuSknH98PmBjN+y9dik3ZzsonohrUVvKdH0tGL54ZlU72pMtPS"
+ "N92x/qsvYJYrjS9kJMjMabrtSMJEyirgeuwmik+qLGCSxcVfzsB3GmZ07M8w4GwF"
+ "YP2fvCGcYT4MTMzGvu5w54RJvSXfhDjatz50WoJxXizWzCHj6a3Sc1x8jTYmSkUR"
+ "kPzKPa6+5qjC0ipxTbJswTiH3mTPJ13oPnL5ZrV5e9qG8JxhsNpLCX2sUz5uHhIc"
+ "0aAIJG4zzyx28IiZXPhsBYvJIdGN70E4/4DhROJ84qZJu7sdZbBhzUVaVQ1qYzXf"
+ "BZfSRRC5AgMBAAECggEBAJMwx9eGe5LIwBfDtCPN93LbxwtHq7FtuQS8XrYexTpN"
+ "76eN5c7LF+11lauh1HzuwAEw32iJHqVl9aQ5PxFm85O3ExbuSP+ngHJwx/bLacVr"
+ "mHYlKGH3Net1WU5Qvz7vO7bbEBjDSj9DMJVIMSWUHv0MZO25jw2lLX/ufrgpvPf7"
+ "KXSgXg/8uV7PbnTbBDNlg02u8eOc+IbH4O8XDKAhD+YQ8AE3pxtopJbb912U/cJs"
+ "Y0hQ01zbkWYH7wL9BeQmR7+TEjjtr/IInNjnXmaOmSX867/rTSTuozaVrl1Ce7r8"
+ "EmUDg9ZLZeKfoNYovMy08wnxWVX2J+WnNDjNiSOm+IECgYEA0v3jtGrOnKbd0d9E"
+ "dbyIuhjgnwp+UsgALIiBeJYjhFS9NcWgs+02q/0ztqOK7g088KBBQOmiA+frLIVb"
+ "uNCt/3jF6kJvHYkHMZ0eBEstxjVSM2UcxzJ6ceHZ68pmrru74382TewVosxccNy0"
+ "glsUWNN0t5KQDcetaycRYg50MmcCgYEAwTb8klpNyQE8AWxVQlbOIEV24iarXxex"
+ "7HynIg9lSeTzquZOXjp0m5omQ04psil2gZ08xjiudG+Dm7QKgYQcxQYUtZPQe15K"
+ "m+2hQM0jA7tRfM1NAZHoTmUlYhzRNX6GWAqQXOgjOqBocT4ySBXRaSQq9zuZu36s"
+ "fI17knap798CgYArDa2yOf0xEAfBdJqmn7MSrlLfgSenwrHuZGhu78wNi7EUUOBq"
+ "9qOqUr+DrDmEO+VMgJbwJPxvaZqeehPuUX6/26gfFjFQSI7UO+hNHf4YLPc6D47g"
+ "wtcjd9+c8q8jRqGfWWz+V4dOsf7G9PJMi0NKoNN3RgvpE+66J72vUZ26TwKBgEUq"
+ "DdfGA7pEetp3kT2iHT9oHlpuRUJRFRv2s015/WQqVR+EOeF5Q2zADZpiTIK+XPGg"
+ "+7Rpbem4UYBXPruGM1ZECv3E4AiJhGO0+Nhdln8reswWIc7CEEqf4nXwouNnW2gA"
+ "wBTB9Hp0GW8QOKedR80/aTH/X9TCT7R2YRnY6JQ5AoGBAKjgPySgrNDhlJkW7jXR"
+ "WiGpjGSAFPT9NMTvEHDo7oLTQ8AcYzcGQ7ISMRdVXR6GJOlFVsH4NLwuHGtcMTPK"
+ "zoHbPHJyOn1SgC5tARD/1vm5CsG2hATRpWRQCTJFg5VRJ4R7Pz+HuxY4SoABcPQd"
+ "K+MP8GlGqTldC6NaB1s7KuAX";
private static SecretKey encryptionKey;
private static SecretKey macKey;
private static KeyStore keyStore;
private static final String password = "Password";
private static final PasswordProtection passwordProtection =
new PasswordProtection(password.toCharArray());
private Map<String, String> description;
private EncryptionContext ctx;
private static PrivateKey privateKey;
private static Certificate certificate;
@BeforeClass
public static void setUpBeforeClass() throws Exception {
KeyGenerator macGen = KeyGenerator.getInstance("HmacSHA256");
macGen.init(256, Utils.getRng());
macKey = macGen.generateKey();
KeyGenerator aesGen = KeyGenerator.getInstance("AES");
aesGen.init(128, Utils.getRng());
encryptionKey = aesGen.generateKey();
keyStore = KeyStore.getInstance("jceks");
keyStore.load(null, password.toCharArray());
KeyFactory kf = KeyFactory.getInstance("RSA");
PKCS8EncodedKeySpec rsaSpec = new PKCS8EncodedKeySpec(Base64.decode(keyPem));
privateKey = kf.generatePrivate(rsaSpec);
CertificateFactory cf = CertificateFactory.getInstance("X509");
certificate = cf.generateCertificate(new ByteArrayInputStream(Base64.decode(certPem)));
keyStore.setEntry("enc", new SecretKeyEntry(encryptionKey), passwordProtection);
keyStore.setEntry("sig", new SecretKeyEntry(macKey), passwordProtection);
keyStore.setEntry(
"enc-a",
new PrivateKeyEntry(privateKey, new Certificate[] {certificate}),
passwordProtection);
keyStore.setEntry(
"sig-a",
new PrivateKeyEntry(privateKey, new Certificate[] {certificate}),
passwordProtection);
keyStore.setCertificateEntry("trustedCert", certificate);
}
@BeforeMethod
public void setUp() {
description = new HashMap<String, String>();
description.put("TestKey", "test value");
description = Collections.unmodifiableMap(description);
ctx = new EncryptionContext.Builder().build();
}
@Test
@SuppressWarnings("unchecked")
public void simpleSymMac() throws Exception {
KeyStoreMaterialsProvider prov =
new KeyStoreMaterialsProvider(
keyStore, "enc", "sig", passwordProtection, passwordProtection, Collections.EMPTY_MAP);
EncryptionMaterials encryptionMaterials = prov.getEncryptionMaterials(ctx);
assertEquals(encryptionKey, encryptionMaterials.getEncryptionKey());
assertEquals(macKey, encryptionMaterials.getSigningKey());
assertEquals(
encryptionKey, prov.getDecryptionMaterials(ctx(encryptionMaterials)).getDecryptionKey());
assertEquals(
macKey, prov.getDecryptionMaterials(ctx(encryptionMaterials)).getVerificationKey());
}
@Test
@SuppressWarnings("unchecked")
public void simpleSymSig() throws Exception {
KeyStoreMaterialsProvider prov =
new KeyStoreMaterialsProvider(
keyStore,
"enc",
"sig-a",
passwordProtection,
passwordProtection,
Collections.EMPTY_MAP);
EncryptionMaterials encryptionMaterials = prov.getEncryptionMaterials(ctx);
assertEquals(encryptionKey, encryptionMaterials.getEncryptionKey());
assertEquals(privateKey, encryptionMaterials.getSigningKey());
assertEquals(
encryptionKey, prov.getDecryptionMaterials(ctx(encryptionMaterials)).getDecryptionKey());
assertEquals(
certificate.getPublicKey(),
prov.getDecryptionMaterials(ctx(encryptionMaterials)).getVerificationKey());
}
@Test
public void equalSymDescMac() throws Exception {
KeyStoreMaterialsProvider prov =
new KeyStoreMaterialsProvider(
keyStore, "enc", "sig", passwordProtection, passwordProtection, description);
EncryptionMaterials encryptionMaterials = prov.getEncryptionMaterials(ctx);
assertEquals(encryptionKey, encryptionMaterials.getEncryptionKey());
assertEquals(macKey, encryptionMaterials.getSigningKey());
assertEquals(
encryptionKey, prov.getDecryptionMaterials(ctx(encryptionMaterials)).getDecryptionKey());
assertEquals(
macKey, prov.getDecryptionMaterials(ctx(encryptionMaterials)).getVerificationKey());
}
@Test
public void superSetSymDescMac() throws Exception {
KeyStoreMaterialsProvider prov =
new KeyStoreMaterialsProvider(
keyStore, "enc", "sig", passwordProtection, passwordProtection, description);
EncryptionMaterials encryptionMaterials = prov.getEncryptionMaterials(ctx);
assertEquals(encryptionKey, encryptionMaterials.getEncryptionKey());
assertEquals(macKey, encryptionMaterials.getSigningKey());
Map<String, String> tmpDesc =
new HashMap<String, String>(encryptionMaterials.getMaterialDescription());
tmpDesc.put("randomValue", "random");
assertEquals(encryptionKey, prov.getDecryptionMaterials(ctx(tmpDesc)).getDecryptionKey());
assertEquals(macKey, prov.getDecryptionMaterials(ctx(tmpDesc)).getVerificationKey());
}
@Test
@SuppressWarnings("unchecked")
public void subSetSymDescMac() throws Exception {
KeyStoreMaterialsProvider prov =
new KeyStoreMaterialsProvider(
keyStore, "enc", "sig", passwordProtection, passwordProtection, description);
EncryptionMaterials encryptionMaterials = prov.getEncryptionMaterials(ctx);
assertEquals(encryptionKey, encryptionMaterials.getEncryptionKey());
assertEquals(macKey, encryptionMaterials.getSigningKey());
assertNull(prov.getDecryptionMaterials(ctx(Collections.EMPTY_MAP)));
}
@Test
public void noMatchSymDescMac() throws Exception {
KeyStoreMaterialsProvider prov =
new KeyStoreMaterialsProvider(
keyStore, "enc", "sig", passwordProtection, passwordProtection, description);
EncryptionMaterials encryptionMaterials = prov.getEncryptionMaterials(ctx);
assertEquals(encryptionKey, encryptionMaterials.getEncryptionKey());
assertEquals(macKey, encryptionMaterials.getSigningKey());
Map<String, String> tmpDesc = new HashMap<String, String>();
tmpDesc.put("randomValue", "random");
assertNull(prov.getDecryptionMaterials(ctx(tmpDesc)));
}
@Test
public void testRefresh() throws Exception {
// Mostly make sure we don't throw an exception
KeyStoreMaterialsProvider prov =
new KeyStoreMaterialsProvider(
keyStore, "enc", "sig", passwordProtection, passwordProtection, description);
prov.refresh();
}
@Test
public void asymSimpleMac() throws Exception {
KeyStoreMaterialsProvider prov =
new KeyStoreMaterialsProvider(
keyStore, "enc-a", "sig", passwordProtection, passwordProtection, description);
EncryptionMaterials eMat = prov.getEncryptionMaterials(ctx);
SecretKey encryptionKey = eMat.getEncryptionKey();
assertNotNull(encryptionKey);
assertEquals(macKey, eMat.getSigningKey());
DecryptionMaterials dMat = prov.getDecryptionMaterials(ctx(eMat));
assertEquals(encryptionKey, dMat.getDecryptionKey());
assertEquals(macKey, dMat.getVerificationKey());
}
@Test
public void asymSimpleSig() throws Exception {
KeyStoreMaterialsProvider prov =
new KeyStoreMaterialsProvider(
keyStore, "enc-a", "sig-a", passwordProtection, passwordProtection, description);
EncryptionMaterials eMat = prov.getEncryptionMaterials(ctx);
SecretKey encryptionKey = eMat.getEncryptionKey();
assertNotNull(encryptionKey);
assertEquals(privateKey, eMat.getSigningKey());
DecryptionMaterials dMat = prov.getDecryptionMaterials(ctx(eMat));
assertEquals(encryptionKey, dMat.getDecryptionKey());
assertEquals(certificate.getPublicKey(), dMat.getVerificationKey());
}
@Test
public void asymSigVerifyOnly() throws Exception {
KeyStoreMaterialsProvider prov =
new KeyStoreMaterialsProvider(
keyStore, "enc-a", "trustedCert", passwordProtection, null, description);
EncryptionMaterials eMat = prov.getEncryptionMaterials(ctx);
SecretKey encryptionKey = eMat.getEncryptionKey();
assertNotNull(encryptionKey);
assertNull(eMat.getSigningKey());
DecryptionMaterials dMat = prov.getDecryptionMaterials(ctx(eMat));
assertEquals(encryptionKey, dMat.getDecryptionKey());
assertEquals(certificate.getPublicKey(), dMat.getVerificationKey());
}
@Test
public void asymSigEncryptOnly() throws Exception {
KeyStoreMaterialsProvider prov =
new KeyStoreMaterialsProvider(
keyStore, "trustedCert", "sig-a", null, passwordProtection, description);
EncryptionMaterials eMat = prov.getEncryptionMaterials(ctx);
SecretKey encryptionKey = eMat.getEncryptionKey();
assertNotNull(encryptionKey);
assertEquals(privateKey, eMat.getSigningKey());
try {
prov.getDecryptionMaterials(ctx(eMat));
fail("Expected exception");
} catch (IllegalStateException ex) {
assertEquals("No private decryption key provided.", ex.getMessage());
}
}
private static EncryptionContext ctx(EncryptionMaterials mat) {
return ctx(mat.getMaterialDescription());
}
private static EncryptionContext ctx(Map<String, String> desc) {
return new EncryptionContext.Builder().withMaterialDescription(desc).build();
}
}
| 5,013 |
0 | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/sdkv1/com/amazonaws/services/dynamodbv2/datamodeling/encryption | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/sdkv1/com/amazonaws/services/dynamodbv2/datamodeling/encryption/providers/SymmetricStaticProviderTest.java | /*
* Copyright 2014 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.services.dynamodbv2.datamodeling.encryption.providers;
import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertNull;
import static org.testng.AssertJUnit.assertTrue;
import com.amazonaws.services.dynamodbv2.datamodeling.encryption.EncryptionContext;
import com.amazonaws.services.dynamodbv2.datamodeling.encryption.materials.EncryptionMaterials;
import com.amazonaws.services.dynamodbv2.datamodeling.internal.Utils;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
public class SymmetricStaticProviderTest {
private static SecretKey encryptionKey;
private static SecretKey macKey;
private static KeyPair sigPair;
private Map<String, String> description;
private EncryptionContext ctx;
@BeforeClass
public static void setUpClass() throws Exception {
KeyPairGenerator rsaGen = KeyPairGenerator.getInstance("RSA");
rsaGen.initialize(2048, Utils.getRng());
sigPair = rsaGen.generateKeyPair();
KeyGenerator macGen = KeyGenerator.getInstance("HmacSHA256");
macGen.init(256, Utils.getRng());
macKey = macGen.generateKey();
KeyGenerator aesGen = KeyGenerator.getInstance("AES");
aesGen.init(128, Utils.getRng());
encryptionKey = aesGen.generateKey();
}
@BeforeMethod
public void setUp() {
description = new HashMap<String, String>();
description.put("TestKey", "test value");
description = Collections.unmodifiableMap(description);
ctx = new EncryptionContext.Builder().build();
}
@Test
public void simpleMac() {
SymmetricStaticProvider prov =
new SymmetricStaticProvider(encryptionKey, macKey, Collections.<String, String>emptyMap());
assertEquals(encryptionKey, prov.getEncryptionMaterials(ctx).getEncryptionKey());
assertEquals(macKey, prov.getEncryptionMaterials(ctx).getSigningKey());
assertEquals(
encryptionKey,
prov.getDecryptionMaterials(ctx(Collections.<String, String>emptyMap()))
.getDecryptionKey());
assertEquals(
macKey,
prov.getDecryptionMaterials(ctx(Collections.<String, String>emptyMap()))
.getVerificationKey());
}
@Test
public void simpleSig() {
SymmetricStaticProvider prov =
new SymmetricStaticProvider(encryptionKey, sigPair, Collections.<String, String>emptyMap());
assertEquals(encryptionKey, prov.getEncryptionMaterials(ctx).getEncryptionKey());
assertEquals(sigPair.getPrivate(), prov.getEncryptionMaterials(ctx).getSigningKey());
assertEquals(
encryptionKey,
prov.getDecryptionMaterials(ctx(Collections.<String, String>emptyMap()))
.getDecryptionKey());
assertEquals(
sigPair.getPublic(),
prov.getDecryptionMaterials(ctx(Collections.<String, String>emptyMap()))
.getVerificationKey());
}
@Test
public void equalDescMac() {
SymmetricStaticProvider prov = new SymmetricStaticProvider(encryptionKey, macKey, description);
assertEquals(encryptionKey, prov.getEncryptionMaterials(ctx).getEncryptionKey());
assertEquals(macKey, prov.getEncryptionMaterials(ctx).getSigningKey());
assertTrue(
prov.getEncryptionMaterials(ctx)
.getMaterialDescription()
.entrySet()
.containsAll(description.entrySet()));
assertEquals(encryptionKey, prov.getDecryptionMaterials(ctx(description)).getDecryptionKey());
assertEquals(macKey, prov.getDecryptionMaterials(ctx(description)).getVerificationKey());
}
@Test
public void supersetDescMac() {
SymmetricStaticProvider prov = new SymmetricStaticProvider(encryptionKey, macKey, description);
assertEquals(encryptionKey, prov.getEncryptionMaterials(ctx).getEncryptionKey());
assertEquals(macKey, prov.getEncryptionMaterials(ctx).getSigningKey());
assertTrue(
prov.getEncryptionMaterials(ctx)
.getMaterialDescription()
.entrySet()
.containsAll(description.entrySet()));
Map<String, String> superSet = new HashMap<String, String>(description);
superSet.put("NewValue", "super!");
assertEquals(encryptionKey, prov.getDecryptionMaterials(ctx(superSet)).getDecryptionKey());
assertEquals(macKey, prov.getDecryptionMaterials(ctx(superSet)).getVerificationKey());
}
@Test
public void subsetDescMac() {
SymmetricStaticProvider prov = new SymmetricStaticProvider(encryptionKey, macKey, description);
assertEquals(encryptionKey, prov.getEncryptionMaterials(ctx).getEncryptionKey());
assertEquals(macKey, prov.getEncryptionMaterials(ctx).getSigningKey());
assertTrue(
prov.getEncryptionMaterials(ctx)
.getMaterialDescription()
.entrySet()
.containsAll(description.entrySet()));
assertNull(prov.getDecryptionMaterials(ctx(Collections.<String, String>emptyMap())));
}
@Test
public void noMatchDescMac() {
SymmetricStaticProvider prov = new SymmetricStaticProvider(encryptionKey, macKey, description);
assertEquals(encryptionKey, prov.getEncryptionMaterials(ctx).getEncryptionKey());
assertEquals(macKey, prov.getEncryptionMaterials(ctx).getSigningKey());
assertTrue(
prov.getEncryptionMaterials(ctx)
.getMaterialDescription()
.entrySet()
.containsAll(description.entrySet()));
Map<String, String> noMatch = new HashMap<String, String>();
noMatch.put("NewValue", "no match!");
assertNull(prov.getDecryptionMaterials(ctx(noMatch)));
}
@Test
public void testRefresh() {
// This does nothing, make sure we don't throw and exception.
SymmetricStaticProvider prov = new SymmetricStaticProvider(encryptionKey, macKey, description);
prov.refresh();
}
@SuppressWarnings("unused")
private static EncryptionContext ctx(EncryptionMaterials mat) {
return ctx(mat.getMaterialDescription());
}
private static EncryptionContext ctx(Map<String, String> desc) {
return new EncryptionContext.Builder().withMaterialDescription(desc).build();
}
}
| 5,014 |
0 | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/sdkv1/com/amazonaws/services/dynamodbv2/datamodeling/encryption | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/sdkv1/com/amazonaws/services/dynamodbv2/datamodeling/encryption/providers/AsymmetricStaticProviderTest.java | /*
* Copyright 2014 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.services.dynamodbv2.datamodeling.encryption.providers;
import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertFalse;
import static org.testng.AssertJUnit.assertNotNull;
import com.amazonaws.services.dynamodbv2.datamodeling.encryption.EncryptionContext;
import com.amazonaws.services.dynamodbv2.datamodeling.encryption.materials.DecryptionMaterials;
import com.amazonaws.services.dynamodbv2.datamodeling.encryption.materials.EncryptionMaterials;
import com.amazonaws.services.dynamodbv2.datamodeling.internal.Utils;
import java.security.GeneralSecurityException;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
public class AsymmetricStaticProviderTest {
private static KeyPair encryptionPair;
private static SecretKey macKey;
private static KeyPair sigPair;
private Map<String, String> description;
private EncryptionContext ctx;
@BeforeClass
public static void setUpClass() throws Exception {
KeyPairGenerator rsaGen = KeyPairGenerator.getInstance("RSA");
rsaGen.initialize(2048, Utils.getRng());
sigPair = rsaGen.generateKeyPair();
encryptionPair = rsaGen.generateKeyPair();
KeyGenerator macGen = KeyGenerator.getInstance("HmacSHA256");
macGen.init(256, Utils.getRng());
macKey = macGen.generateKey();
}
@BeforeMethod
public void setUp() {
description = new HashMap<String, String>();
description.put("TestKey", "test value");
description = Collections.unmodifiableMap(description);
ctx = new EncryptionContext.Builder().build();
}
@Test
public void constructWithMac() throws GeneralSecurityException {
AsymmetricStaticProvider prov =
new AsymmetricStaticProvider(
encryptionPair, macKey, Collections.<String, String>emptyMap());
EncryptionMaterials eMat = prov.getEncryptionMaterials(ctx);
SecretKey encryptionKey = eMat.getEncryptionKey();
assertNotNull(encryptionKey);
assertEquals(macKey, eMat.getSigningKey());
DecryptionMaterials dMat = prov.getDecryptionMaterials(ctx(eMat));
assertEquals(encryptionKey, dMat.getDecryptionKey());
assertEquals(macKey, dMat.getVerificationKey());
}
@Test
public void constructWithSigPair() throws GeneralSecurityException {
AsymmetricStaticProvider prov =
new AsymmetricStaticProvider(
encryptionPair, sigPair, Collections.<String, String>emptyMap());
EncryptionMaterials eMat = prov.getEncryptionMaterials(ctx);
SecretKey encryptionKey = eMat.getEncryptionKey();
assertNotNull(encryptionKey);
assertEquals(sigPair.getPrivate(), eMat.getSigningKey());
DecryptionMaterials dMat = prov.getDecryptionMaterials(ctx(eMat));
assertEquals(encryptionKey, dMat.getDecryptionKey());
assertEquals(sigPair.getPublic(), dMat.getVerificationKey());
}
@Test
public void randomEnvelopeKeys() throws GeneralSecurityException {
AsymmetricStaticProvider prov =
new AsymmetricStaticProvider(
encryptionPair, macKey, Collections.<String, String>emptyMap());
EncryptionMaterials eMat = prov.getEncryptionMaterials(ctx);
SecretKey encryptionKey = eMat.getEncryptionKey();
assertNotNull(encryptionKey);
assertEquals(macKey, eMat.getSigningKey());
EncryptionMaterials eMat2 = prov.getEncryptionMaterials(ctx);
SecretKey encryptionKey2 = eMat2.getEncryptionKey();
assertEquals(macKey, eMat.getSigningKey());
assertFalse("Envelope keys must be different", encryptionKey.equals(encryptionKey2));
}
@Test
public void testRefresh() {
// This does nothing, make sure we don't throw and exception.
AsymmetricStaticProvider prov =
new AsymmetricStaticProvider(encryptionPair, macKey, description);
prov.refresh();
}
private static EncryptionContext ctx(EncryptionMaterials mat) {
return new EncryptionContext.Builder()
.withMaterialDescription(mat.getMaterialDescription())
.build();
}
}
| 5,015 |
0 | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/sdkv1/com/amazonaws/services/dynamodbv2/datamodeling/encryption | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/sdkv1/com/amazonaws/services/dynamodbv2/datamodeling/encryption/providers/WrappedMaterialsProviderTest.java | package com.amazonaws.services.dynamodbv2.datamodeling.encryption.providers;
import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertFalse;
import static org.testng.AssertJUnit.assertNotNull;
import com.amazonaws.services.dynamodbv2.datamodeling.encryption.EncryptionContext;
import com.amazonaws.services.dynamodbv2.datamodeling.encryption.materials.DecryptionMaterials;
import com.amazonaws.services.dynamodbv2.datamodeling.encryption.materials.EncryptionMaterials;
import com.amazonaws.services.dynamodbv2.datamodeling.encryption.materials.WrappedRawMaterials;
import java.security.GeneralSecurityException;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
public class WrappedMaterialsProviderTest {
private static SecretKey symEncryptionKey;
private static SecretKey macKey;
private static KeyPair sigPair;
private static KeyPair encryptionPair;
private static SecureRandom rnd;
private Map<String, String> description;
private EncryptionContext ctx;
@BeforeClass
public static void setUpClass() throws NoSuchAlgorithmException {
rnd = new SecureRandom();
KeyPairGenerator rsaGen = KeyPairGenerator.getInstance("RSA");
rsaGen.initialize(2048, rnd);
sigPair = rsaGen.generateKeyPair();
encryptionPair = rsaGen.generateKeyPair();
KeyGenerator aesGen = KeyGenerator.getInstance("AES");
aesGen.init(128, rnd);
symEncryptionKey = aesGen.generateKey();
KeyGenerator macGen = KeyGenerator.getInstance("HmacSHA256");
macGen.init(256, rnd);
macKey = macGen.generateKey();
}
@BeforeMethod
public void setUp() {
description = new HashMap<String, String>();
description.put("TestKey", "test value");
ctx = new EncryptionContext.Builder().build();
}
@Test
public void simpleMac() throws GeneralSecurityException {
WrappedMaterialsProvider prov =
new WrappedMaterialsProvider(
symEncryptionKey, symEncryptionKey, macKey, Collections.emptyMap());
EncryptionMaterials eMat = prov.getEncryptionMaterials(ctx);
SecretKey contentEncryptionKey = eMat.getEncryptionKey();
assertNotNull(contentEncryptionKey);
assertEquals(macKey, eMat.getSigningKey());
DecryptionMaterials dMat = prov.getDecryptionMaterials(ctx(eMat));
assertEquals(contentEncryptionKey, dMat.getDecryptionKey());
assertEquals(macKey, dMat.getVerificationKey());
}
@Test
public void simpleSigPair() throws GeneralSecurityException {
WrappedMaterialsProvider prov =
new WrappedMaterialsProvider(
symEncryptionKey, symEncryptionKey, sigPair, Collections.emptyMap());
EncryptionMaterials eMat = prov.getEncryptionMaterials(ctx);
SecretKey contentEncryptionKey = eMat.getEncryptionKey();
assertNotNull(contentEncryptionKey);
assertEquals(sigPair.getPrivate(), eMat.getSigningKey());
DecryptionMaterials dMat = prov.getDecryptionMaterials(ctx(eMat));
assertEquals(contentEncryptionKey, dMat.getDecryptionKey());
assertEquals(sigPair.getPublic(), dMat.getVerificationKey());
}
@Test
public void randomEnvelopeKeys() throws GeneralSecurityException {
WrappedMaterialsProvider prov =
new WrappedMaterialsProvider(
symEncryptionKey, symEncryptionKey, macKey, Collections.emptyMap());
EncryptionMaterials eMat = prov.getEncryptionMaterials(ctx);
SecretKey contentEncryptionKey = eMat.getEncryptionKey();
assertNotNull(contentEncryptionKey);
assertEquals(macKey, eMat.getSigningKey());
EncryptionMaterials eMat2 = prov.getEncryptionMaterials(ctx);
SecretKey contentEncryptionKey2 = eMat2.getEncryptionKey();
assertEquals(macKey, eMat.getSigningKey());
assertFalse(
"Envelope keys must be different", contentEncryptionKey.equals(contentEncryptionKey2));
}
@Test
public void testRefresh() {
// This does nothing, make sure we don't throw an exception.
WrappedMaterialsProvider prov =
new WrappedMaterialsProvider(
symEncryptionKey, symEncryptionKey, macKey, Collections.emptyMap());
prov.refresh();
}
@Test
public void wrapUnwrapAsymMatExplicitWrappingAlgorithmPkcs1() throws GeneralSecurityException {
Map<String, String> desc = new HashMap<String, String>();
desc.put(WrappedRawMaterials.KEY_WRAPPING_ALGORITHM, "RSA/ECB/PKCS1Padding");
WrappedMaterialsProvider prov =
new WrappedMaterialsProvider(
encryptionPair.getPublic(), encryptionPair.getPrivate(), sigPair, desc);
EncryptionMaterials eMat = prov.getEncryptionMaterials(ctx);
SecretKey contentEncryptionKey = eMat.getEncryptionKey();
assertNotNull(contentEncryptionKey);
assertEquals(sigPair.getPrivate(), eMat.getSigningKey());
DecryptionMaterials dMat = prov.getDecryptionMaterials(ctx(eMat));
assertEquals(
"RSA/ECB/PKCS1Padding",
eMat.getMaterialDescription().get(WrappedRawMaterials.KEY_WRAPPING_ALGORITHM));
assertEquals(contentEncryptionKey, dMat.getDecryptionKey());
assertEquals(sigPair.getPublic(), dMat.getVerificationKey());
}
@Test
public void wrapUnwrapAsymMatExplicitWrappingAlgorithmPkcs2() throws GeneralSecurityException {
Map<String, String> desc = new HashMap<String, String>();
desc.put(WrappedRawMaterials.KEY_WRAPPING_ALGORITHM, "RSA/ECB/OAEPWithSHA-256AndMGF1Padding");
WrappedMaterialsProvider prov =
new WrappedMaterialsProvider(
encryptionPair.getPublic(), encryptionPair.getPrivate(), sigPair, desc);
EncryptionMaterials eMat = prov.getEncryptionMaterials(ctx);
SecretKey contentEncryptionKey = eMat.getEncryptionKey();
assertNotNull(contentEncryptionKey);
assertEquals(sigPair.getPrivate(), eMat.getSigningKey());
DecryptionMaterials dMat = prov.getDecryptionMaterials(ctx(eMat));
assertEquals(
"RSA/ECB/OAEPWithSHA-256AndMGF1Padding",
eMat.getMaterialDescription().get(WrappedRawMaterials.KEY_WRAPPING_ALGORITHM));
assertEquals(contentEncryptionKey, dMat.getDecryptionKey());
assertEquals(sigPair.getPublic(), dMat.getVerificationKey());
}
@Test
public void wrapUnwrapAsymMatExplicitContentKeyAlgorithm() throws GeneralSecurityException {
Map<String, String> desc = new HashMap<String, String>();
desc.put(WrappedRawMaterials.CONTENT_KEY_ALGORITHM, "AES");
WrappedMaterialsProvider prov =
new WrappedMaterialsProvider(
encryptionPair.getPublic(),
encryptionPair.getPrivate(),
sigPair,
Collections.emptyMap());
EncryptionMaterials eMat = prov.getEncryptionMaterials(ctx);
SecretKey contentEncryptionKey = eMat.getEncryptionKey();
assertNotNull(contentEncryptionKey);
assertEquals("AES", contentEncryptionKey.getAlgorithm());
assertEquals(
"AES", eMat.getMaterialDescription().get(WrappedRawMaterials.CONTENT_KEY_ALGORITHM));
assertEquals(sigPair.getPrivate(), eMat.getSigningKey());
DecryptionMaterials dMat = prov.getDecryptionMaterials(ctx(eMat));
assertEquals(
"AES", dMat.getMaterialDescription().get(WrappedRawMaterials.CONTENT_KEY_ALGORITHM));
assertEquals(contentEncryptionKey, dMat.getDecryptionKey());
assertEquals(sigPair.getPublic(), dMat.getVerificationKey());
}
@Test
public void wrapUnwrapAsymMatExplicitContentKeyLength128() throws GeneralSecurityException {
Map<String, String> desc = new HashMap<String, String>();
desc.put(WrappedRawMaterials.CONTENT_KEY_ALGORITHM, "AES/128");
WrappedMaterialsProvider prov =
new WrappedMaterialsProvider(
encryptionPair.getPublic(), encryptionPair.getPrivate(), sigPair, desc);
EncryptionMaterials eMat = prov.getEncryptionMaterials(ctx);
SecretKey contentEncryptionKey = eMat.getEncryptionKey();
assertNotNull(contentEncryptionKey);
assertEquals("AES", contentEncryptionKey.getAlgorithm());
assertEquals(
"AES", eMat.getMaterialDescription().get(WrappedRawMaterials.CONTENT_KEY_ALGORITHM));
assertEquals(16, contentEncryptionKey.getEncoded().length); // 128 Bits
assertEquals(sigPair.getPrivate(), eMat.getSigningKey());
DecryptionMaterials dMat = prov.getDecryptionMaterials(ctx(eMat));
assertEquals(
"AES", dMat.getMaterialDescription().get(WrappedRawMaterials.CONTENT_KEY_ALGORITHM));
assertEquals(contentEncryptionKey, dMat.getDecryptionKey());
assertEquals(sigPair.getPublic(), dMat.getVerificationKey());
}
@Test
public void wrapUnwrapAsymMatExplicitContentKeyLength256() throws GeneralSecurityException {
Map<String, String> desc = new HashMap<String, String>();
desc.put(WrappedRawMaterials.CONTENT_KEY_ALGORITHM, "AES/256");
WrappedMaterialsProvider prov =
new WrappedMaterialsProvider(
encryptionPair.getPublic(), encryptionPair.getPrivate(), sigPair, desc);
EncryptionMaterials eMat = prov.getEncryptionMaterials(ctx);
SecretKey contentEncryptionKey = eMat.getEncryptionKey();
assertNotNull(contentEncryptionKey);
assertEquals("AES", contentEncryptionKey.getAlgorithm());
assertEquals(
"AES", eMat.getMaterialDescription().get(WrappedRawMaterials.CONTENT_KEY_ALGORITHM));
assertEquals(32, contentEncryptionKey.getEncoded().length); // 256 Bits
assertEquals(sigPair.getPrivate(), eMat.getSigningKey());
DecryptionMaterials dMat = prov.getDecryptionMaterials(ctx(eMat));
assertEquals(
"AES", dMat.getMaterialDescription().get(WrappedRawMaterials.CONTENT_KEY_ALGORITHM));
assertEquals(contentEncryptionKey, dMat.getDecryptionKey());
assertEquals(sigPair.getPublic(), dMat.getVerificationKey());
}
@Test
public void unwrapAsymMatExplicitEncAlgAes128() throws GeneralSecurityException {
Map<String, String> desc = new HashMap<String, String>();
desc.put(WrappedRawMaterials.CONTENT_KEY_ALGORITHM, "AES/128");
WrappedMaterialsProvider prov =
new WrappedMaterialsProvider(
encryptionPair.getPublic(), encryptionPair.getPrivate(), sigPair, desc);
// Get materials we can test unwrapping on
EncryptionMaterials eMat = prov.getEncryptionMaterials(ctx);
// Ensure "AES/128" on the created materials creates the expected key
Map<String, String> aes128Desc = eMat.getMaterialDescription();
aes128Desc.put(WrappedRawMaterials.CONTENT_KEY_ALGORITHM, "AES/128");
EncryptionContext aes128Ctx =
new EncryptionContext.Builder().withMaterialDescription(aes128Desc).build();
DecryptionMaterials dMat = prov.getDecryptionMaterials(aes128Ctx);
assertEquals(
"AES/128", dMat.getMaterialDescription().get(WrappedRawMaterials.CONTENT_KEY_ALGORITHM));
assertEquals("AES", dMat.getDecryptionKey().getAlgorithm());
assertEquals(eMat.getEncryptionKey(), dMat.getDecryptionKey());
assertEquals(sigPair.getPublic(), dMat.getVerificationKey());
}
@Test
public void unwrapAsymMatExplicitEncAlgAes256() throws GeneralSecurityException {
Map<String, String> desc = new HashMap<String, String>();
desc.put(WrappedRawMaterials.CONTENT_KEY_ALGORITHM, "AES/256");
WrappedMaterialsProvider prov =
new WrappedMaterialsProvider(
encryptionPair.getPublic(), encryptionPair.getPrivate(), sigPair, desc);
// Get materials we can test unwrapping on
EncryptionMaterials eMat = prov.getEncryptionMaterials(ctx);
// Ensure "AES/256" on the created materials creates the expected key
Map<String, String> aes256Desc = eMat.getMaterialDescription();
aes256Desc.put(WrappedRawMaterials.CONTENT_KEY_ALGORITHM, "AES/256");
EncryptionContext aes256Ctx =
new EncryptionContext.Builder().withMaterialDescription(aes256Desc).build();
DecryptionMaterials dMat = prov.getDecryptionMaterials(aes256Ctx);
assertEquals(
"AES/256", dMat.getMaterialDescription().get(WrappedRawMaterials.CONTENT_KEY_ALGORITHM));
assertEquals("AES", dMat.getDecryptionKey().getAlgorithm());
assertEquals(eMat.getEncryptionKey(), dMat.getDecryptionKey());
assertEquals(sigPair.getPublic(), dMat.getVerificationKey());
}
@Test
public void wrapUnwrapSymMatExplicitContentKeyAlgorithm() throws GeneralSecurityException {
Map<String, String> desc = new HashMap<String, String>();
desc.put(WrappedRawMaterials.CONTENT_KEY_ALGORITHM, "AES");
WrappedMaterialsProvider prov =
new WrappedMaterialsProvider(symEncryptionKey, symEncryptionKey, macKey, desc);
EncryptionMaterials eMat = prov.getEncryptionMaterials(ctx);
SecretKey contentEncryptionKey = eMat.getEncryptionKey();
assertNotNull(contentEncryptionKey);
assertEquals("AES", contentEncryptionKey.getAlgorithm());
assertEquals(
"AES", eMat.getMaterialDescription().get(WrappedRawMaterials.CONTENT_KEY_ALGORITHM));
assertEquals(macKey, eMat.getSigningKey());
DecryptionMaterials dMat = prov.getDecryptionMaterials(ctx(eMat));
assertEquals(
"AES", dMat.getMaterialDescription().get(WrappedRawMaterials.CONTENT_KEY_ALGORITHM));
assertEquals(contentEncryptionKey, dMat.getDecryptionKey());
assertEquals(macKey, dMat.getVerificationKey());
}
@Test
public void wrapUnwrapSymMatExplicitContentKeyLength128() throws GeneralSecurityException {
Map<String, String> desc = new HashMap<String, String>();
desc.put(WrappedRawMaterials.CONTENT_KEY_ALGORITHM, "AES/128");
WrappedMaterialsProvider prov =
new WrappedMaterialsProvider(symEncryptionKey, symEncryptionKey, macKey, desc);
EncryptionMaterials eMat = prov.getEncryptionMaterials(ctx);
SecretKey contentEncryptionKey = eMat.getEncryptionKey();
assertNotNull(contentEncryptionKey);
assertEquals("AES", contentEncryptionKey.getAlgorithm());
assertEquals(
"AES", eMat.getMaterialDescription().get(WrappedRawMaterials.CONTENT_KEY_ALGORITHM));
assertEquals(16, contentEncryptionKey.getEncoded().length); // 128 Bits
assertEquals(macKey, eMat.getSigningKey());
DecryptionMaterials dMat = prov.getDecryptionMaterials(ctx(eMat));
assertEquals(
"AES", dMat.getMaterialDescription().get(WrappedRawMaterials.CONTENT_KEY_ALGORITHM));
assertEquals(contentEncryptionKey, dMat.getDecryptionKey());
assertEquals(macKey, dMat.getVerificationKey());
}
@Test
public void wrapUnwrapSymMatExplicitContentKeyLength256() throws GeneralSecurityException {
Map<String, String> desc = new HashMap<String, String>();
desc.put(WrappedRawMaterials.CONTENT_KEY_ALGORITHM, "AES/256");
WrappedMaterialsProvider prov =
new WrappedMaterialsProvider(symEncryptionKey, symEncryptionKey, macKey, desc);
EncryptionMaterials eMat = prov.getEncryptionMaterials(ctx);
SecretKey contentEncryptionKey = eMat.getEncryptionKey();
assertNotNull(contentEncryptionKey);
assertEquals("AES", contentEncryptionKey.getAlgorithm());
assertEquals(
"AES", eMat.getMaterialDescription().get(WrappedRawMaterials.CONTENT_KEY_ALGORITHM));
assertEquals(32, contentEncryptionKey.getEncoded().length); // 256 Bits
assertEquals(macKey, eMat.getSigningKey());
DecryptionMaterials dMat = prov.getDecryptionMaterials(ctx(eMat));
assertEquals(
"AES", dMat.getMaterialDescription().get(WrappedRawMaterials.CONTENT_KEY_ALGORITHM));
assertEquals(contentEncryptionKey, dMat.getDecryptionKey());
assertEquals(macKey, dMat.getVerificationKey());
}
@Test
public void unwrapSymMatExplicitEncAlgAes128() throws GeneralSecurityException {
Map<String, String> desc = new HashMap<String, String>();
desc.put(WrappedRawMaterials.CONTENT_KEY_ALGORITHM, "AES/128");
WrappedMaterialsProvider prov =
new WrappedMaterialsProvider(symEncryptionKey, symEncryptionKey, macKey, desc);
// Get materials we can test unwrapping on
EncryptionMaterials eMat = prov.getEncryptionMaterials(ctx);
// Ensure "AES/128" on the created materials creates the expected key
Map<String, String> aes128Desc = eMat.getMaterialDescription();
aes128Desc.put(WrappedRawMaterials.CONTENT_KEY_ALGORITHM, "AES/128");
EncryptionContext aes128Ctx =
new EncryptionContext.Builder().withMaterialDescription(aes128Desc).build();
DecryptionMaterials dMat = prov.getDecryptionMaterials(aes128Ctx);
assertEquals(
"AES/128", dMat.getMaterialDescription().get(WrappedRawMaterials.CONTENT_KEY_ALGORITHM));
assertEquals("AES", dMat.getDecryptionKey().getAlgorithm());
assertEquals(eMat.getEncryptionKey(), dMat.getDecryptionKey());
assertEquals(macKey, dMat.getVerificationKey());
}
@Test
public void unwrapSymMatExplicitEncAlgAes256() throws GeneralSecurityException {
Map<String, String> desc = new HashMap<String, String>();
desc.put(WrappedRawMaterials.CONTENT_KEY_ALGORITHM, "AES/256");
WrappedMaterialsProvider prov =
new WrappedMaterialsProvider(symEncryptionKey, symEncryptionKey, macKey, desc);
EncryptionMaterials eMat = prov.getEncryptionMaterials(ctx);
Map<String, String> aes256Desc = eMat.getMaterialDescription();
aes256Desc.put(WrappedRawMaterials.CONTENT_KEY_ALGORITHM, "AES/256");
EncryptionContext aes256Ctx =
new EncryptionContext.Builder().withMaterialDescription(aes256Desc).build();
DecryptionMaterials dMat = prov.getDecryptionMaterials(aes256Ctx);
assertEquals(
"AES/256", dMat.getMaterialDescription().get(WrappedRawMaterials.CONTENT_KEY_ALGORITHM));
assertEquals("AES", dMat.getDecryptionKey().getAlgorithm());
assertEquals(eMat.getEncryptionKey(), dMat.getDecryptionKey());
assertEquals(macKey, dMat.getVerificationKey());
}
private static EncryptionContext ctx(EncryptionMaterials mat) {
return new EncryptionContext.Builder()
.withMaterialDescription(mat.getMaterialDescription())
.build();
}
}
| 5,016 |
0 | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/sdkv1/com/amazonaws/services/dynamodbv2/datamodeling/encryption | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/sdkv1/com/amazonaws/services/dynamodbv2/datamodeling/encryption/providers/CachingMostRecentProviderTests.java | // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package com.amazonaws.services.dynamodbv2.datamodeling.encryption.providers;
import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertFalse;
import static org.testng.AssertJUnit.assertNull;
import static org.testng.AssertJUnit.assertTrue;
import com.amazonaws.services.dynamodbv2.AmazonDynamoDB;
import com.amazonaws.services.dynamodbv2.datamodeling.encryption.DynamoDBEncryptor;
import com.amazonaws.services.dynamodbv2.datamodeling.encryption.EncryptionContext;
import com.amazonaws.services.dynamodbv2.datamodeling.encryption.materials.DecryptionMaterials;
import com.amazonaws.services.dynamodbv2.datamodeling.encryption.materials.EncryptionMaterials;
import com.amazonaws.services.dynamodbv2.datamodeling.encryption.providers.store.MetaStore;
import com.amazonaws.services.dynamodbv2.datamodeling.encryption.providers.store.ProviderStore;
import com.amazonaws.services.dynamodbv2.local.embedded.DynamoDBEmbedded;
import com.amazonaws.services.dynamodbv2.model.AttributeValue;
import com.amazonaws.services.dynamodbv2.model.ProvisionedThroughput;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
public class CachingMostRecentProviderTests {
private static final String TABLE_NAME = "keystoreTable";
private static final String MATERIAL_NAME = "material";
private static final String MATERIAL_PARAM = "materialName";
private static final SecretKey AES_KEY =
new SecretKeySpec(new byte[] {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}, "AES");
private static final SecretKey HMAC_KEY =
new SecretKeySpec(new byte[] {0, 1, 2, 3, 4, 5, 6, 7}, "HmacSHA256");
private static final EncryptionMaterialsProvider BASE_PROVIDER =
new SymmetricStaticProvider(AES_KEY, HMAC_KEY);
private static final DynamoDBEncryptor ENCRYPTOR = DynamoDBEncryptor.getInstance(BASE_PROVIDER);
private AmazonDynamoDB client;
private Map<String, Integer> methodCalls;
private ProviderStore store;
private EncryptionContext ctx;
@BeforeMethod
public void setup() {
methodCalls = new HashMap<String, Integer>();
client = instrument(DynamoDBEmbedded.create().amazonDynamoDB(), AmazonDynamoDB.class, methodCalls);
MetaStore.createTable(client, TABLE_NAME, new ProvisionedThroughput(1L, 1L));
store = new MetaStore(client, TABLE_NAME, ENCRYPTOR);
ctx = new EncryptionContext.Builder().build();
methodCalls.clear();
}
@Test
public void testConstructors() {
final CachingMostRecentProvider prov =
new CachingMostRecentProvider(store, MATERIAL_NAME, 100, 1000);
assertEquals(MATERIAL_NAME, prov.getMaterialName());
assertEquals(100, prov.getTtlInMills());
assertEquals(-1, prov.getCurrentVersion());
assertEquals(0, prov.getLastUpdated());
final CachingMostRecentProvider prov2 =
new CachingMostRecentProvider(store, MATERIAL_NAME, 500);
assertEquals(MATERIAL_NAME, prov2.getMaterialName());
assertEquals(500, prov2.getTtlInMills());
assertEquals(-1, prov2.getCurrentVersion());
assertEquals(0, prov2.getLastUpdated());
}
@Test
public void testSmallMaxCacheSize() {
final Map<String, AttributeValue> attr1 =
Collections.singletonMap(MATERIAL_PARAM, new AttributeValue("material1"));
final EncryptionContext ctx1 = ctx(attr1);
final Map<String, AttributeValue> attr2 =
Collections.singletonMap(MATERIAL_PARAM, new AttributeValue("material2"));
final EncryptionContext ctx2 = ctx(attr2);
final CachingMostRecentProvider prov = new ExtendedProvider(store, 500, 1);
assertNull(methodCalls.get("putItem"));
final EncryptionMaterials eMat1_1 = prov.getEncryptionMaterials(ctx1);
// It's a new provider, so we see a single putItem
assertEquals(1, (int) methodCalls.getOrDefault("putItem", 0));
methodCalls.clear();
final EncryptionMaterials eMat1_2 = prov.getEncryptionMaterials(ctx2);
// It's a new provider, so we see a single putItem
assertEquals(1, (int) methodCalls.getOrDefault("putItem", 0));
methodCalls.clear();
// Ensure the two materials are, in fact, different
assertFalse(eMat1_1.getSigningKey().equals(eMat1_2.getSigningKey()));
// Ensure the second set of materials are cached
final EncryptionMaterials eMat2_2 = prov.getEncryptionMaterials(ctx2);
assertTrue("Expected no calls but was " + methodCalls.toString(), methodCalls.isEmpty());
// Ensure the first set of materials are no longer cached, due to being the LRU
final EncryptionMaterials eMat2_1 = prov.getEncryptionMaterials(ctx1);
assertEquals(1, (int) methodCalls.getOrDefault("query", 0)); // To find current version
assertEquals(1, (int) methodCalls.getOrDefault("getItem", 0));
assertEquals(0, store.getVersionFromMaterialDescription(eMat1_2.getMaterialDescription()));
assertEquals(0, store.getVersionFromMaterialDescription(eMat2_2.getMaterialDescription()));
}
@Test
public void testSingleVersion() throws InterruptedException {
final CachingMostRecentProvider prov = new CachingMostRecentProvider(store, MATERIAL_NAME, 500);
assertNull(methodCalls.get("putItem"));
final EncryptionMaterials eMat1 = prov.getEncryptionMaterials(ctx);
// It's a new provider, so we see a single putItem
assertEquals(1, (int) methodCalls.getOrDefault("putItem", 0));
methodCalls.clear();
// Ensure the cache is working
final EncryptionMaterials eMat2 = prov.getEncryptionMaterials(ctx);
assertTrue("Expected no calls but was " + methodCalls.toString(), methodCalls.isEmpty());
assertEquals(0, store.getVersionFromMaterialDescription(eMat1.getMaterialDescription()));
assertEquals(0, store.getVersionFromMaterialDescription(eMat2.getMaterialDescription()));
// Let the TTL be exceeded
Thread.sleep(500);
final EncryptionMaterials eMat3 = prov.getEncryptionMaterials(ctx);
assertEquals(2, methodCalls.size());
assertEquals(1, (int) methodCalls.getOrDefault("query", 0)); // To find current version
assertEquals(1, (int) methodCalls.getOrDefault("getItem", 0)); // To get provider
assertEquals(0, store.getVersionFromMaterialDescription(eMat3.getMaterialDescription()));
assertEquals(eMat1.getSigningKey(), eMat2.getSigningKey());
assertEquals(eMat1.getSigningKey(), eMat3.getSigningKey());
// Check algorithms. Right now we only support AES and HmacSHA256
assertEquals("AES", eMat1.getEncryptionKey().getAlgorithm());
assertEquals("HmacSHA256", eMat1.getSigningKey().getAlgorithm());
// Ensure we can decrypt all of them without hitting ddb more than the minimum
final CachingMostRecentProvider prov2 =
new CachingMostRecentProvider(store, MATERIAL_NAME, 500);
final DecryptionMaterials dMat1 = prov2.getDecryptionMaterials(ctx(eMat1));
methodCalls.clear();
assertEquals(eMat1.getEncryptionKey(), dMat1.getDecryptionKey());
assertEquals(eMat1.getSigningKey(), dMat1.getVerificationKey());
final DecryptionMaterials dMat2 = prov2.getDecryptionMaterials(ctx(eMat2));
assertEquals(eMat2.getEncryptionKey(), dMat2.getDecryptionKey());
assertEquals(eMat2.getSigningKey(), dMat2.getVerificationKey());
final DecryptionMaterials dMat3 = prov2.getDecryptionMaterials(ctx(eMat3));
assertEquals(eMat3.getEncryptionKey(), dMat3.getDecryptionKey());
assertEquals(eMat3.getSigningKey(), dMat3.getVerificationKey());
assertTrue("Expected no calls but was " + methodCalls.toString(), methodCalls.isEmpty());
}
@Test
public void testSingleVersionWithRefresh() throws InterruptedException {
final CachingMostRecentProvider prov = new CachingMostRecentProvider(store, MATERIAL_NAME, 500);
assertNull(methodCalls.get("putItem"));
final EncryptionMaterials eMat1 = prov.getEncryptionMaterials(ctx);
// It's a new provider, so we see a single putItem
assertEquals(1, (int) methodCalls.getOrDefault("putItem", 0));
methodCalls.clear();
// Ensure the cache is working
final EncryptionMaterials eMat2 = prov.getEncryptionMaterials(ctx);
assertTrue("Expected no calls but was " + methodCalls.toString(), methodCalls.isEmpty());
assertEquals(0, store.getVersionFromMaterialDescription(eMat1.getMaterialDescription()));
assertEquals(0, store.getVersionFromMaterialDescription(eMat2.getMaterialDescription()));
prov.refresh();
final EncryptionMaterials eMat3 = prov.getEncryptionMaterials(ctx);
assertEquals(1, (int) methodCalls.getOrDefault("query", 0)); // To find current version
assertEquals(1, (int) methodCalls.getOrDefault("getItem", 0));
assertEquals(0, store.getVersionFromMaterialDescription(eMat3.getMaterialDescription()));
prov.refresh();
assertEquals(eMat1.getSigningKey(), eMat2.getSigningKey());
assertEquals(eMat1.getSigningKey(), eMat3.getSigningKey());
// Ensure that after cache refresh we only get one more hit as opposed to multiple
prov.getEncryptionMaterials(ctx);
Thread.sleep(700);
// Force refresh
prov.getEncryptionMaterials(ctx);
methodCalls.clear();
// Check to ensure no more hits
assertEquals(eMat1.getSigningKey(), prov.getEncryptionMaterials(ctx).getSigningKey());
assertEquals(eMat1.getSigningKey(), prov.getEncryptionMaterials(ctx).getSigningKey());
assertEquals(eMat1.getSigningKey(), prov.getEncryptionMaterials(ctx).getSigningKey());
assertEquals(eMat1.getSigningKey(), prov.getEncryptionMaterials(ctx).getSigningKey());
assertEquals(eMat1.getSigningKey(), prov.getEncryptionMaterials(ctx).getSigningKey());
assertTrue("Expected no calls but was " + methodCalls.toString(), methodCalls.isEmpty());
// Ensure we can decrypt all of them without hitting ddb more than the minimum
final CachingMostRecentProvider prov2 =
new CachingMostRecentProvider(store, MATERIAL_NAME, 500);
final DecryptionMaterials dMat1 = prov2.getDecryptionMaterials(ctx(eMat1));
methodCalls.clear();
assertEquals(eMat1.getEncryptionKey(), dMat1.getDecryptionKey());
assertEquals(eMat1.getSigningKey(), dMat1.getVerificationKey());
final DecryptionMaterials dMat2 = prov2.getDecryptionMaterials(ctx(eMat2));
assertEquals(eMat2.getEncryptionKey(), dMat2.getDecryptionKey());
assertEquals(eMat2.getSigningKey(), dMat2.getVerificationKey());
final DecryptionMaterials dMat3 = prov2.getDecryptionMaterials(ctx(eMat3));
assertEquals(eMat3.getEncryptionKey(), dMat3.getDecryptionKey());
assertEquals(eMat3.getSigningKey(), dMat3.getVerificationKey());
assertTrue("Expected no calls but was " + methodCalls.toString(), methodCalls.isEmpty());
}
@Test
public void testTwoVersions() throws InterruptedException {
final CachingMostRecentProvider prov = new CachingMostRecentProvider(store, MATERIAL_NAME, 500);
assertNull(methodCalls.get("putItem"));
final EncryptionMaterials eMat1 = prov.getEncryptionMaterials(ctx);
// It's a new provider, so we see a single putItem
assertEquals(1, (int) methodCalls.getOrDefault("putItem", 0));
methodCalls.clear();
// Create the new material
store.newProvider(MATERIAL_NAME);
methodCalls.clear();
// Ensure the cache is working
final EncryptionMaterials eMat2 = prov.getEncryptionMaterials(ctx);
assertTrue("Expected no calls but was " + methodCalls.toString(), methodCalls.isEmpty());
assertEquals(0, store.getVersionFromMaterialDescription(eMat1.getMaterialDescription()));
assertEquals(0, store.getVersionFromMaterialDescription(eMat2.getMaterialDescription()));
assertTrue("Expected no calls but was " + methodCalls.toString(), methodCalls.isEmpty());
// Let the TTL be exceeded
Thread.sleep(500);
final EncryptionMaterials eMat3 = prov.getEncryptionMaterials(ctx);
assertEquals(1, (int) methodCalls.getOrDefault("query", 0)); // To find current version
assertEquals(1, (int) methodCalls.getOrDefault("getItem", 0)); // To retrieve current version
assertNull(methodCalls.get("putItem")); // No attempt to create a new item
assertEquals(1, store.getVersionFromMaterialDescription(eMat3.getMaterialDescription()));
assertEquals(eMat1.getSigningKey(), eMat2.getSigningKey());
assertFalse(eMat1.getSigningKey().equals(eMat3.getSigningKey()));
// Ensure we can decrypt all of them without hitting ddb more than the minimum
final CachingMostRecentProvider prov2 =
new CachingMostRecentProvider(store, MATERIAL_NAME, 500);
final DecryptionMaterials dMat1 = prov2.getDecryptionMaterials(ctx(eMat1));
methodCalls.clear();
assertEquals(eMat1.getEncryptionKey(), dMat1.getDecryptionKey());
assertEquals(eMat1.getSigningKey(), dMat1.getVerificationKey());
final DecryptionMaterials dMat2 = prov2.getDecryptionMaterials(ctx(eMat2));
assertEquals(eMat2.getEncryptionKey(), dMat2.getDecryptionKey());
assertEquals(eMat2.getSigningKey(), dMat2.getVerificationKey());
final DecryptionMaterials dMat3 = prov2.getDecryptionMaterials(ctx(eMat3));
assertEquals(eMat3.getEncryptionKey(), dMat3.getDecryptionKey());
assertEquals(eMat3.getSigningKey(), dMat3.getVerificationKey());
// Get item will be hit once for the one old key
assertEquals(1, methodCalls.size());
assertEquals(1, (int) methodCalls.getOrDefault("getItem", 0));
}
@Test
public void testTwoVersionsWithRefresh() throws InterruptedException {
final CachingMostRecentProvider prov = new CachingMostRecentProvider(store, MATERIAL_NAME, 100);
assertNull(methodCalls.get("putItem"));
final EncryptionMaterials eMat1 = prov.getEncryptionMaterials(ctx);
// It's a new provider, so we see a single putItem
assertEquals(1, (int) methodCalls.getOrDefault("putItem", 0));
methodCalls.clear();
// Create the new material
store.newProvider(MATERIAL_NAME);
methodCalls.clear();
// Ensure the cache is working
final EncryptionMaterials eMat2 = prov.getEncryptionMaterials(ctx);
assertTrue("Expected no calls but was " + methodCalls.toString(), methodCalls.isEmpty());
assertEquals(0, store.getVersionFromMaterialDescription(eMat1.getMaterialDescription()));
assertEquals(0, store.getVersionFromMaterialDescription(eMat2.getMaterialDescription()));
prov.refresh();
final EncryptionMaterials eMat3 = prov.getEncryptionMaterials(ctx);
assertEquals(1, (int) methodCalls.getOrDefault("query", 0)); // To find current version
assertEquals(1, (int) methodCalls.getOrDefault("getItem", 0));
assertEquals(1, store.getVersionFromMaterialDescription(eMat3.getMaterialDescription()));
assertEquals(eMat1.getSigningKey(), eMat2.getSigningKey());
assertFalse(eMat1.getSigningKey().equals(eMat3.getSigningKey()));
// Ensure we can decrypt all of them without hitting ddb more than the minimum
final CachingMostRecentProvider prov2 =
new CachingMostRecentProvider(store, MATERIAL_NAME, 500);
final DecryptionMaterials dMat1 = prov2.getDecryptionMaterials(ctx(eMat1));
methodCalls.clear();
assertEquals(eMat1.getEncryptionKey(), dMat1.getDecryptionKey());
assertEquals(eMat1.getSigningKey(), dMat1.getVerificationKey());
final DecryptionMaterials dMat2 = prov2.getDecryptionMaterials(ctx(eMat2));
assertEquals(eMat2.getEncryptionKey(), dMat2.getDecryptionKey());
assertEquals(eMat2.getSigningKey(), dMat2.getVerificationKey());
final DecryptionMaterials dMat3 = prov2.getDecryptionMaterials(ctx(eMat3));
assertEquals(eMat3.getEncryptionKey(), dMat3.getDecryptionKey());
assertEquals(eMat3.getSigningKey(), dMat3.getVerificationKey());
// Get item will be hit once for the one old key
assertEquals(1, methodCalls.size());
assertEquals(1, (int) methodCalls.getOrDefault("getItem", 0));
}
@Test
public void testSingleVersionTwoMaterials() throws InterruptedException {
final Map<String, AttributeValue> attr1 =
Collections.singletonMap(MATERIAL_PARAM, new AttributeValue("material1"));
final EncryptionContext ctx1 = ctx(attr1);
final Map<String, AttributeValue> attr2 =
Collections.singletonMap(MATERIAL_PARAM, new AttributeValue("material2"));
final EncryptionContext ctx2 = ctx(attr2);
final CachingMostRecentProvider prov = new ExtendedProvider(store, 500, 100);
assertNull(methodCalls.get("putItem"));
final EncryptionMaterials eMat1_1 = prov.getEncryptionMaterials(ctx1);
// It's a new provider, so we see a single putItem
assertEquals(1, (int) methodCalls.getOrDefault("putItem", 0));
methodCalls.clear();
final EncryptionMaterials eMat1_2 = prov.getEncryptionMaterials(ctx2);
// It's a new provider, so we see a single putItem
assertEquals(1, (int) methodCalls.getOrDefault("putItem", 0));
methodCalls.clear();
// Ensure the two materials are, in fact, different
assertFalse(eMat1_1.getSigningKey().equals(eMat1_2.getSigningKey()));
// Ensure the cache is working
final EncryptionMaterials eMat2_1 = prov.getEncryptionMaterials(ctx1);
assertTrue("Expected no calls but was " + methodCalls.toString(), methodCalls.isEmpty());
assertEquals(0, store.getVersionFromMaterialDescription(eMat1_1.getMaterialDescription()));
assertEquals(0, store.getVersionFromMaterialDescription(eMat2_1.getMaterialDescription()));
final EncryptionMaterials eMat2_2 = prov.getEncryptionMaterials(ctx2);
assertTrue("Expected no calls but was " + methodCalls.toString(), methodCalls.isEmpty());
assertEquals(0, store.getVersionFromMaterialDescription(eMat1_2.getMaterialDescription()));
assertEquals(0, store.getVersionFromMaterialDescription(eMat2_2.getMaterialDescription()));
// Let the TTL be exceeded
Thread.sleep(500);
final EncryptionMaterials eMat3_1 = prov.getEncryptionMaterials(ctx1);
assertEquals(2, methodCalls.size());
assertEquals(1, (int) methodCalls.get("query")); // To find current version
assertEquals(1, (int) methodCalls.get("getItem")); // To get the provider
assertEquals(0, store.getVersionFromMaterialDescription(eMat3_1.getMaterialDescription()));
methodCalls.clear();
final EncryptionMaterials eMat3_2 = prov.getEncryptionMaterials(ctx2);
assertEquals(2, methodCalls.size());
assertEquals(1, (int) methodCalls.get("query")); // To find current version
assertEquals(1, (int) methodCalls.get("getItem")); // To get the provider
assertEquals(0, store.getVersionFromMaterialDescription(eMat3_2.getMaterialDescription()));
assertEquals(eMat1_1.getSigningKey(), eMat2_1.getSigningKey());
assertEquals(eMat1_2.getSigningKey(), eMat2_2.getSigningKey());
assertEquals(eMat1_1.getSigningKey(), eMat3_1.getSigningKey());
assertEquals(eMat1_2.getSigningKey(), eMat3_2.getSigningKey());
// Check algorithms. Right now we only support AES and HmacSHA256
assertEquals("AES", eMat1_1.getEncryptionKey().getAlgorithm());
assertEquals("AES", eMat1_2.getEncryptionKey().getAlgorithm());
assertEquals("HmacSHA256", eMat1_1.getSigningKey().getAlgorithm());
assertEquals("HmacSHA256", eMat1_2.getSigningKey().getAlgorithm());
// Ensure we can decrypt all of them without hitting ddb more than the minimum
final CachingMostRecentProvider prov2 = new ExtendedProvider(store, 500, 100);
final DecryptionMaterials dMat1_1 = prov2.getDecryptionMaterials(ctx(eMat1_1, attr1));
final DecryptionMaterials dMat1_2 = prov2.getDecryptionMaterials(ctx(eMat1_2, attr2));
methodCalls.clear();
assertEquals(eMat1_1.getEncryptionKey(), dMat1_1.getDecryptionKey());
assertEquals(eMat1_2.getEncryptionKey(), dMat1_2.getDecryptionKey());
assertEquals(eMat1_1.getSigningKey(), dMat1_1.getVerificationKey());
assertEquals(eMat1_2.getSigningKey(), dMat1_2.getVerificationKey());
final DecryptionMaterials dMat2_1 = prov2.getDecryptionMaterials(ctx(eMat2_1, attr1));
final DecryptionMaterials dMat2_2 = prov2.getDecryptionMaterials(ctx(eMat2_2, attr2));
assertEquals(eMat2_1.getEncryptionKey(), dMat2_1.getDecryptionKey());
assertEquals(eMat2_2.getEncryptionKey(), dMat2_2.getDecryptionKey());
assertEquals(eMat2_1.getSigningKey(), dMat2_1.getVerificationKey());
assertEquals(eMat2_2.getSigningKey(), dMat2_2.getVerificationKey());
final DecryptionMaterials dMat3_1 = prov2.getDecryptionMaterials(ctx(eMat3_1, attr1));
final DecryptionMaterials dMat3_2 = prov2.getDecryptionMaterials(ctx(eMat3_2, attr2));
assertEquals(eMat3_1.getEncryptionKey(), dMat3_1.getDecryptionKey());
assertEquals(eMat3_2.getEncryptionKey(), dMat3_2.getDecryptionKey());
assertEquals(eMat3_1.getSigningKey(), dMat3_1.getVerificationKey());
assertEquals(eMat3_2.getSigningKey(), dMat3_2.getVerificationKey());
assertTrue("Expected no calls but was " + methodCalls.toString(), methodCalls.isEmpty());
}
@Test
public void testSingleVersionWithTwoMaterialsWithRefresh() throws InterruptedException {
final Map<String, AttributeValue> attr1 =
Collections.singletonMap(MATERIAL_PARAM, new AttributeValue("material1"));
final EncryptionContext ctx1 = ctx(attr1);
final Map<String, AttributeValue> attr2 =
Collections.singletonMap(MATERIAL_PARAM, new AttributeValue("material2"));
final EncryptionContext ctx2 = ctx(attr2);
final CachingMostRecentProvider prov = new ExtendedProvider(store, 500, 100);
assertNull(methodCalls.get("putItem"));
final EncryptionMaterials eMat1_1 = prov.getEncryptionMaterials(ctx1);
// It's a new provider, so we see a single putItem
assertEquals(1, (int) methodCalls.getOrDefault("putItem", 0));
methodCalls.clear();
final EncryptionMaterials eMat1_2 = prov.getEncryptionMaterials(ctx2);
// It's a new provider, so we see a single putItem
assertEquals(1, (int) methodCalls.getOrDefault("putItem", 0));
methodCalls.clear();
// Ensure the two materials are, in fact, different
assertFalse(eMat1_1.getSigningKey().equals(eMat1_2.getSigningKey()));
// Ensure the cache is working
final EncryptionMaterials eMat2_1 = prov.getEncryptionMaterials(ctx1);
assertTrue("Expected no calls but was " + methodCalls.toString(), methodCalls.isEmpty());
assertEquals(0, store.getVersionFromMaterialDescription(eMat1_1.getMaterialDescription()));
assertEquals(0, store.getVersionFromMaterialDescription(eMat2_1.getMaterialDescription()));
final EncryptionMaterials eMat2_2 = prov.getEncryptionMaterials(ctx2);
assertTrue("Expected no calls but was " + methodCalls.toString(), methodCalls.isEmpty());
assertEquals(0, store.getVersionFromMaterialDescription(eMat1_2.getMaterialDescription()));
assertEquals(0, store.getVersionFromMaterialDescription(eMat2_2.getMaterialDescription()));
prov.refresh();
final EncryptionMaterials eMat3_1 = prov.getEncryptionMaterials(ctx1);
assertEquals(1, (int) methodCalls.getOrDefault("query", 0)); // To find current version
assertEquals(1, (int) methodCalls.getOrDefault("getItem", 0));
final EncryptionMaterials eMat3_2 = prov.getEncryptionMaterials(ctx2);
assertEquals(2, (int) methodCalls.getOrDefault("query", 0)); // To find current version
assertEquals(2, (int) methodCalls.getOrDefault("getItem", 0));
assertEquals(0, store.getVersionFromMaterialDescription(eMat3_1.getMaterialDescription()));
assertEquals(0, store.getVersionFromMaterialDescription(eMat3_2.getMaterialDescription()));
prov.refresh();
assertEquals(eMat1_1.getSigningKey(), eMat2_1.getSigningKey());
assertEquals(eMat1_1.getSigningKey(), eMat3_1.getSigningKey());
assertEquals(eMat1_2.getSigningKey(), eMat2_2.getSigningKey());
assertEquals(eMat1_2.getSigningKey(), eMat3_2.getSigningKey());
// Ensure that after cache refresh we only get one more hit as opposed to multiple
prov.getEncryptionMaterials(ctx1);
prov.getEncryptionMaterials(ctx2);
Thread.sleep(700);
// Force refresh
prov.getEncryptionMaterials(ctx1);
prov.getEncryptionMaterials(ctx2);
methodCalls.clear();
// Check to ensure no more hits
assertEquals(eMat1_1.getSigningKey(), prov.getEncryptionMaterials(ctx1).getSigningKey());
assertEquals(eMat1_1.getSigningKey(), prov.getEncryptionMaterials(ctx1).getSigningKey());
assertEquals(eMat1_1.getSigningKey(), prov.getEncryptionMaterials(ctx1).getSigningKey());
assertEquals(eMat1_1.getSigningKey(), prov.getEncryptionMaterials(ctx1).getSigningKey());
assertEquals(eMat1_1.getSigningKey(), prov.getEncryptionMaterials(ctx1).getSigningKey());
assertEquals(eMat1_2.getSigningKey(), prov.getEncryptionMaterials(ctx2).getSigningKey());
assertEquals(eMat1_2.getSigningKey(), prov.getEncryptionMaterials(ctx2).getSigningKey());
assertEquals(eMat1_2.getSigningKey(), prov.getEncryptionMaterials(ctx2).getSigningKey());
assertEquals(eMat1_2.getSigningKey(), prov.getEncryptionMaterials(ctx2).getSigningKey());
assertEquals(eMat1_2.getSigningKey(), prov.getEncryptionMaterials(ctx2).getSigningKey());
assertTrue("Expected no calls but was " + methodCalls.toString(), methodCalls.isEmpty());
// Ensure we can decrypt all of them without hitting ddb more than the minimum
final CachingMostRecentProvider prov2 = new ExtendedProvider(store, 500, 100);
final DecryptionMaterials dMat1_1 = prov2.getDecryptionMaterials(ctx(eMat1_1, attr1));
final DecryptionMaterials dMat1_2 = prov2.getDecryptionMaterials(ctx(eMat1_2, attr2));
methodCalls.clear();
assertEquals(eMat1_1.getEncryptionKey(), dMat1_1.getDecryptionKey());
assertEquals(eMat1_2.getEncryptionKey(), dMat1_2.getDecryptionKey());
assertEquals(eMat1_1.getSigningKey(), dMat1_1.getVerificationKey());
assertEquals(eMat1_2.getSigningKey(), dMat1_2.getVerificationKey());
final DecryptionMaterials dMat2_1 = prov2.getDecryptionMaterials(ctx(eMat2_1, attr1));
final DecryptionMaterials dMat2_2 = prov2.getDecryptionMaterials(ctx(eMat2_2, attr2));
assertEquals(eMat2_1.getEncryptionKey(), dMat2_1.getDecryptionKey());
assertEquals(eMat2_2.getEncryptionKey(), dMat2_2.getDecryptionKey());
assertEquals(eMat2_1.getSigningKey(), dMat2_1.getVerificationKey());
assertEquals(eMat2_2.getSigningKey(), dMat2_2.getVerificationKey());
final DecryptionMaterials dMat3_1 = prov2.getDecryptionMaterials(ctx(eMat3_1, attr1));
final DecryptionMaterials dMat3_2 = prov2.getDecryptionMaterials(ctx(eMat3_2, attr2));
assertEquals(eMat3_1.getEncryptionKey(), dMat3_1.getDecryptionKey());
assertEquals(eMat3_2.getEncryptionKey(), dMat3_2.getDecryptionKey());
assertEquals(eMat3_1.getSigningKey(), dMat3_1.getVerificationKey());
assertEquals(eMat3_2.getSigningKey(), dMat3_2.getVerificationKey());
assertTrue("Expected no calls but was " + methodCalls.toString(), methodCalls.isEmpty());
}
@Test
public void testTwoVersionsWithTwoMaterialsWithRefresh() throws InterruptedException {
final Map<String, AttributeValue> attr1 =
Collections.singletonMap(MATERIAL_PARAM, new AttributeValue("material1"));
final EncryptionContext ctx1 = ctx(attr1);
final Map<String, AttributeValue> attr2 =
Collections.singletonMap(MATERIAL_PARAM, new AttributeValue("material2"));
final EncryptionContext ctx2 = ctx(attr2);
final CachingMostRecentProvider prov = new ExtendedProvider(store, 500, 100);
assertNull(methodCalls.get("putItem"));
final EncryptionMaterials eMat1_1 = prov.getEncryptionMaterials(ctx1);
// It's a new provider, so we see a single putItem
assertEquals(1, (int) methodCalls.getOrDefault("putItem", 0));
methodCalls.clear();
final EncryptionMaterials eMat1_2 = prov.getEncryptionMaterials(ctx2);
// It's a new provider, so we see a single putItem
assertEquals(1, (int) methodCalls.getOrDefault("putItem", 0));
methodCalls.clear();
// Create the new material
store.newProvider("material1");
store.newProvider("material2");
methodCalls.clear();
// Ensure the cache is working
final EncryptionMaterials eMat2_1 = prov.getEncryptionMaterials(ctx1);
final EncryptionMaterials eMat2_2 = prov.getEncryptionMaterials(ctx2);
assertTrue("Expected no calls but was " + methodCalls.toString(), methodCalls.isEmpty());
assertEquals(0, store.getVersionFromMaterialDescription(eMat1_1.getMaterialDescription()));
assertEquals(0, store.getVersionFromMaterialDescription(eMat2_1.getMaterialDescription()));
assertEquals(0, store.getVersionFromMaterialDescription(eMat1_2.getMaterialDescription()));
assertEquals(0, store.getVersionFromMaterialDescription(eMat2_2.getMaterialDescription()));
prov.refresh();
final EncryptionMaterials eMat3_1 = prov.getEncryptionMaterials(ctx1);
final EncryptionMaterials eMat3_2 = prov.getEncryptionMaterials(ctx2);
assertEquals(2, (int) methodCalls.getOrDefault("query", 0)); // To find current version
assertEquals(2, (int) methodCalls.getOrDefault("getItem", 0));
assertEquals(1, store.getVersionFromMaterialDescription(eMat3_1.getMaterialDescription()));
assertEquals(1, store.getVersionFromMaterialDescription(eMat3_2.getMaterialDescription()));
assertEquals(eMat1_1.getSigningKey(), eMat2_1.getSigningKey());
assertFalse(eMat1_1.getSigningKey().equals(eMat3_1.getSigningKey()));
assertEquals(eMat1_2.getSigningKey(), eMat2_2.getSigningKey());
assertFalse(eMat1_2.getSigningKey().equals(eMat3_2.getSigningKey()));
// Ensure we can decrypt all of them without hitting ddb more than the minimum
final CachingMostRecentProvider prov2 = new ExtendedProvider(store, 500, 100);
final DecryptionMaterials dMat1_1 = prov2.getDecryptionMaterials(ctx(eMat1_1, attr1));
final DecryptionMaterials dMat1_2 = prov2.getDecryptionMaterials(ctx(eMat1_2, attr2));
methodCalls.clear();
assertEquals(eMat1_1.getEncryptionKey(), dMat1_1.getDecryptionKey());
assertEquals(eMat1_2.getEncryptionKey(), dMat1_2.getDecryptionKey());
assertEquals(eMat1_1.getSigningKey(), dMat1_1.getVerificationKey());
assertEquals(eMat1_2.getSigningKey(), dMat1_2.getVerificationKey());
final DecryptionMaterials dMat2_1 = prov2.getDecryptionMaterials(ctx(eMat2_1, attr1));
final DecryptionMaterials dMat2_2 = prov2.getDecryptionMaterials(ctx(eMat2_2, attr2));
assertEquals(eMat2_1.getEncryptionKey(), dMat2_1.getDecryptionKey());
assertEquals(eMat2_2.getEncryptionKey(), dMat2_2.getDecryptionKey());
assertEquals(eMat2_1.getSigningKey(), dMat2_1.getVerificationKey());
assertEquals(eMat2_2.getSigningKey(), dMat2_2.getVerificationKey());
final DecryptionMaterials dMat3_1 = prov2.getDecryptionMaterials(ctx(eMat3_1, attr1));
final DecryptionMaterials dMat3_2 = prov2.getDecryptionMaterials(ctx(eMat3_2, attr2));
assertEquals(eMat3_1.getEncryptionKey(), dMat3_1.getDecryptionKey());
assertEquals(eMat3_2.getEncryptionKey(), dMat3_2.getDecryptionKey());
assertEquals(eMat3_1.getSigningKey(), dMat3_1.getVerificationKey());
assertEquals(eMat3_2.getSigningKey(), dMat3_2.getVerificationKey());
// Get item will be hit twice, once for each old key
assertEquals(1, methodCalls.size());
assertEquals(2, (int) methodCalls.getOrDefault("getItem", 0));
}
private static EncryptionContext ctx(final Map<String, AttributeValue> attr) {
return new EncryptionContext.Builder().withAttributeValues(attr).build();
}
private static EncryptionContext ctx(
final EncryptionMaterials mat, Map<String, AttributeValue> attr) {
return new EncryptionContext.Builder()
.withAttributeValues(attr)
.withMaterialDescription(mat.getMaterialDescription())
.build();
}
private static EncryptionContext ctx(final EncryptionMaterials mat) {
return new EncryptionContext.Builder()
.withMaterialDescription(mat.getMaterialDescription())
.build();
}
private static class ExtendedProvider extends CachingMostRecentProvider {
public ExtendedProvider(ProviderStore keystore, long ttlInMillis, int maxCacheSize) {
super(keystore, null, ttlInMillis, maxCacheSize);
}
@Override
public long getCurrentVersion() {
throw new UnsupportedOperationException();
}
@Override
protected String getMaterialName(final EncryptionContext context) {
return context.getAttributeValues().get(MATERIAL_PARAM).getS();
}
}
@SuppressWarnings("unchecked")
private static <T> T instrument(
final T obj, final Class<T> clazz, final Map<String, Integer> map) {
return (T)
Proxy.newProxyInstance(
clazz.getClassLoader(),
new Class[] {clazz},
new InvocationHandler() {
private final Object lock = new Object();
@Override
public Object invoke(final Object proxy, final Method method, final Object[] args)
throws Throwable {
synchronized (lock) {
try {
final Integer oldCount = map.get(method.getName());
if (oldCount != null) {
map.put(method.getName(), oldCount + 1);
} else {
map.put(method.getName(), 1);
}
return method.invoke(obj, args);
} catch (final InvocationTargetException ex) {
throw ex.getCause();
}
}
}
});
}
}
| 5,017 |
0 | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/sdkv1/com/amazonaws/services/dynamodbv2/datamodeling/encryption/providers | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/sdkv1/com/amazonaws/services/dynamodbv2/datamodeling/encryption/providers/store/MetaStoreTests.java | /*
* Copyright 2015 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.services.dynamodbv2.datamodeling.encryption.providers.store;
import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertNotNull;
import static org.testng.AssertJUnit.fail;
import com.amazonaws.services.dynamodbv2.AmazonDynamoDB;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMappingException;
import com.amazonaws.services.dynamodbv2.datamodeling.encryption.DynamoDBEncryptor;
import com.amazonaws.services.dynamodbv2.datamodeling.encryption.EncryptionContext;
import com.amazonaws.services.dynamodbv2.datamodeling.encryption.materials.DecryptionMaterials;
import com.amazonaws.services.dynamodbv2.datamodeling.encryption.materials.EncryptionMaterials;
import com.amazonaws.services.dynamodbv2.datamodeling.encryption.providers.EncryptionMaterialsProvider;
import com.amazonaws.services.dynamodbv2.datamodeling.encryption.providers.SymmetricStaticProvider;
import com.amazonaws.services.dynamodbv2.local.embedded.DynamoDBEmbedded;
import com.amazonaws.services.dynamodbv2.model.AttributeValue;
import com.amazonaws.services.dynamodbv2.model.ProvisionedThroughput;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
public class MetaStoreTests {
private static final String SOURCE_TABLE_NAME = "keystoreTable";
private static final String DESTINATION_TABLE_NAME = "keystoreDestinationTable";
private static final String MATERIAL_NAME = "material";
private static final SecretKey AES_KEY =
new SecretKeySpec(new byte[] {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}, "AES");
private static final SecretKey TARGET_AES_KEY =
new SecretKeySpec(
new byte[] {0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30}, "AES");
private static final SecretKey HMAC_KEY =
new SecretKeySpec(new byte[] {0, 1, 2, 3, 4, 5, 6, 7}, "HmacSHA256");
private static final SecretKey TARGET_HMAC_KEY =
new SecretKeySpec(new byte[] {0, 2, 4, 6, 8, 10, 12, 14}, "HmacSHA256");
private static final EncryptionMaterialsProvider BASE_PROVIDER =
new SymmetricStaticProvider(AES_KEY, HMAC_KEY);
private static final EncryptionMaterialsProvider TARGET_BASE_PROVIDER =
new SymmetricStaticProvider(TARGET_AES_KEY, TARGET_HMAC_KEY);
private static final DynamoDBEncryptor ENCRYPTOR = DynamoDBEncryptor.getInstance(BASE_PROVIDER);
private static final DynamoDBEncryptor TARGET_ENCRYPTOR =
DynamoDBEncryptor.getInstance(TARGET_BASE_PROVIDER);
private AmazonDynamoDB client;
private AmazonDynamoDB targetClient;
private MetaStore store;
private MetaStore targetStore;
private EncryptionContext ctx;
private static class TestExtraDataSupplier implements MetaStore.ExtraDataSupplier {
private final Map<String, AttributeValue> attributeValueMap;
private final Set<String> signedOnlyFieldNames;
public TestExtraDataSupplier(
final Map<String, AttributeValue> attributeValueMap,
final Set<String> signedOnlyFieldNames) {
this.attributeValueMap = attributeValueMap;
this.signedOnlyFieldNames = signedOnlyFieldNames;
}
@Override
public Map<String, AttributeValue> getAttributes(String materialName, long version) {
return this.attributeValueMap;
}
@Override
public Set<String> getSignedOnlyFieldNames() {
return this.signedOnlyFieldNames;
}
}
@BeforeMethod
public void setup() {
client = synchronize(DynamoDBEmbedded.create().amazonDynamoDB(), AmazonDynamoDB.class);
targetClient = synchronize(DynamoDBEmbedded.create().amazonDynamoDB(), AmazonDynamoDB.class);
MetaStore.createTable(client, SOURCE_TABLE_NAME, new ProvisionedThroughput(1L, 1L));
// Creating Targeted DynamoDB Object
MetaStore.createTable(targetClient, DESTINATION_TABLE_NAME, new ProvisionedThroughput(1L, 1L));
store = new MetaStore(client, SOURCE_TABLE_NAME, ENCRYPTOR);
targetStore = new MetaStore(targetClient, DESTINATION_TABLE_NAME, TARGET_ENCRYPTOR);
ctx = new EncryptionContext.Builder().build();
}
@Test
public void testNoMaterials() {
assertEquals(-1, store.getMaxVersion(MATERIAL_NAME));
}
@Test
public void singleMaterial() {
assertEquals(-1, store.getMaxVersion(MATERIAL_NAME));
final EncryptionMaterialsProvider prov = store.newProvider(MATERIAL_NAME);
assertEquals(0, store.getMaxVersion(MATERIAL_NAME));
final EncryptionMaterials eMat = prov.getEncryptionMaterials(ctx);
final SecretKey encryptionKey = eMat.getEncryptionKey();
assertNotNull(encryptionKey);
final DecryptionMaterials dMat = prov.getDecryptionMaterials(ctx(eMat));
assertEquals(0, store.getVersionFromMaterialDescription(eMat.getMaterialDescription()));
assertEquals(encryptionKey, dMat.getDecryptionKey());
assertEquals(eMat.getSigningKey(), dMat.getVerificationKey());
}
@Test
public void singleMaterialExplicitAccess() {
assertEquals(-1, store.getMaxVersion(MATERIAL_NAME));
final EncryptionMaterialsProvider prov1 = store.newProvider(MATERIAL_NAME);
assertEquals(0, store.getMaxVersion(MATERIAL_NAME));
final EncryptionMaterialsProvider prov2 = store.getProvider(MATERIAL_NAME);
final EncryptionMaterials eMat = prov1.getEncryptionMaterials(ctx);
final SecretKey encryptionKey = eMat.getEncryptionKey();
assertNotNull(encryptionKey);
final DecryptionMaterials dMat = prov2.getDecryptionMaterials(ctx(eMat));
assertEquals(0, store.getVersionFromMaterialDescription(eMat.getMaterialDescription()));
assertEquals(encryptionKey, dMat.getDecryptionKey());
assertEquals(eMat.getSigningKey(), dMat.getVerificationKey());
}
@Test
public void singleMaterialExplicitAccessWithVersion() {
assertEquals(-1, store.getMaxVersion(MATERIAL_NAME));
final EncryptionMaterialsProvider prov1 = store.newProvider(MATERIAL_NAME);
assertEquals(0, store.getMaxVersion(MATERIAL_NAME));
final EncryptionMaterialsProvider prov2 = store.getProvider(MATERIAL_NAME, 0);
final EncryptionMaterials eMat = prov1.getEncryptionMaterials(ctx);
final SecretKey encryptionKey = eMat.getEncryptionKey();
assertNotNull(encryptionKey);
final DecryptionMaterials dMat = prov2.getDecryptionMaterials(ctx(eMat));
assertEquals(0, store.getVersionFromMaterialDescription(eMat.getMaterialDescription()));
assertEquals(encryptionKey, dMat.getDecryptionKey());
assertEquals(eMat.getSigningKey(), dMat.getVerificationKey());
}
@Test
public void singleMaterialWithImplicitCreation() {
assertEquals(-1, store.getMaxVersion(MATERIAL_NAME));
final EncryptionMaterialsProvider prov = store.getProvider(MATERIAL_NAME);
assertEquals(0, store.getMaxVersion(MATERIAL_NAME));
final EncryptionMaterials eMat = prov.getEncryptionMaterials(ctx);
final SecretKey encryptionKey = eMat.getEncryptionKey();
assertNotNull(encryptionKey);
final DecryptionMaterials dMat = prov.getDecryptionMaterials(ctx(eMat));
assertEquals(0, store.getVersionFromMaterialDescription(eMat.getMaterialDescription()));
assertEquals(encryptionKey, dMat.getDecryptionKey());
assertEquals(eMat.getSigningKey(), dMat.getVerificationKey());
}
@Test
public void twoDifferentMaterials() {
assertEquals(-1, store.getMaxVersion(MATERIAL_NAME));
final EncryptionMaterialsProvider prov1 = store.newProvider(MATERIAL_NAME);
assertEquals(0, store.getMaxVersion(MATERIAL_NAME));
final EncryptionMaterialsProvider prov2 = store.newProvider(MATERIAL_NAME);
assertEquals(1, store.getMaxVersion(MATERIAL_NAME));
final EncryptionMaterials eMat = prov1.getEncryptionMaterials(ctx);
assertEquals(0, store.getVersionFromMaterialDescription(eMat.getMaterialDescription()));
final SecretKey encryptionKey = eMat.getEncryptionKey();
assertNotNull(encryptionKey);
try {
prov2.getDecryptionMaterials(ctx(eMat));
fail("Missing expected exception");
} catch (final DynamoDBMappingException ex) {
// Expected Exception
}
final EncryptionMaterials eMat2 = prov2.getEncryptionMaterials(ctx);
assertEquals(1, store.getVersionFromMaterialDescription(eMat2.getMaterialDescription()));
}
@Test
public void getOrCreateCollision() {
assertEquals(-1, store.getMaxVersion(MATERIAL_NAME));
final EncryptionMaterialsProvider prov1 = store.getOrCreate(MATERIAL_NAME, 0);
assertEquals(0, store.getMaxVersion(MATERIAL_NAME));
final EncryptionMaterialsProvider prov2 = store.getOrCreate(MATERIAL_NAME, 0);
final EncryptionMaterials eMat = prov1.getEncryptionMaterials(ctx);
final SecretKey encryptionKey = eMat.getEncryptionKey();
assertNotNull(encryptionKey);
final DecryptionMaterials dMat = prov2.getDecryptionMaterials(ctx(eMat));
assertEquals(encryptionKey, dMat.getDecryptionKey());
assertEquals(eMat.getSigningKey(), dMat.getVerificationKey());
}
@Test
public void getOrCreateWithContextSupplier() {
final Map<String, AttributeValue> attributeValueMap = new HashMap<>();
attributeValueMap.put("CustomKeyId", new AttributeValue().withS("testCustomKeyId"));
attributeValueMap.put("KeyToken", new AttributeValue().withS("testKeyToken"));
final Set<String> signedOnlyAttributes = new HashSet<>();
signedOnlyAttributes.add("CustomKeyId");
final TestExtraDataSupplier extraDataSupplier =
new TestExtraDataSupplier(attributeValueMap, signedOnlyAttributes);
final MetaStore metaStore =
new MetaStore(client, SOURCE_TABLE_NAME, ENCRYPTOR, extraDataSupplier);
assertEquals(-1, metaStore.getMaxVersion(MATERIAL_NAME));
final EncryptionMaterialsProvider prov1 = metaStore.getOrCreate(MATERIAL_NAME, 0);
assertEquals(0, metaStore.getMaxVersion(MATERIAL_NAME));
final EncryptionMaterialsProvider prov2 = metaStore.getOrCreate(MATERIAL_NAME, 0);
final EncryptionMaterials eMat = prov1.getEncryptionMaterials(ctx);
final SecretKey encryptionKey = eMat.getEncryptionKey();
assertNotNull(encryptionKey);
final DecryptionMaterials dMat = prov2.getDecryptionMaterials(ctx(eMat));
assertEquals(encryptionKey, dMat.getDecryptionKey());
assertEquals(eMat.getSigningKey(), dMat.getVerificationKey());
}
@Test
public void replicateIntermediateKeysTest() {
assertEquals(-1, store.getMaxVersion(MATERIAL_NAME));
final EncryptionMaterialsProvider prov1 = store.getOrCreate(MATERIAL_NAME, 0);
assertEquals(0, store.getMaxVersion(MATERIAL_NAME));
store.replicate(MATERIAL_NAME, 0, targetStore);
assertEquals(0, targetStore.getMaxVersion(MATERIAL_NAME));
final EncryptionMaterials eMat = prov1.getEncryptionMaterials(ctx);
final DecryptionMaterials dMat =
targetStore.getProvider(MATERIAL_NAME, 0).getDecryptionMaterials(ctx(eMat));
assertEquals(eMat.getEncryptionKey(), dMat.getDecryptionKey());
assertEquals(eMat.getSigningKey(), dMat.getVerificationKey());
}
@Test(expectedExceptions = IndexOutOfBoundsException.class)
public void replicateIntermediateKeysWhenMaterialNotFoundTest() {
store.replicate(MATERIAL_NAME, 0, targetStore);
}
@Test
public void newProviderCollision() throws InterruptedException {
final SlowNewProvider slowProv = new SlowNewProvider();
assertEquals(-1, store.getMaxVersion(MATERIAL_NAME));
assertEquals(-1, slowProv.slowStore.getMaxVersion(MATERIAL_NAME));
slowProv.start();
Thread.sleep(100);
final EncryptionMaterialsProvider prov1 = store.newProvider(MATERIAL_NAME);
slowProv.join();
assertEquals(0, store.getMaxVersion(MATERIAL_NAME));
assertEquals(0, slowProv.slowStore.getMaxVersion(MATERIAL_NAME));
final EncryptionMaterialsProvider prov2 = slowProv.result;
final EncryptionMaterials eMat = prov1.getEncryptionMaterials(ctx);
final SecretKey encryptionKey = eMat.getEncryptionKey();
assertNotNull(encryptionKey);
final DecryptionMaterials dMat = prov2.getDecryptionMaterials(ctx(eMat));
assertEquals(encryptionKey, dMat.getDecryptionKey());
assertEquals(eMat.getSigningKey(), dMat.getVerificationKey());
}
@Test(expectedExceptions = IndexOutOfBoundsException.class)
public void invalidVersion() {
store.getProvider(MATERIAL_NAME, 1000);
}
@Test(expectedExceptions = IllegalArgumentException.class)
public void invalidSignedOnlyField() {
final Map<String, AttributeValue> attributeValueMap = new HashMap<>();
attributeValueMap.put("enc", new AttributeValue().withS("testEncryptionKey"));
final Set<String> signedOnlyAttributes = new HashSet<>();
signedOnlyAttributes.add("enc");
final TestExtraDataSupplier extraDataSupplier =
new TestExtraDataSupplier(attributeValueMap, signedOnlyAttributes);
new MetaStore(client, SOURCE_TABLE_NAME, ENCRYPTOR, extraDataSupplier);
}
private static EncryptionContext ctx(final EncryptionMaterials mat) {
return new EncryptionContext.Builder()
.withMaterialDescription(mat.getMaterialDescription())
.build();
}
private class SlowNewProvider extends Thread {
public volatile EncryptionMaterialsProvider result;
public ProviderStore slowStore =
new MetaStore(client, SOURCE_TABLE_NAME, ENCRYPTOR) {
@Override
public EncryptionMaterialsProvider newProvider(final String materialName) {
final long nextId = getMaxVersion(materialName) + 1;
try {
Thread.sleep(1000);
} catch (final InterruptedException e) {
// Ignored
}
return getOrCreate(materialName, nextId);
}
};
@Override
public void run() {
result = slowStore.newProvider(MATERIAL_NAME);
}
}
@SuppressWarnings("unchecked")
private static <T> T synchronize(final T obj, final Class<T> clazz) {
return (T)
Proxy.newProxyInstance(
clazz.getClassLoader(),
new Class[] {clazz},
new InvocationHandler() {
private final Object lock = new Object();
@Override
public Object invoke(final Object proxy, final Method method, final Object[] args)
throws Throwable {
synchronized (lock) {
try {
return method.invoke(obj, args);
} catch (final InvocationTargetException ex) {
throw ex.getCause();
}
}
}
});
}
}
| 5,018 |
0 | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/sdkv1/com/amazonaws/services/dynamodbv2/datamodeling/encryption | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/sdkv1/com/amazonaws/services/dynamodbv2/datamodeling/encryption/utils/EncryptionContextOperatorsTest.java | package com.amazonaws.services.dynamodbv2.datamodeling.encryption.utils;
import static com.amazonaws.services.dynamodbv2.datamodeling.encryption.utils.EncryptionContextOperators.overrideEncryptionContextTableName;
import static com.amazonaws.services.dynamodbv2.datamodeling.encryption.utils.EncryptionContextOperators.overrideEncryptionContextTableNameUsingMap;
import static org.testng.AssertJUnit.assertEquals;
import com.amazonaws.services.dynamodbv2.datamodeling.encryption.EncryptionContext;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;
import org.testng.annotations.Test;
public class EncryptionContextOperatorsTest {
@Test
public void testCreateEncryptionContextTableNameOverride_expectedOverride() {
Function<EncryptionContext, EncryptionContext> myNewTableName =
overrideEncryptionContextTableName("OriginalTableName", "MyNewTableName");
EncryptionContext context =
new EncryptionContext.Builder().withTableName("OriginalTableName").build();
EncryptionContext newContext = myNewTableName.apply(context);
assertEquals("OriginalTableName", context.getTableName());
assertEquals("MyNewTableName", newContext.getTableName());
}
/**
* Some pretty clear repetition in null cases. May make sense to replace with data providers or
* parameterized classes for null cases
*/
@Test
public void testNullCasesCreateEncryptionContextTableNameOverride_nullOriginalTableName() {
assertEncryptionContextUnchanged(
new EncryptionContext.Builder().withTableName("example").build(), null, "MyNewTableName");
}
@Test
public void testCreateEncryptionContextTableNameOverride_differentOriginalTableName() {
assertEncryptionContextUnchanged(
new EncryptionContext.Builder().withTableName("example").build(),
"DifferentTableName",
"MyNewTableName");
}
@Test
public void testNullCasesCreateEncryptionContextTableNameOverride_nullEncryptionContext() {
assertEncryptionContextUnchanged(null, "DifferentTableName", "MyNewTableName");
}
@Test
public void testCreateEncryptionContextTableNameOverrideMap_expectedOverride() {
Map<String, String> tableNameOverrides = new HashMap<>();
tableNameOverrides.put("OriginalTableName", "MyNewTableName");
Function<EncryptionContext, EncryptionContext> nameOverrideMap =
overrideEncryptionContextTableNameUsingMap(tableNameOverrides);
EncryptionContext context =
new EncryptionContext.Builder().withTableName("OriginalTableName").build();
EncryptionContext newContext = nameOverrideMap.apply(context);
assertEquals("OriginalTableName", context.getTableName());
assertEquals("MyNewTableName", newContext.getTableName());
}
@Test
public void testCreateEncryptionContextTableNameOverrideMap_multipleOverrides() {
Map<String, String> tableNameOverrides = new HashMap<>();
tableNameOverrides.put("OriginalTableName1", "MyNewTableName1");
tableNameOverrides.put("OriginalTableName2", "MyNewTableName2");
Function<EncryptionContext, EncryptionContext> overrideOperator =
overrideEncryptionContextTableNameUsingMap(tableNameOverrides);
EncryptionContext context =
new EncryptionContext.Builder().withTableName("OriginalTableName1").build();
EncryptionContext newContext = overrideOperator.apply(context);
assertEquals("OriginalTableName1", context.getTableName());
assertEquals("MyNewTableName1", newContext.getTableName());
EncryptionContext context2 =
new EncryptionContext.Builder().withTableName("OriginalTableName2").build();
EncryptionContext newContext2 = overrideOperator.apply(context2);
assertEquals("OriginalTableName2", context2.getTableName());
assertEquals("MyNewTableName2", newContext2.getTableName());
}
@Test
public void
testNullCasesCreateEncryptionContextTableNameOverrideFromMap_nullEncryptionContextTableName() {
Map<String, String> tableNameOverrides = new HashMap<>();
tableNameOverrides.put("DifferentTableName", "MyNewTableName");
assertEncryptionContextUnchangedFromMap(
new EncryptionContext.Builder().build(), tableNameOverrides);
}
@Test
public void testNullCasesCreateEncryptionContextTableNameOverrideFromMap_nullEncryptionContext() {
Map<String, String> tableNameOverrides = new HashMap<>();
tableNameOverrides.put("DifferentTableName", "MyNewTableName");
assertEncryptionContextUnchangedFromMap(null, tableNameOverrides);
}
@Test
public void testNullCasesCreateEncryptionContextTableNameOverrideFromMap_nullOriginalTableName() {
Map<String, String> tableNameOverrides = new HashMap<>();
tableNameOverrides.put(null, "MyNewTableName");
assertEncryptionContextUnchangedFromMap(
new EncryptionContext.Builder().withTableName("example").build(), tableNameOverrides);
}
@Test
public void testNullCasesCreateEncryptionContextTableNameOverrideFromMap_nullNewTableName() {
Map<String, String> tableNameOverrides = new HashMap<>();
tableNameOverrides.put("MyOriginalTableName", null);
assertEncryptionContextUnchangedFromMap(
new EncryptionContext.Builder().withTableName("MyOriginalTableName").build(),
tableNameOverrides);
}
@Test
public void testNullCasesCreateEncryptionContextTableNameOverrideFromMap_nullMap() {
assertEncryptionContextUnchangedFromMap(
new EncryptionContext.Builder().withTableName("MyOriginalTableName").build(), null);
}
private void assertEncryptionContextUnchanged(
EncryptionContext encryptionContext, String originalTableName, String newTableName) {
Function<EncryptionContext, EncryptionContext> encryptionContextTableNameOverride =
overrideEncryptionContextTableName(originalTableName, newTableName);
EncryptionContext newEncryptionContext =
encryptionContextTableNameOverride.apply(encryptionContext);
assertEquals(encryptionContext, newEncryptionContext);
}
private void assertEncryptionContextUnchangedFromMap(
EncryptionContext encryptionContext, Map<String, String> overrideMap) {
Function<EncryptionContext, EncryptionContext> encryptionContextTableNameOverrideFromMap =
overrideEncryptionContextTableNameUsingMap(overrideMap);
EncryptionContext newEncryptionContext =
encryptionContextTableNameOverrideFromMap.apply(encryptionContext);
assertEquals(encryptionContext, newEncryptionContext);
}
}
| 5,019 |
0 | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/sdkv1/com/amazonaws/services/dynamodbv2/datamodeling | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/sdkv1/com/amazonaws/services/dynamodbv2/datamodeling/internal/ByteBufferInputStreamTest.java | /*
* Copyright 2014 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.services.dynamodbv2.datamodeling.internal;
import static org.testng.AssertJUnit.assertArrayEquals;
import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertFalse;
import java.io.IOException;
import java.nio.ByteBuffer;
import org.testng.annotations.Test;
public class ByteBufferInputStreamTest {
@Test
public void testRead() throws IOException {
ByteBufferInputStream bis =
new ByteBufferInputStream(ByteBuffer.wrap(new byte[] {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}));
for (int x = 0; x < 10; ++x) {
assertEquals(10 - x, bis.available());
assertEquals(x, bis.read());
}
assertEquals(0, bis.available());
bis.close();
}
@Test
public void testReadByteArray() throws IOException {
ByteBufferInputStream bis =
new ByteBufferInputStream(ByteBuffer.wrap(new byte[] {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}));
assertEquals(10, bis.available());
byte[] buff = new byte[4];
int len = bis.read(buff);
assertEquals(4, len);
assertEquals(6, bis.available());
assertArrayEquals(new byte[] {0, 1, 2, 3}, buff);
len = bis.read(buff);
assertEquals(4, len);
assertEquals(2, bis.available());
assertArrayEquals(new byte[] {4, 5, 6, 7}, buff);
len = bis.read(buff);
assertEquals(2, len);
assertEquals(0, bis.available());
assertArrayEquals(new byte[] {8, 9, 6, 7}, buff);
bis.close();
}
@Test
public void testSkip() throws IOException {
ByteBufferInputStream bis =
new ByteBufferInputStream(
ByteBuffer.wrap(new byte[] {(byte) 0xFA, 15, 15, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9}));
assertEquals(13, bis.available());
assertEquals(0xFA, bis.read());
assertEquals(12, bis.available());
bis.skip(2);
assertEquals(10, bis.available());
for (int x = 0; x < 10; ++x) {
assertEquals(x, bis.read());
}
assertEquals(0, bis.available());
assertEquals(-1, bis.read());
bis.close();
}
@Test
public void testMarkSupported() throws IOException {
try (ByteBufferInputStream bis = new ByteBufferInputStream(ByteBuffer.allocate(0))) {
assertFalse(bis.markSupported());
}
}
}
| 5,020 |
0 | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/sdkv1/com/amazonaws/services/dynamodbv2/datamodeling | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/sdkv1/com/amazonaws/services/dynamodbv2/datamodeling/internal/LRUCacheTest.java | // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package com.amazonaws.services.dynamodbv2.datamodeling.internal;
import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertNull;
import static org.testng.AssertJUnit.assertTrue;
import org.testng.annotations.Test;
public class LRUCacheTest {
@Test
public void test() {
final LRUCache<String> cache = new LRUCache<String>(3);
assertEquals(0, cache.size());
assertEquals(3, cache.getMaxSize());
cache.add("k1", "v1");
assertTrue(cache.size() == 1);
cache.add("k1", "v11");
assertTrue(cache.size() == 1);
cache.add("k2", "v2");
assertTrue(cache.size() == 2);
cache.add("k3", "v3");
assertTrue(cache.size() == 3);
assertEquals("v11", cache.get("k1"));
assertEquals("v2", cache.get("k2"));
assertEquals("v3", cache.get("k3"));
cache.add("k4", "v4");
assertTrue(cache.size() == 3);
assertNull(cache.get("k1"));
assertEquals("v4", cache.get("k4"));
assertEquals("v2", cache.get("k2"));
assertEquals("v3", cache.get("k3"));
assertTrue(cache.size() == 3);
cache.add("k5", "v5");
assertNull(cache.get("k4"));
assertEquals("v5", cache.get("k5"));
assertEquals("v2", cache.get("k2"));
assertEquals("v3", cache.get("k3"));
cache.clear();
assertEquals(0, cache.size());
}
@Test
public void testRemove() {
final LRUCache<String> cache = new LRUCache<String>(3);
assertEquals(0, cache.size());
assertEquals(3, cache.getMaxSize());
cache.add("k1", "v1");
assertTrue(cache.size() == 1);
final String oldValue = cache.remove("k1");
assertTrue(cache.size() == 0);
assertEquals("v1", oldValue);
assertNull(cache.get("k1"));
final String emptyValue = cache.remove("k1");
assertTrue(cache.size() == 0);
assertNull(emptyValue);
assertNull(cache.get("k1"));
}
@Test
public void testClear() {
final LRUCache<String> cache = new LRUCache<String>(3);
assertEquals(0, cache.size());
cache.clear();
assertEquals(0, cache.size());
cache.add("k1", "v1");
cache.add("k2", "v2");
cache.add("k3", "v3");
assertTrue(cache.size() == 3);
cache.clear();
assertTrue(cache.size() == 0);
assertNull(cache.get("k1"));
assertNull(cache.get("k2"));
assertNull(cache.get("k3"));
}
@Test(expectedExceptions = IllegalArgumentException.class)
public void testZeroSize() {
new LRUCache<Object>(0);
}
@Test(expectedExceptions = IllegalArgumentException.class)
public void testIllegalArgument() {
new LRUCache<Object>(-1);
}
@Test
public void testSingleEntry() {
final LRUCache<String> cache = new LRUCache<String>(1);
assertTrue(cache.size() == 0);
cache.add("k1", "v1");
assertTrue(cache.size() == 1);
cache.add("k1", "v11");
assertTrue(cache.size() == 1);
assertEquals("v11", cache.get("k1"));
cache.add("k2", "v2");
assertTrue(cache.size() == 1);
assertEquals("v2", cache.get("k2"));
assertNull(cache.get("k1"));
cache.add("k3", "v3");
assertTrue(cache.size() == 1);
assertEquals("v3", cache.get("k3"));
assertNull(cache.get("k2"));
}
}
| 5,021 |
0 | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/sdkv1/com/amazonaws/services/dynamodbv2/datamodeling | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/sdkv1/com/amazonaws/services/dynamodbv2/datamodeling/internal/AttributeValueMarshallerTest.java | /*
* Copyright 2014 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.services.dynamodbv2.datamodeling.internal;
import static com.amazonaws.services.dynamodbv2.datamodeling.internal.AttributeValueMarshaller.marshall;
import static com.amazonaws.services.dynamodbv2.datamodeling.internal.AttributeValueMarshaller.unmarshall;
import com.amazonaws.services.dynamodbv2.model.AttributeValue;
import com.amazonaws.util.Base64;
import java.nio.ByteBuffer;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.testng.Assert;
import org.testng.AssertJUnit;
import org.testng.annotations.Test;
public class AttributeValueMarshallerTest {
@Test(expectedExceptions = IllegalArgumentException.class)
public void testEmpty() {
AttributeValue av = new AttributeValue();
marshall(av);
}
@Test
public void testNumber() {
AttributeValue av = new AttributeValue().withN("1337");
assertEquals(av, unmarshall(marshall(av)));
}
@Test
public void testString() {
AttributeValue av = new AttributeValue().withS("1337");
assertEquals(av, unmarshall(marshall(av)));
}
@Test
public void testByteBuffer() {
AttributeValue av = new AttributeValue().withB(ByteBuffer.wrap(new byte[] {0, 1, 2, 3, 4, 5}));
assertEquals(av, unmarshall(marshall(av)));
}
// We can't use straight .equals for comparison because Attribute Values represents Sets
// as Lists and so incorrectly does an ordered comparison
@Test
public void testNumberS() {
AttributeValue av =
new AttributeValue().withNS(Collections.unmodifiableList(Arrays.asList("1337", "1", "5")));
assertEquals(av, unmarshall(marshall(av)));
}
@Test
public void testNumberSOrdering() {
AttributeValue av1 =
new AttributeValue().withNS(Collections.unmodifiableList(Arrays.asList("1337", "1", "5")));
AttributeValue av2 =
new AttributeValue().withNS(Collections.unmodifiableList(Arrays.asList("1", "5", "1337")));
assertEquals(av1, av2);
ByteBuffer buff1 = marshall(av1);
ByteBuffer buff2 = marshall(av2);
Assert.assertEquals(buff1, buff2);
}
@Test
public void testStringS() {
AttributeValue av =
new AttributeValue().withSS(Collections.unmodifiableList(Arrays.asList("Bob", "Ann", "5")));
assertEquals(av, unmarshall(marshall(av)));
}
@Test
public void testStringSOrdering() {
AttributeValue av1 =
new AttributeValue().withSS(Collections.unmodifiableList(Arrays.asList("Bob", "Ann", "5")));
AttributeValue av2 =
new AttributeValue().withSS(Collections.unmodifiableList(Arrays.asList("Ann", "Bob", "5")));
assertEquals(av1, av2);
ByteBuffer buff1 = marshall(av1);
ByteBuffer buff2 = marshall(av2);
Assert.assertEquals(buff1, buff2);
}
@Test
public void testByteBufferS() {
AttributeValue av =
new AttributeValue()
.withBS(
Collections.unmodifiableList(
Arrays.asList(
ByteBuffer.wrap(new byte[] {0, 1, 2, 3, 4, 5}),
ByteBuffer.wrap(new byte[] {5, 4, 3, 2, 1, 0, 0, 0, 5, 6, 7}))));
assertEquals(av, unmarshall(marshall(av)));
}
@Test
public void testByteBufferSOrdering() {
AttributeValue av1 =
new AttributeValue()
.withBS(
Collections.unmodifiableList(
Arrays.asList(
ByteBuffer.wrap(new byte[] {0, 1, 2, 3, 4, 5}),
ByteBuffer.wrap(new byte[] {5, 4, 3, 2, 1, 0, 0, 0, 5, 6, 7}))));
AttributeValue av2 =
new AttributeValue()
.withBS(
Collections.unmodifiableList(
Arrays.asList(
ByteBuffer.wrap(new byte[] {5, 4, 3, 2, 1, 0, 0, 0, 5, 6, 7}),
ByteBuffer.wrap(new byte[] {0, 1, 2, 3, 4, 5}))));
assertEquals(av1, av2);
ByteBuffer buff1 = marshall(av1);
ByteBuffer buff2 = marshall(av2);
Assert.assertEquals(buff1, buff2);
}
@Test
public void testBoolTrue() {
AttributeValue av = new AttributeValue().withBOOL(Boolean.TRUE);
assertEquals(av, unmarshall(marshall(av)));
}
@Test
public void testBoolFalse() {
AttributeValue av = new AttributeValue().withBOOL(Boolean.FALSE);
assertEquals(av, unmarshall(marshall(av)));
}
@Test
public void testNULL() {
AttributeValue av = new AttributeValue().withNULL(Boolean.TRUE);
assertEquals(av, unmarshall(marshall(av)));
}
@Test(expectedExceptions = NullPointerException.class)
public void testActualNULL() {
unmarshall(marshall(null));
}
@Test
public void testEmptyList() {
AttributeValue av = new AttributeValue().withL();
assertEquals(av, unmarshall(marshall(av)));
}
@Test
public void testListOfString() {
AttributeValue av = new AttributeValue().withL(new AttributeValue().withS("StringValue"));
assertEquals(av, unmarshall(marshall(av)));
}
@Test
public void testList() {
AttributeValue av =
new AttributeValue()
.withL(
new AttributeValue().withS("StringValue"),
new AttributeValue().withN("1000"),
new AttributeValue().withBOOL(Boolean.TRUE));
assertEquals(av, unmarshall(marshall(av)));
}
@Test
public void testListWithNull() {
final AttributeValue av =
new AttributeValue()
.withL(
new AttributeValue().withS("StringValue"),
new AttributeValue().withN("1000"),
new AttributeValue().withBOOL(Boolean.TRUE),
null);
try {
marshall(av);
Assert.fail("Unexpected success");
} catch (final NullPointerException npe) {
Assert.assertEquals(
"Encountered null list entry value while marshalling attribute value {L: [{S: StringValue,}, {N: 1000,}, {BOOL: true}, null],}",
npe.getMessage());
}
}
@Test
public void testListDuplicates() {
AttributeValue av =
new AttributeValue()
.withL(
new AttributeValue().withN("1000"),
new AttributeValue().withN("1000"),
new AttributeValue().withN("1000"),
new AttributeValue().withN("1000"));
AttributeValue result = unmarshall(marshall(av));
assertEquals(av, result);
Assert.assertEquals(4, result.getL().size());
}
@Test
public void testComplexList() {
final List<AttributeValue> list1 =
Arrays.asList(
new AttributeValue().withS("StringValue"),
new AttributeValue().withN("1000"),
new AttributeValue().withBOOL(Boolean.TRUE));
final List<AttributeValue> list22 =
Arrays.asList(
new AttributeValue().withS("AWS"),
new AttributeValue().withN("-3700"),
new AttributeValue().withBOOL(Boolean.FALSE));
final List<AttributeValue> list2 =
Arrays.asList(
new AttributeValue().withL(list22), new AttributeValue().withNULL(Boolean.TRUE));
AttributeValue av =
new AttributeValue()
.withL(
new AttributeValue().withS("StringValue1"),
new AttributeValue().withL(list1),
new AttributeValue().withN("50"),
new AttributeValue().withL(list2));
assertEquals(av, unmarshall(marshall(av)));
}
@Test
public void testEmptyMap() {
Map<String, AttributeValue> map = new HashMap<String, AttributeValue>();
AttributeValue av = new AttributeValue().withM(map);
assertEquals(av, unmarshall(marshall(av)));
}
@Test
public void testSimpleMap() {
Map<String, AttributeValue> map = new HashMap<String, AttributeValue>();
map.put("KeyValue", new AttributeValue().withS("ValueValue"));
AttributeValue av = new AttributeValue().withM(map);
assertEquals(av, unmarshall(marshall(av)));
}
@Test
public void testSimpleMapWithNull() {
final Map<String, AttributeValue> map = new HashMap<String, AttributeValue>();
map.put("KeyValue", new AttributeValue().withS("ValueValue"));
map.put("NullKeyValue", null);
final AttributeValue av = new AttributeValue().withM(map);
try {
marshall(av);
Assert.fail("Unexpected success");
} catch (final NullPointerException npe) {
// Map entries may permute under nondeterministic Java API
String npeMessage = npe.getMessage();
String common =
"Encountered null map value for key NullKeyValue while marshalling attribute value ";
String case1 = common + "{M: {KeyValue={S: ValueValue,}, NullKeyValue=null},}";
String case2 = common + "{M: {NullKeyValue=null, KeyValue={S: ValueValue,}},}";
Assert.assertTrue(case1.equals(npeMessage) || case2.equals(npeMessage));
}
}
@Test
public void testMapOrdering() {
LinkedHashMap<String, AttributeValue> m1 = new LinkedHashMap<String, AttributeValue>();
LinkedHashMap<String, AttributeValue> m2 = new LinkedHashMap<String, AttributeValue>();
m1.put("Value1", new AttributeValue().withN("1"));
m1.put("Value2", new AttributeValue().withBOOL(Boolean.TRUE));
m2.put("Value2", new AttributeValue().withBOOL(Boolean.TRUE));
m2.put("Value1", new AttributeValue().withN("1"));
AttributeValue av1 = new AttributeValue().withM(m1);
AttributeValue av2 = new AttributeValue().withM(m2);
ByteBuffer buff1 = marshall(av1);
ByteBuffer buff2 = marshall(av2);
Assert.assertEquals(buff1, buff2);
assertEquals(av1, unmarshall(buff1));
assertEquals(av1, unmarshall(buff2));
assertEquals(av2, unmarshall(buff1));
assertEquals(av2, unmarshall(buff2));
}
@Test
public void testComplexMap() {
AttributeValue av = buildComplexAttributeValue();
assertEquals(av, unmarshall(marshall(av)));
}
// This test ensures that an AttributeValue marshalled by an older
// version of this library still unmarshalls correctly. It also
// ensures that old and new marshalling is identical.
@Test
public void testVersioningCompatibility() {
AttributeValue newObject = buildComplexAttributeValue();
byte[] oldBytes = Base64.decode(COMPLEX_ATTRIBUTE_MARSHALLED);
byte[] newBytes = marshall(newObject).array();
AssertJUnit.assertArrayEquals(oldBytes, newBytes);
AttributeValue oldObject = unmarshall(ByteBuffer.wrap(oldBytes));
assertEquals(oldObject, newObject);
}
private static final String COMPLEX_ATTRIBUTE_MARSHALLED =
"AE0AAAADAHM"
+ "AAAAJSW5uZXJMaXN0AEwAAAAGAHMAAAALQ29tcGxleExpc3QAbgAAAAE1AGIAA"
+ "AAGAAECAwQFAEwAAAAFAD8BAAAAAABMAAAAAQA/AABNAAAAAwBzAAAABFBpbms"
+ "AcwAAAAVGbG95ZABzAAAABFRlc3QAPwEAcwAAAAdWZXJzaW9uAG4AAAABMQAAA"
+ "E0AAAADAHMAAAAETGlzdABMAAAABQBuAAAAATUAbgAAAAE0AG4AAAABMwBuAAA"
+ "AATIAbgAAAAExAHMAAAADTWFwAE0AAAABAHMAAAAGTmVzdGVkAD8BAHMAAAAEV"
+ "HJ1ZQA/AQBzAAAACVNpbmdsZU1hcABNAAAAAQBzAAAAA0ZPTwBzAAAAA0JBUgB"
+ "zAAAACVN0cmluZ1NldABTAAAAAwAAAANiYXIAAAADYmF6AAAAA2Zvbw==";
private static AttributeValue buildComplexAttributeValue() {
Map<String, AttributeValue> floydMap = new HashMap<String, AttributeValue>();
floydMap.put("Pink", new AttributeValue().withS("Floyd"));
floydMap.put("Version", new AttributeValue().withN("1"));
floydMap.put("Test", new AttributeValue().withBOOL(Boolean.TRUE));
List<AttributeValue> floydList =
Arrays.asList(
new AttributeValue().withBOOL(Boolean.TRUE),
new AttributeValue().withNULL(Boolean.TRUE),
new AttributeValue().withNULL(Boolean.TRUE),
new AttributeValue().withL(new AttributeValue().withBOOL(Boolean.FALSE)),
new AttributeValue().withM(floydMap));
List<AttributeValue> nestedList =
Arrays.asList(
new AttributeValue().withN("5"),
new AttributeValue().withN("4"),
new AttributeValue().withN("3"),
new AttributeValue().withN("2"),
new AttributeValue().withN("1"));
Map<String, AttributeValue> nestedMap = new HashMap<String, AttributeValue>();
nestedMap.put("True", new AttributeValue().withBOOL(Boolean.TRUE));
nestedMap.put("List", new AttributeValue().withL(nestedList));
nestedMap.put(
"Map",
new AttributeValue()
.withM(
Collections.singletonMap("Nested", new AttributeValue().withBOOL(Boolean.TRUE))));
List<AttributeValue> innerList =
Arrays.asList(
new AttributeValue().withS("ComplexList"),
new AttributeValue().withN("5"),
new AttributeValue().withB(ByteBuffer.wrap(new byte[] {0, 1, 2, 3, 4, 5})),
new AttributeValue().withL(floydList),
new AttributeValue().withNULL(Boolean.TRUE),
new AttributeValue().withM(nestedMap));
AttributeValue av = new AttributeValue();
av.addMEntry(
"SingleMap",
new AttributeValue()
.withM(Collections.singletonMap("FOO", new AttributeValue().withS("BAR"))));
av.addMEntry("InnerList", new AttributeValue().withL(innerList));
av.addMEntry("StringSet", new AttributeValue().withSS("foo", "bar", "baz"));
return av;
}
private void assertEquals(AttributeValue o1, AttributeValue o2) {
Assert.assertEquals(o1.getB(), o2.getB());
assertSetsEqual(o1.getBS(), o2.getBS());
Assert.assertEquals(o1.getN(), o2.getN());
assertSetsEqual(o1.getNS(), o2.getNS());
Assert.assertEquals(o1.getS(), o2.getS());
assertSetsEqual(o1.getSS(), o2.getSS());
Assert.assertEquals(o1.getBOOL(), o2.getBOOL());
Assert.assertEquals(o1.getNULL(), o2.getNULL());
if (o1.getL() != null) {
Assert.assertNotNull(o2.getL());
final List<AttributeValue> l1 = o1.getL();
final List<AttributeValue> l2 = o2.getL();
Assert.assertEquals(l1.size(), l2.size());
for (int x = 0; x < l1.size(); ++x) {
assertEquals(l1.get(x), l2.get(x));
}
}
if (o1.getM() != null) {
Assert.assertNotNull(o2.getM());
final Map<String, AttributeValue> m1 = o1.getM();
final Map<String, AttributeValue> m2 = o2.getM();
Assert.assertEquals(m1.size(), m2.size());
for (Map.Entry<String, AttributeValue> entry : m1.entrySet()) {
assertEquals(entry.getValue(), m2.get(entry.getKey()));
}
}
}
private <T> void assertSetsEqual(Collection<T> c1, Collection<T> c2) {
Assert.assertFalse(c1 == null ^ c2 == null);
if (c1 != null) {
Set<T> s1 = new HashSet<T>(c1);
Set<T> s2 = new HashSet<T>(c2);
Assert.assertEquals(s1, s2);
}
}
}
| 5,022 |
0 | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/sdkv1/com/amazonaws/services/dynamodbv2/datamodeling | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/sdkv1/com/amazonaws/services/dynamodbv2/datamodeling/internal/Base64Tests.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.services.dynamodbv2.datamodeling.internal;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.quicktheories.QuickTheory.qt;
import static org.quicktheories.generators.Generate.byteArrays;
import static org.quicktheories.generators.Generate.bytes;
import static org.quicktheories.generators.SourceDSL.integers;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import org.apache.commons.lang3.StringUtils;
import org.testng.annotations.Test;
/** Tests for the Base64 interface used by the DynamoDBEncryptionClient */
public class Base64Tests {
@Test
public void testBase64EncodeEquivalence() {
qt().forAll(
byteArrays(
integers().between(0, 1000000), bytes(Byte.MIN_VALUE, Byte.MAX_VALUE, (byte) 0)))
.check(
(a) -> {
// Base64 encode using both implementations and check for equality of output
// in case one version produces different output
String sdk1Base64 = com.amazonaws.util.Base64.encodeAsString(a);
String encryptionClientBase64 = Base64.encodeToString(a);
return StringUtils.equals(sdk1Base64, encryptionClientBase64);
});
}
@Test
public void testBase64DecodeEquivalence() {
qt().forAll(
byteArrays(
integers().between(0, 10000), bytes(Byte.MIN_VALUE, Byte.MAX_VALUE, (byte) 0)))
.as((b) -> java.util.Base64.getMimeEncoder().encodeToString(b))
.check(
(s) -> {
// Check for equality using the MimeEncoder, which inserts newlines
// The encryptionClient's decoder is expected to ignore them
byte[] sdk1Bytes = com.amazonaws.util.Base64.decode(s);
byte[] encryptionClientBase64 = Base64.decode(s);
return Arrays.equals(sdk1Bytes, encryptionClientBase64);
});
}
@Test
public void testNullDecodeBehavior() {
byte[] decoded = Base64.decode(null);
assertThat(decoded, equalTo(null));
}
@Test
public void testNullDecodeBehaviorSdk1() {
byte[] decoded = com.amazonaws.util.Base64.decode((String) null);
assertThat(decoded, equalTo(null));
byte[] decoded2 = com.amazonaws.util.Base64.decode((byte[]) null);
assertThat(decoded2, equalTo(null));
}
@Test
public void testBase64PaddingBehavior() {
String testInput = "another one bites the dust";
String expectedEncoding = "YW5vdGhlciBvbmUgYml0ZXMgdGhlIGR1c3Q=";
assertThat(
Base64.encodeToString(testInput.getBytes(StandardCharsets.UTF_8)),
equalTo(expectedEncoding));
String encodingWithoutPadding = "YW5vdGhlciBvbmUgYml0ZXMgdGhlIGR1c3Q";
assertThat(Base64.decode(encodingWithoutPadding), equalTo(testInput.getBytes()));
}
@Test(expectedExceptions = IllegalArgumentException.class)
public void testBase64PaddingBehaviorSdk1() {
String testInput = "another one bites the dust";
String encodingWithoutPadding = "YW5vdGhlciBvbmUgYml0ZXMgdGhlIGR1c3Q";
com.amazonaws.util.Base64.decode(encodingWithoutPadding);
}
@Test
public void rfc4648TestVectors() {
assertThat(Base64.encodeToString("".getBytes(StandardCharsets.UTF_8)), equalTo(""));
assertThat(Base64.encodeToString("f".getBytes(StandardCharsets.UTF_8)), equalTo("Zg=="));
assertThat(Base64.encodeToString("fo".getBytes(StandardCharsets.UTF_8)), equalTo("Zm8="));
assertThat(Base64.encodeToString("foo".getBytes(StandardCharsets.UTF_8)), equalTo("Zm9v"));
assertThat(Base64.encodeToString("foob".getBytes(StandardCharsets.UTF_8)), equalTo("Zm9vYg=="));
assertThat(
Base64.encodeToString("fooba".getBytes(StandardCharsets.UTF_8)), equalTo("Zm9vYmE="));
assertThat(
Base64.encodeToString("foobar".getBytes(StandardCharsets.UTF_8)), equalTo("Zm9vYmFy"));
}
}
| 5,023 |
0 | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/sdkv1/com/amazonaws/services/dynamodbv2/datamodeling | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/sdkv1/com/amazonaws/services/dynamodbv2/datamodeling/internal/HkdfTests.java | /*
* Copyright 2015 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.services.dynamodbv2.datamodeling.internal;
import static org.testng.AssertJUnit.assertArrayEquals;
import org.testng.annotations.Test;
public class HkdfTests {
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));
Hkdf kdf = Hkdf.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];
Hkdf kdf = Hkdf.getInstance(trial.algo);
kdf.init(trial.ikm, trial.salt);
// Just ensuring no exceptions are thrown
kdf.deriveKey((String) null, 16);
kdf.deriveKey((byte[]) null, 16);
}
@Test
public void defaultSalt() throws Exception {
// Tests all the different ways to get the default salt
testCase trial = testCases[0];
Hkdf kdf1 = Hkdf.getInstance(trial.algo);
kdf1.init(trial.ikm, null);
Hkdf kdf2 = Hkdf.getInstance(trial.algo);
kdf2.init(trial.ikm, new byte[0]);
Hkdf kdf3 = Hkdf.getInstance(trial.algo);
kdf3.init(trial.ikm);
Hkdf kdf4 = Hkdf.getInstance(trial.algo);
kdf4.init(trial.ikm, new byte[32]);
byte[] key1 = kdf1.deriveKey("Test", 16);
byte[] key2 = kdf2.deriveKey("Test", 16);
byte[] key3 = kdf3.deriveKey("Test", 16);
byte[] key4 = kdf4.deriveKey("Test", 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;
public 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;
}
}
}
| 5,024 |
0 | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/sdkv1/com/amazonaws/services/dynamodbv2/datamodeling | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/sdkv1/com/amazonaws/services/dynamodbv2/datamodeling/internal/TTLCacheTest.java | // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package com.amazonaws.services.dynamodbv2.datamodeling.internal;
import static org.mockito.Matchers.any;
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 static org.testng.Assert.assertThrows;
import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertNull;
import static org.testng.AssertJUnit.assertTrue;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import org.testng.annotations.Test;
public class TTLCacheTest {
private static final long TTL_GRACE_IN_NANO = TimeUnit.MILLISECONDS.toNanos(500);
@Test(expectedExceptions = IllegalArgumentException.class)
public void testInvalidSize() {
final TTLCache<String> cache = new TTLCache<String>(0, 1000, mock(TTLCache.EntryLoader.class));
}
@Test(expectedExceptions = IllegalArgumentException.class)
public void testInvalidTTL() {
final TTLCache<String> cache = new TTLCache<String>(3, 0, mock(TTLCache.EntryLoader.class));
}
@Test(expectedExceptions = NullPointerException.class)
public void testNullLoader() {
final TTLCache<String> cache = new TTLCache<String>(3, 1000, null);
}
@Test
public void testConstructor() {
final TTLCache<String> cache =
new TTLCache<String>(1000, 1000, mock(TTLCache.EntryLoader.class));
assertEquals(0, cache.size());
assertEquals(1000, cache.getMaxSize());
}
@Test
public void testLoadPastMaxSize() {
final String loadedValue = "loaded value";
final long ttlInMillis = 1000;
final int maxSize = 1;
TTLCache.EntryLoader loader = spy(TTLCache.EntryLoader.class);
when(loader.load(any())).thenReturn(loadedValue);
MsClock clock = mock(MsClock.class);
when(clock.timestampNano()).thenReturn((long) 0);
final TTLCache<String> cache = new TTLCache<String>(maxSize, ttlInMillis, loader);
cache.clock = clock;
assertEquals(0, cache.size());
assertEquals(maxSize, cache.getMaxSize());
cache.load("k1");
verify(loader, times(1)).load("k1");
assertTrue(cache.size() == 1);
String result = cache.load("k2");
verify(loader, times(1)).load("k2");
assertTrue(cache.size() == 1);
assertEquals(loadedValue, result);
// to verify result is in the cache, load one more time
// and expect the loader to not be called
String cachedValue = cache.load("k2");
verifyNoMoreInteractions(loader);
assertTrue(cache.size() == 1);
assertEquals(loadedValue, cachedValue);
}
@Test
public void testLoadNoExistingEntry() {
final String loadedValue = "loaded value";
final long ttlInMillis = 1000;
final int maxSize = 3;
TTLCache.EntryLoader loader = spy(TTLCache.EntryLoader.class);
when(loader.load(any())).thenReturn(loadedValue);
MsClock clock = mock(MsClock.class);
when(clock.timestampNano()).thenReturn((long) 0);
final TTLCache<String> cache = new TTLCache<String>(maxSize, ttlInMillis, loader);
cache.clock = clock;
assertEquals(0, cache.size());
assertEquals(maxSize, cache.getMaxSize());
String result = cache.load("k1");
verify(loader, times(1)).load("k1");
assertTrue(cache.size() == 1);
assertEquals(loadedValue, result);
// to verify result is in the cache, load one more time
// and expect the loader to not be called
String cachedValue = cache.load("k1");
verifyNoMoreInteractions(loader);
assertTrue(cache.size() == 1);
assertEquals(loadedValue, cachedValue);
}
@Test
public void testLoadNotExpired() {
final String loadedValue = "loaded value";
final long ttlInMillis = 1000;
final int maxSize = 3;
TTLCache.EntryLoader loader = spy(TTLCache.EntryLoader.class);
when(loader.load(any())).thenReturn(loadedValue);
MsClock clock = mock(MsClock.class);
final TTLCache<String> cache = new TTLCache<String>(maxSize, ttlInMillis, loader);
cache.clock = clock;
assertEquals(0, cache.size());
assertEquals(maxSize, cache.getMaxSize());
// when first creating the entry, time is 0
when(clock.timestampNano()).thenReturn((long) 0);
cache.load("k1");
assertTrue(cache.size() == 1);
verify(loader, times(1)).load("k1");
// on load, time is within TTL
when(clock.timestampNano()).thenReturn(TimeUnit.MILLISECONDS.toNanos(ttlInMillis));
String result = cache.load("k1");
verifyNoMoreInteractions(loader);
assertTrue(cache.size() == 1);
assertEquals(loadedValue, result);
}
@Test
public void testLoadInGrace() {
final String loadedValue = "loaded value";
final long ttlInMillis = 1000;
final int maxSize = 3;
TTLCache.EntryLoader loader = spy(TTLCache.EntryLoader.class);
when(loader.load(any())).thenReturn(loadedValue);
MsClock clock = mock(MsClock.class);
final TTLCache<String> cache = new TTLCache<String>(maxSize, ttlInMillis, loader);
cache.clock = clock;
assertEquals(0, cache.size());
assertEquals(maxSize, cache.getMaxSize());
// when first creating the entry, time is zero
when(clock.timestampNano()).thenReturn((long) 0);
cache.load("k1");
assertTrue(cache.size() == 1);
verify(loader, times(1)).load("k1");
// on load, time is past TTL but within the grace period
when(clock.timestampNano()).thenReturn(TimeUnit.MILLISECONDS.toNanos(ttlInMillis) + 1);
String result = cache.load("k1");
// Because this is tested in a single thread,
// this is expected to obtain the lock and load the new value
verify(loader, times(2)).load("k1");
verifyNoMoreInteractions(loader);
assertTrue(cache.size() == 1);
assertEquals(loadedValue, result);
}
@Test
public void testLoadExpired() {
final String loadedValue = "loaded value";
final long ttlInMillis = 1000;
final int maxSize = 3;
TTLCache.EntryLoader loader = spy(TTLCache.EntryLoader.class);
when(loader.load(any())).thenReturn(loadedValue);
MsClock clock = mock(MsClock.class);
final TTLCache<String> cache = new TTLCache<String>(maxSize, ttlInMillis, loader);
cache.clock = clock;
assertEquals(0, cache.size());
assertEquals(maxSize, cache.getMaxSize());
// when first creating the entry, time is zero
when(clock.timestampNano()).thenReturn((long) 0);
cache.load("k1");
assertTrue(cache.size() == 1);
verify(loader, times(1)).load("k1");
// on load, time is past TTL and grace period
when(clock.timestampNano())
.thenReturn(TimeUnit.MILLISECONDS.toNanos(ttlInMillis) + TTL_GRACE_IN_NANO + 1);
String result = cache.load("k1");
verify(loader, times(2)).load("k1");
verifyNoMoreInteractions(loader);
assertTrue(cache.size() == 1);
assertEquals(loadedValue, result);
}
@Test
public void testLoadExpiredEviction() {
final String loadedValue = "loaded value";
final long ttlInMillis = 1000;
final int maxSize = 3;
TTLCache.EntryLoader loader = spy(TTLCache.EntryLoader.class);
when(loader.load(any()))
.thenReturn(loadedValue)
.thenThrow(new IllegalStateException("This loader is mocked to throw a failure."));
MsClock clock = mock(MsClock.class);
final TTLCache<String> cache = new TTLCache<String>(maxSize, ttlInMillis, loader);
cache.clock = clock;
assertEquals(0, cache.size());
assertEquals(maxSize, cache.getMaxSize());
// when first creating the entry, time is zero
when(clock.timestampNano()).thenReturn((long) 0);
cache.load("k1");
verify(loader, times(1)).load("k1");
assertTrue(cache.size() == 1);
// on load, time is past TTL and grace period
when(clock.timestampNano())
.thenReturn(TimeUnit.MILLISECONDS.toNanos(ttlInMillis) + TTL_GRACE_IN_NANO + 1);
assertThrows(IllegalStateException.class, () -> cache.load("k1"));
verify(loader, times(2)).load("k1");
verifyNoMoreInteractions(loader);
assertTrue(cache.size() == 0);
}
@Test
public void testLoadWithFunction() {
final String loadedValue = "loaded value";
final String functionValue = "function value";
final long ttlInMillis = 1000;
final int maxSize = 3;
final Function<String, String> function = spy(Function.class);
when(function.apply(any())).thenReturn(functionValue);
TTLCache.EntryLoader loader = spy(TTLCache.EntryLoader.class);
when(loader.load(any()))
.thenReturn(loadedValue)
.thenThrow(new IllegalStateException("This loader is mocked to throw a failure."));
MsClock clock = mock(MsClock.class);
when(clock.timestampNano()).thenReturn((long) 0);
final TTLCache<String> cache = new TTLCache<String>(maxSize, ttlInMillis, loader);
cache.clock = clock;
assertEquals(0, cache.size());
assertEquals(maxSize, cache.getMaxSize());
String result = cache.load("k1", function);
verify(function, times(1)).apply("k1");
assertTrue(cache.size() == 1);
assertEquals(functionValue, result);
// to verify result is in the cache, load one more time
// and expect the loader to not be called
String cachedValue = cache.load("k1");
verifyNoMoreInteractions(function);
verifyNoMoreInteractions(loader);
assertTrue(cache.size() == 1);
assertEquals(functionValue, cachedValue);
}
@Test
public void testClear() {
final String loadedValue = "loaded value";
final long ttlInMillis = 1000;
final int maxSize = 3;
TTLCache.EntryLoader loader = spy(TTLCache.EntryLoader.class);
when(loader.load(any())).thenReturn(loadedValue);
final TTLCache<String> cache = new TTLCache<String>(maxSize, ttlInMillis, loader);
assertTrue(cache.size() == 0);
cache.load("k1");
cache.load("k2");
assertTrue(cache.size() == 2);
cache.clear();
assertTrue(cache.size() == 0);
}
@Test
public void testPut() {
final long ttlInMillis = 1000;
final int maxSize = 3;
TTLCache.EntryLoader loader = spy(TTLCache.EntryLoader.class);
MsClock clock = mock(MsClock.class);
when(clock.timestampNano()).thenReturn((long) 0);
final TTLCache<String> cache = new TTLCache<String>(maxSize, ttlInMillis, loader);
cache.clock = clock;
assertEquals(0, cache.size());
assertEquals(maxSize, cache.getMaxSize());
String oldValue = cache.put("k1", "v1");
assertNull(oldValue);
assertTrue(cache.size() == 1);
String oldValue2 = cache.put("k1", "v11");
assertEquals("v1", oldValue2);
assertTrue(cache.size() == 1);
}
@Test
public void testExpiredPut() {
final long ttlInMillis = 1000;
final int maxSize = 3;
TTLCache.EntryLoader loader = spy(TTLCache.EntryLoader.class);
MsClock clock = mock(MsClock.class);
when(clock.timestampNano()).thenReturn((long) 0);
final TTLCache<String> cache = new TTLCache<String>(maxSize, ttlInMillis, loader);
cache.clock = clock;
assertEquals(0, cache.size());
assertEquals(maxSize, cache.getMaxSize());
// First put is at time 0
String oldValue = cache.put("k1", "v1");
assertNull(oldValue);
assertTrue(cache.size() == 1);
// Second put is at time past TTL and grace period
when(clock.timestampNano())
.thenReturn(TimeUnit.MILLISECONDS.toNanos(ttlInMillis) + TTL_GRACE_IN_NANO + 1);
String oldValue2 = cache.put("k1", "v11");
assertNull(oldValue2);
assertTrue(cache.size() == 1);
}
@Test
public void testPutPastMaxSize() {
final String loadedValue = "loaded value";
final long ttlInMillis = 1000;
final int maxSize = 1;
TTLCache.EntryLoader loader = spy(TTLCache.EntryLoader.class);
when(loader.load(any())).thenReturn(loadedValue);
MsClock clock = mock(MsClock.class);
when(clock.timestampNano()).thenReturn((long) 0);
final TTLCache<String> cache = new TTLCache<String>(maxSize, ttlInMillis, loader);
cache.clock = clock;
assertEquals(0, cache.size());
assertEquals(maxSize, cache.getMaxSize());
cache.put("k1", "v1");
assertTrue(cache.size() == 1);
cache.put("k2", "v2");
assertTrue(cache.size() == 1);
// to verify put value is in the cache, load
// and expect the loader to not be called
String cachedValue = cache.load("k2");
verifyNoMoreInteractions(loader);
assertTrue(cache.size() == 1);
assertEquals(cachedValue, "v2");
}
}
| 5,025 |
0 | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/sdkv1/com/amazonaws/services/dynamodbv2/datamodeling | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/test/sdkv1/com/amazonaws/services/dynamodbv2/datamodeling/internal/ConcurrentTTLCacheTest.java | package com.amazonaws.services.dynamodbv2.datamodeling.internal;
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 edu.umd.cs.mtc.MultithreadedTestCase;
import edu.umd.cs.mtc.TestFramework;
import java.util.concurrent.TimeUnit;
import org.testng.annotations.Test;
/* Test specific thread interleavings with behaviors we care about in the
* TTLCache.
*/
public class ConcurrentTTLCacheTest {
private static final long TTL_GRACE_IN_NANO = TimeUnit.MILLISECONDS.toNanos(500);
private static final long ttlInMillis = 1000;
@Test
public void testGracePeriodCase() throws Throwable {
TestFramework.runOnce(new GracePeriodCase());
}
@Test
public void testExpiredCase() throws Throwable {
TestFramework.runOnce(new ExpiredCase());
}
@Test
public void testNewEntryCase() throws Throwable {
TestFramework.runOnce(new NewEntryCase());
}
@Test
public void testPutLoadCase() throws Throwable {
TestFramework.runOnce(new PutLoadCase());
}
// Ensure the loader is only called once if two threads attempt to load during the grace period
class GracePeriodCase extends MultithreadedTestCase {
TTLCache<String> cache;
TTLCache.EntryLoader loader;
MsClock clock = mock(MsClock.class);
@Override
public void initialize() {
loader =
spy(
new TTLCache.EntryLoader<String>() {
@Override
public String load(String entryKey) {
// Wait until thread2 finishes to complete load
waitForTick(2);
return "loadedValue";
}
});
when(clock.timestampNano()).thenReturn((long) 0);
cache = new TTLCache<>(3, ttlInMillis, loader);
cache.clock = clock;
// Put an initial value into the cache at time 0
cache.put("k1", "v1");
}
// The thread that first calls load in the grace period and acquires the lock
public void thread1() {
when(clock.timestampNano()).thenReturn(TimeUnit.MILLISECONDS.toNanos(ttlInMillis) + 1);
String loadedValue = cache.load("k1");
assertTick(2);
// Expect to get back the value calculated from load
assertEquals("loadedValue", loadedValue);
}
// The thread that calls load in the grace period after the lock has been acquired
public void thread2() {
// Wait until the first thread acquires the lock and starts load
waitForTick(1);
when(clock.timestampNano()).thenReturn(TimeUnit.MILLISECONDS.toNanos(ttlInMillis) + 1);
String loadedValue = cache.load("k1");
// Expect to get back the original value in the cache
assertEquals("v1", loadedValue);
}
@Override
public void finish() {
// Ensure the loader was only called once
verify(loader, times(1)).load("k1");
}
}
// Ensure the loader is only called once if two threads attempt to load an expired entry.
class ExpiredCase extends MultithreadedTestCase {
TTLCache<String> cache;
TTLCache.EntryLoader loader;
MsClock clock = mock(MsClock.class);
@Override
public void initialize() {
loader =
spy(
new TTLCache.EntryLoader<String>() {
@Override
public String load(String entryKey) {
// Wait until thread2 is waiting for the lock to complete load
waitForTick(2);
return "loadedValue";
}
});
when(clock.timestampNano()).thenReturn((long) 0);
cache = new TTLCache<>(3, ttlInMillis, loader);
cache.clock = clock;
// Put an initial value into the cache at time 0
cache.put("k1", "v1");
}
// The thread that first calls load after expiration
public void thread1() {
when(clock.timestampNano())
.thenReturn(TimeUnit.MILLISECONDS.toNanos(ttlInMillis) + TTL_GRACE_IN_NANO + 1);
String loadedValue = cache.load("k1");
assertTick(2);
// Expect to get back the value calculated from load
assertEquals("loadedValue", loadedValue);
}
// The thread that calls load after expiration,
// after the first thread calls load, but before
// the new value is put into the cache.
public void thread2() {
// Wait until the first thread acquires the lock and starts load
waitForTick(1);
when(clock.timestampNano())
.thenReturn(TimeUnit.MILLISECONDS.toNanos(ttlInMillis) + TTL_GRACE_IN_NANO + 1);
String loadedValue = cache.load("k1");
// Expect to get back the newly loaded value
assertEquals("loadedValue", loadedValue);
// assert that this thread only finishes once the first thread's load does
assertTick(2);
}
@Override
public void finish() {
// Ensure the loader was only called once
verify(loader, times(1)).load("k1");
}
}
// Ensure the loader is only called once if two threads attempt to load the same new entry.
class NewEntryCase extends MultithreadedTestCase {
TTLCache<String> cache;
TTLCache.EntryLoader loader;
MsClock clock = mock(MsClock.class);
@Override
public void initialize() {
loader =
spy(
new TTLCache.EntryLoader<String>() {
@Override
public String load(String entryKey) {
// Wait until thread2 is blocked to complete load
waitForTick(2);
return "loadedValue";
}
});
when(clock.timestampNano()).thenReturn((long) 0);
cache = new TTLCache<>(3, ttlInMillis, loader);
cache.clock = clock;
}
// The thread that first calls load
public void thread1() {
String loadedValue = cache.load("k1");
assertTick(2);
// Expect to get back the value calculated from load
assertEquals("loadedValue", loadedValue);
}
// The thread that calls load after the first thread calls load,
// but before the new value is put into the cache.
public void thread2() {
// Wait until the first thread acquires the lock and starts load
waitForTick(1);
String loadedValue = cache.load("k1");
// Expect to get back the newly loaded value
assertEquals("loadedValue", loadedValue);
// assert that this thread only finishes once the first thread's load does
assertTick(2);
}
@Override
public void finish() {
// Ensure the loader was only called once
verify(loader, times(1)).load("k1");
}
}
// Ensure the loader blocks put on load/put of the same new entry
class PutLoadCase extends MultithreadedTestCase {
TTLCache<String> cache;
TTLCache.EntryLoader loader;
MsClock clock = mock(MsClock.class);
@Override
public void initialize() {
loader =
spy(
new TTLCache.EntryLoader<String>() {
@Override
public String load(String entryKey) {
// Wait until the put blocks to complete load
waitForTick(2);
return "loadedValue";
}
});
when(clock.timestampNano()).thenReturn((long) 0);
cache = new TTLCache<>(3, ttlInMillis, loader);
cache.clock = clock;
}
// The thread that first calls load
public void thread1() {
String loadedValue = cache.load("k1");
// Expect to get back the value calculated from load
assertEquals("loadedValue", loadedValue);
verify(loader, times(1)).load("k1");
}
// The thread that calls put during the first thread's load
public void thread2() {
// Wait until the first thread is loading
waitForTick(1);
String previousValue = cache.put("k1", "v1");
// Expect to get back the value loaded into the cache by thread1
assertEquals("loadedValue", previousValue);
// assert that this thread was blocked by the first thread
assertTick(2);
}
}
}
| 5,026 |
0 | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/main/java/software/amazon/cryptography/dbencryptionsdk/structuredencryption | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/main/java/software/amazon/cryptography/dbencryptionsdk/structuredencryption/internaldafny/__default.java | package software.amazon.cryptography.dbencryptionsdk.structuredencryption.internaldafny;
public class __default extends software.amazon.cryptography.dbencryptionsdk.structuredencryption.internaldafny._ExternBase___default {
}
| 5,027 |
0 | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/main/java/software/amazon/cryptography/dbencryptionsdk/structuredencryption/internaldafny | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/main/java/software/amazon/cryptography/dbencryptionsdk/structuredencryption/internaldafny/types/__default.java | package software.amazon.cryptography.dbencryptionsdk.structuredencryption.internaldafny.types;
public class __default extends software.amazon.cryptography.dbencryptionsdk.structuredencryption.internaldafny.types._ExternBase___default{
}
| 5,028 |
0 | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/main/java/software/amazon/cryptography/dbencryptionsdk | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/main/java/software/amazon/cryptography/dbencryptionsdk/dynamodb/DynamoDbEncryptionExecutionAttribute.java | package software.amazon.cryptography.dbencryptionsdk.dynamodb;
import software.amazon.awssdk.core.SdkRequest;
import software.amazon.awssdk.core.interceptor.ExecutionAttribute;
public class DynamoDbEncryptionExecutionAttribute {
static final ExecutionAttribute<SdkRequest> ORIGINAL_REQUEST = new ExecutionAttribute<SdkRequest>("OriginalRequest");
}
| 5,029 |
0 | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/main/java/software/amazon/cryptography/dbencryptionsdk | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/main/java/software/amazon/cryptography/dbencryptionsdk/dynamodb/DynamoDbEncryptionInterceptor.java | package software.amazon.cryptography.dbencryptionsdk.dynamodb;
import software.amazon.awssdk.awscore.AwsRequest;
import software.amazon.awssdk.awscore.AwsRequestOverrideConfiguration;
import software.amazon.awssdk.core.ClientType;
import software.amazon.awssdk.core.interceptor.*;
import software.amazon.awssdk.core.SdkRequest;
import software.amazon.awssdk.core.SdkResponse;
import software.amazon.awssdk.services.dynamodb.model.*;
import software.amazon.cryptography.dbencryptionsdk.dynamodb.transforms.DynamoDbEncryptionTransforms;
import software.amazon.cryptography.dbencryptionsdk.dynamodb.transforms.model.*;
import software.amazon.cryptography.dbencryptionsdk.dynamodb.model.*;
import java.util.Objects;
import java.util.Optional;
import static software.amazon.cryptography.dbencryptionsdk.dynamodb.DynamoDbEncryptionExecutionAttribute.ORIGINAL_REQUEST;
import static software.amazon.cryptography.dbencryptionsdk.dynamodb.SupportedOperations.SUPPORTED_OPERATION_NAMES;
/**
* Implementation of {@link ExecutionInterceptor} that enables client side encryption with DynamoDb.
*/
public class DynamoDbEncryptionInterceptor implements ExecutionInterceptor {
private final DynamoDbTablesEncryptionConfig config;
private DynamoDbEncryptionTransforms transformer;
// This value is protected in DefaultDynamoDbBaseClientBuilder,
// so hardcode here. We do not expect it to change.
static final String DDB_NAME = "DynamoDb";
protected DynamoDbEncryptionInterceptor(BuilderImpl builder) {
this.config = builder.config();
this.transformer = DynamoDbEncryptionTransforms.builder()
.DynamoDbTablesEncryptionConfig(config)
.build();
}
public DynamoDbTablesEncryptionConfig config() {
return this.config;
}
@Override
public SdkRequest modifyRequest(Context.ModifyRequest context, ExecutionAttributes executionAttributes) {
SdkRequest originalRequest = context.request();
// Only transform DDB requests. Otherwise, throw an error.
if (!executionAttributes.getAttribute(SdkExecutionAttribute.SERVICE_NAME).equals(DDB_NAME)) {
throw DynamoDbEncryptionTransformsException.builder()
.message("DynamoDbEncryptionInterceptor does not support use with services other than DynamoDb.")
.build();
}
// Throw an error if this is not a Sync client.
if (!executionAttributes.getAttribute(SdkExecutionAttribute.CLIENT_TYPE).equals(ClientType.SYNC)) {
throw DynamoDbEncryptionTransformsException.builder()
.message("DynamoDbEncryptionInterceptor does not support use with the Async client.")
.build();
}
// Store original request so it can be used when intercepting the response
executionAttributes.putAttribute(ORIGINAL_REQUEST, originalRequest);
String operationName = executionAttributes.getAttribute(SdkExecutionAttribute.OPERATION_NAME);
// Ensure we are dealing with a known operation. Otherwise, throw an error.
checkSupportedOperation(operationName);
SdkRequest outgoingRequest;
switch(operationName) {
case "BatchExecuteStatement": {
BatchExecuteStatementRequest transformedRequest = transformer.BatchExecuteStatementInputTransform(
BatchExecuteStatementInputTransformInput.builder()
.sdkInput((BatchExecuteStatementRequest) originalRequest)
.build()).transformedInput();
outgoingRequest = copyOverrideConfig((BatchExecuteStatementRequest) originalRequest, transformedRequest);
break;
} case "BatchGetItem": {
BatchGetItemRequest transformedRequest = transformer.BatchGetItemInputTransform(
BatchGetItemInputTransformInput.builder()
.sdkInput((BatchGetItemRequest) originalRequest)
.build()).transformedInput();
outgoingRequest = copyOverrideConfig((BatchGetItemRequest) originalRequest, transformedRequest);
break;
} case "BatchWriteItem": {
BatchWriteItemRequest transformedRequest = transformer.BatchWriteItemInputTransform(
BatchWriteItemInputTransformInput.builder()
.sdkInput((BatchWriteItemRequest) originalRequest)
.build()).transformedInput();
outgoingRequest = copyOverrideConfig((BatchWriteItemRequest) originalRequest, transformedRequest);
break;
} case "DeleteItem": {
DeleteItemRequest transformedRequest = transformer.DeleteItemInputTransform(
DeleteItemInputTransformInput.builder()
.sdkInput((DeleteItemRequest) originalRequest)
.build()).transformedInput();
outgoingRequest = copyOverrideConfig((DeleteItemRequest) originalRequest, transformedRequest);
break;
} case "ExecuteStatement": {
ExecuteStatementRequest transformedRequest = transformer.ExecuteStatementInputTransform(
ExecuteStatementInputTransformInput.builder()
.sdkInput((ExecuteStatementRequest) originalRequest)
.build()).transformedInput();
outgoingRequest = copyOverrideConfig((ExecuteStatementRequest) originalRequest, transformedRequest);
break;
} case "ExecuteTransaction": {
ExecuteTransactionRequest transformedRequest = transformer.ExecuteTransactionInputTransform(
ExecuteTransactionInputTransformInput.builder()
.sdkInput((ExecuteTransactionRequest) originalRequest)
.build()).transformedInput();
outgoingRequest = copyOverrideConfig((ExecuteTransactionRequest) originalRequest, transformedRequest);
break;
} case "GetItem": {
GetItemRequest transformedRequest = transformer.GetItemInputTransform(
GetItemInputTransformInput.builder()
.sdkInput((GetItemRequest) originalRequest)
.build()).transformedInput();
outgoingRequest = copyOverrideConfig((GetItemRequest) originalRequest, transformedRequest);
break;
} case "PutItem": {
PutItemRequest transformedRequest = transformer.PutItemInputTransform(
PutItemInputTransformInput.builder()
.sdkInput((PutItemRequest) originalRequest)
.build()).transformedInput();
outgoingRequest = copyOverrideConfig((PutItemRequest) originalRequest, transformedRequest);
break;
} case "Query": {
QueryRequest queryRequest = (QueryRequest) originalRequest;
QueryRequest transformedRequest = transformer.QueryInputTransform(
QueryInputTransformInput.builder()
.sdkInput(queryRequest)
.build()).transformedInput();
// Our current Java->Dafny conversion squashes empty maps into the "None" type.
// In order to avoid gray failures for invalid `exclusiveStartKey`,
// and because our transforms do not act on or modify this value currently,
// copy over the original `exclusiveStartKey`
// so that the server can correctly reject it as invalid if it is empty.
transformedRequest = transformedRequest.toBuilder()
.exclusiveStartKey(queryRequest.exclusiveStartKey())
.build();
outgoingRequest = copyOverrideConfig(queryRequest, transformedRequest);
break;
} case "Scan": {
ScanRequest scanRequest = (ScanRequest) originalRequest;
ScanRequest transformedRequest = transformer.ScanInputTransform(
ScanInputTransformInput.builder()
.sdkInput(scanRequest)
.build()).transformedInput();
// Our current Java->Dafny conversion squashes empty maps into the "None" type.
// In order to avoid gray failures for invalid `exclusiveStartKey`,
// and because our transforms do not act on or modify this value currently,
// copy over the original `exclusiveStartKey`
// so that the server can correctly reject it as invalid if it is empty.
transformedRequest = transformedRequest.toBuilder()
.exclusiveStartKey(scanRequest.exclusiveStartKey())
.build();
outgoingRequest = copyOverrideConfig(scanRequest, transformedRequest);
break;
} case "TransactGetItems": {
TransactGetItemsRequest transformedRequest = transformer.TransactGetItemsInputTransform(
TransactGetItemsInputTransformInput.builder()
.sdkInput((TransactGetItemsRequest) originalRequest)
.build()).transformedInput();
outgoingRequest = copyOverrideConfig((TransactGetItemsRequest) originalRequest, transformedRequest);
break;
} case "TransactWriteItems": {
TransactWriteItemsRequest transformedRequest = transformer.TransactWriteItemsInputTransform(
TransactWriteItemsInputTransformInput.builder()
.sdkInput((TransactWriteItemsRequest) originalRequest)
.build()).transformedInput();
outgoingRequest = copyOverrideConfig((TransactWriteItemsRequest) originalRequest, transformedRequest);
break;
} case "UpdateItem": {
UpdateItemRequest transformedRequest = transformer.UpdateItemInputTransform(
UpdateItemInputTransformInput.builder()
.sdkInput((UpdateItemRequest) originalRequest)
.build()).transformedInput();
outgoingRequest = copyOverrideConfig((UpdateItemRequest) originalRequest, transformedRequest);
break;
} default: {
// Currently we only transform the above hardcoded set of APIs.
// Passthrough all others.
outgoingRequest = originalRequest;
break;
}
}
return outgoingRequest;
}
@Override
public SdkResponse modifyResponse(Context.ModifyResponse context, ExecutionAttributes executionAttributes) {
SdkResponse originalResponse = context.response();
// Only transform DDB requests. Otherwise, throw an error.
// It should be impossible to encounter this error. Belt and suspenders.
if (!executionAttributes.getAttribute(SdkExecutionAttribute.SERVICE_NAME).equals(DDB_NAME)) {
throw DynamoDbEncryptionTransformsException.builder()
.message("DynamoDbEncryptionInterceptor does not support use with services other than DynamoDb.")
.build();
}
// Throw an error if this is not a Sync client.
// It should be impossible to encounter this error. Belt and suspenders.
if (!executionAttributes.getAttribute(SdkExecutionAttribute.CLIENT_TYPE).equals(ClientType.SYNC)) {
throw DynamoDbEncryptionTransformsException.builder()
.message("DynamoDbEncryptionInterceptor does not support use with the Async client.")
.build();
}
SdkRequest originalRequest = executionAttributes.getAttribute(ORIGINAL_REQUEST);
String operationName = executionAttributes.getAttribute(SdkExecutionAttribute.OPERATION_NAME);
// Ensure we are dealing with a known operation. Otherwise, throw an error.
// It should be impossible to encounter this error. Belt and suspenders.
checkSupportedOperation(operationName);
SdkResponse outgoingResponse;
switch(operationName) {
case "BatchExecuteStatement": {
BatchExecuteStatementResponse transformedResponse = transformer.BatchExecuteStatementOutputTransform(
BatchExecuteStatementOutputTransformInput.builder()
.sdkOutput((BatchExecuteStatementResponse) originalResponse)
.originalInput((BatchExecuteStatementRequest) originalRequest)
.build()).transformedOutput();
outgoingResponse = transformedResponse.toBuilder()
.responseMetadata(((BatchExecuteStatementResponse) originalResponse).responseMetadata())
.sdkHttpResponse(originalResponse.sdkHttpResponse())
.build();
break;
} case "BatchGetItem": {
BatchGetItemResponse transformedResponse = transformer.BatchGetItemOutputTransform(
BatchGetItemOutputTransformInput.builder()
.sdkOutput((BatchGetItemResponse) originalResponse)
.originalInput((BatchGetItemRequest) originalRequest)
.build()).transformedOutput();
outgoingResponse = transformedResponse.toBuilder()
.responseMetadata(((BatchGetItemResponse) originalResponse).responseMetadata())
.sdkHttpResponse(originalResponse.sdkHttpResponse())
.build();
break;
} case "BatchWriteItem": {
BatchWriteItemResponse transformedResponse = transformer.BatchWriteItemOutputTransform(
BatchWriteItemOutputTransformInput.builder()
.sdkOutput((BatchWriteItemResponse) originalResponse)
.originalInput((BatchWriteItemRequest) originalRequest)
.build()).transformedOutput();
outgoingResponse = transformedResponse.toBuilder()
.responseMetadata(((BatchWriteItemResponse) originalResponse).responseMetadata())
.sdkHttpResponse(originalResponse.sdkHttpResponse())
.build();
break;
} case "ExecuteStatement": {
ExecuteStatementResponse transformedResponse = transformer.ExecuteStatementOutputTransform(
ExecuteStatementOutputTransformInput.builder()
.sdkOutput((ExecuteStatementResponse) originalResponse)
.originalInput((ExecuteStatementRequest) originalRequest)
.build()).transformedOutput();
outgoingResponse = transformedResponse.toBuilder()
.responseMetadata(((ExecuteStatementResponse) originalResponse).responseMetadata())
.sdkHttpResponse(originalResponse.sdkHttpResponse())
.build();
break;
} case "ExecuteTransaction": {
ExecuteTransactionResponse transformedResponse = transformer.ExecuteTransactionOutputTransform(
ExecuteTransactionOutputTransformInput.builder()
.sdkOutput((ExecuteTransactionResponse) originalResponse)
.originalInput((ExecuteTransactionRequest) originalRequest)
.build()).transformedOutput();
outgoingResponse = transformedResponse.toBuilder()
.responseMetadata(((ExecuteTransactionResponse) originalResponse).responseMetadata())
.sdkHttpResponse(originalResponse.sdkHttpResponse())
.build();
break;
} case "GetItem": {
GetItemResponse transformedResponse = transformer.GetItemOutputTransform(
GetItemOutputTransformInput.builder()
.sdkOutput((GetItemResponse) originalResponse)
.originalInput((GetItemRequest) originalRequest)
.build()).transformedOutput();
outgoingResponse = transformedResponse.toBuilder()
.responseMetadata(((GetItemResponse) originalResponse).responseMetadata())
.sdkHttpResponse(originalResponse.sdkHttpResponse())
.build();
break;
} case "PutItem": {
PutItemResponse transformedResponse = transformer.PutItemOutputTransform(
PutItemOutputTransformInput.builder()
.sdkOutput((PutItemResponse) originalResponse)
.originalInput((PutItemRequest) originalRequest)
.build()).transformedOutput();
outgoingResponse = transformedResponse.toBuilder()
.responseMetadata(((PutItemResponse) originalResponse).responseMetadata())
.sdkHttpResponse(originalResponse.sdkHttpResponse())
.build();
break;
} case "Query": {
QueryResponse transformedResponse = transformer.QueryOutputTransform(
QueryOutputTransformInput.builder()
.sdkOutput((QueryResponse) originalResponse)
.originalInput((QueryRequest) originalRequest)
.build()).transformedOutput();
outgoingResponse = transformedResponse.toBuilder()
.responseMetadata(((QueryResponse) originalResponse).responseMetadata())
.sdkHttpResponse(originalResponse.sdkHttpResponse())
.build();
break;
} case "Scan": {
ScanResponse transformedResponse = transformer.ScanOutputTransform(
ScanOutputTransformInput.builder()
.sdkOutput((ScanResponse) originalResponse)
.originalInput((ScanRequest) originalRequest)
.build()).transformedOutput();
outgoingResponse = transformedResponse.toBuilder()
.responseMetadata(((ScanResponse) originalResponse).responseMetadata())
.sdkHttpResponse(originalResponse.sdkHttpResponse())
.build();
break;
} case "TransactGetItems": {
TransactGetItemsResponse transformedResponse = transformer.TransactGetItemsOutputTransform(
TransactGetItemsOutputTransformInput.builder()
.sdkOutput((TransactGetItemsResponse) originalResponse)
.originalInput((TransactGetItemsRequest) originalRequest)
.build()).transformedOutput();
outgoingResponse = transformedResponse.toBuilder()
.responseMetadata(((TransactGetItemsResponse) originalResponse).responseMetadata())
.sdkHttpResponse(originalResponse.sdkHttpResponse())
.build();
break;
} case "TransactWriteItems": {
TransactWriteItemsResponse transformedResponse = transformer.TransactWriteItemsOutputTransform(
TransactWriteItemsOutputTransformInput.builder()
.sdkOutput((TransactWriteItemsResponse) originalResponse)
.originalInput((TransactWriteItemsRequest) originalRequest)
.build()).transformedOutput();
outgoingResponse = transformedResponse.toBuilder()
.responseMetadata(((TransactWriteItemsResponse) originalResponse).responseMetadata())
.sdkHttpResponse(originalResponse.sdkHttpResponse())
.build();
break;
} case "UpdateItem": {
UpdateItemResponse transformedResponse = transformer.UpdateItemOutputTransform(
UpdateItemOutputTransformInput.builder()
.sdkOutput((UpdateItemResponse) originalResponse)
.originalInput((UpdateItemRequest) originalRequest)
.build()).transformedOutput();
outgoingResponse = transformedResponse.toBuilder()
.responseMetadata(((UpdateItemResponse) originalResponse).responseMetadata())
.sdkHttpResponse(originalResponse.sdkHttpResponse())
.build();
break;
} default: {
// Currently we only transform the above hardcoded set of APIs.
// Passthrough all others.
outgoingResponse = originalResponse;
break;
}
}
return outgoingResponse;
}
private void checkSupportedOperation(String operationName) {
if (!SUPPORTED_OPERATION_NAMES.contains(operationName)) {
throw DynamoDbEncryptionTransformsException.builder()
.message(String.format("DynamoDbEncryptionInterceptor does not support use with unrecognized operation: %s", operationName))
.build();
}
}
// We currently assume that the OverrideConfig is the only non-smithy modelled information that we need to preserve
private AwsRequest copyOverrideConfig(AwsRequest original, AwsRequest transformed) {
Optional<AwsRequestOverrideConfiguration> config = original.overrideConfiguration();
if (!config.isPresent()) {
// If there is no config to copy over, this is a no-op
return transformed;
}
return transformed.toBuilder()
.overrideConfiguration(config.get())
.build();
}
public Builder toBuilder() {
return new BuilderImpl(this);
}
public static Builder builder() {
return new BuilderImpl();
}
public interface Builder {
Builder config(DynamoDbTablesEncryptionConfig config);
DynamoDbTablesEncryptionConfig config();
DynamoDbEncryptionInterceptor build();
}
static class BuilderImpl implements Builder {
protected DynamoDbTablesEncryptionConfig config;
protected BuilderImpl() {
}
protected BuilderImpl(DynamoDbEncryptionInterceptor model) {
this.config = model.config();
}
public Builder config(DynamoDbTablesEncryptionConfig config) {
this.config = config;
return this;
}
public DynamoDbTablesEncryptionConfig config() {
return this.config;
}
public DynamoDbEncryptionInterceptor build() {
if (Objects.isNull(this.config())) {
throw DynamoDbEncryptionTransformsException.builder()
.message("Missing value for required field `config`")
.build();
}
return new DynamoDbEncryptionInterceptor(this);
}
}
}
| 5,030 |
0 | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/main/java/software/amazon/cryptography/dbencryptionsdk | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/main/java/software/amazon/cryptography/dbencryptionsdk/dynamodb/SupportedOperations.java | package software.amazon.cryptography.dbencryptionsdk.dynamodb;
import java.util.Arrays;
import java.util.List;
// In order to ensure the Encryption Interceptor remains "hard to misuse",
// we must always fail in the case that we encounter an operation we don't
// recognize, which means keeping track of which operations we do support use with.
// Otherwise, it may be possible in the future for a new DDB
// operation to have surprising behavior when used with the interceptor.
public class SupportedOperations {
public static List<String> SUPPORTED_OPERATION_NAMES = Arrays.asList(
"BatchExecuteStatement",
"BatchGetItem",
"BatchWriteItem",
"CreateBackup",
"CreateGlobalTable",
"CreateTable",
"DeleteBackup",
"DeleteItem",
"DeleteTable",
"DescribeBackup",
"DescribeContinuousBackups",
"DescribeContributorInsights",
"DescribeEndpoints",
"DescribeExport",
"DescribeGlobalTable",
"DescribeGlobalTableSettings",
"DescribeImport",
"DescribeKinesisStreamingDestination",
"DescribeLimits",
"DescribeTable",
"DescribeTableReplicaAutoScaling",
"DescribeTimeToLive",
"DisableKinesisStreamingDestination",
"EnableKinesisStreamingDestination",
"ExecuteStatement",
"ExportTableToPointInTime",
"ExecuteTransaction",
"GetItem",
"ImportTable",
"ListBackups",
"ListContributorInsights",
"ListExports",
"ListGlobalTables",
"ListImports",
"ListTables",
"ListTagsOfResource",
"PutItem",
"Query",
"RestoreTableFromBackup",
"RestoreTableToPointInTime",
"Scan",
"TagResource",
"TransactGetItems",
"TransactWriteItems",
"UntagResource",
"UpdateContinuousBackups",
"UpdateContributorInsights",
"UpdateGlobalTable",
"UpdateGlobalTableSettings",
"UpdateItem",
"UpdateTable",
"UpdateTableReplicaAutoScaling",
"UpdateTimeToLive"
);
}
| 5,031 |
0 | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/main/java/software/amazon/cryptography/dbencryptionsdk/dynamodb | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/main/java/software/amazon/cryptography/dbencryptionsdk/dynamodb/enhancedclient/DynamoDbEnhancedTableEncryptionConfig.java | package software.amazon.cryptography.dbencryptionsdk.dynamodb.enhancedclient;
import java.util.List;
import java.util.Objects;
import software.amazon.cryptography.dbencryptionsdk.dynamodb.model.LegacyOverride;
import software.amazon.cryptography.dbencryptionsdk.dynamodb.model.PlaintextOverride;
import software.amazon.cryptography.materialproviders.IKeyring;
import software.amazon.awssdk.enhanced.dynamodb.TableSchema;
import software.amazon.cryptography.materialproviders.CryptographicMaterialsManager;
import software.amazon.cryptography.materialproviders.ICryptographicMaterialsManager;
import software.amazon.cryptography.materialproviders.Keyring;
import software.amazon.cryptography.materialproviders.model.DBEAlgorithmSuiteId;
public class DynamoDbEnhancedTableEncryptionConfig {
private final String logicalTableName;
private final TableSchema<?> schemaOnEncrypt;
private final List<String> allowedUnsignedAttributes;
private final String allowedUnsignedAttributePrefix;
private final Keyring keyring;
private final CryptographicMaterialsManager cmm;
private final LegacyOverride legacyOverride;
private final PlaintextOverride plaintextOverride;
private final DBEAlgorithmSuiteId algorithmSuiteId;
protected DynamoDbEnhancedTableEncryptionConfig(BuilderImpl builder) {
this.logicalTableName = builder.logicalTableName();
this.schemaOnEncrypt = builder.schemaOnEncrypt();
this.allowedUnsignedAttributes = builder.allowedUnsignedAttributes();
this.allowedUnsignedAttributePrefix = builder.allowedUnsignedAttributePrefix();
this.keyring = builder.keyring();
this.cmm = builder.cmm();
this.legacyOverride = builder.legacyOverride();
this.plaintextOverride = builder.plaintextOverride();
this.algorithmSuiteId = builder.algorithmSuiteId();
}
public String logicalTableName() { return this.logicalTableName; }
public TableSchema<?> schemaOnEncrypt() {
return this.schemaOnEncrypt;
}
public List<String> allowedUnsignedAttributes() {
return this.allowedUnsignedAttributes;
}
public String allowedUnsignedAttributePrefix() {
return this.allowedUnsignedAttributePrefix;
}
public Keyring keyring() {
return this.keyring;
}
public CryptographicMaterialsManager cmm() {
return this.cmm;
}
public LegacyOverride legacyOverride() {
return this.legacyOverride;
}
public PlaintextOverride plaintextOverride() {
return this.plaintextOverride;
}
public DBEAlgorithmSuiteId algorithmSuiteId() {
return this.algorithmSuiteId;
}
public Builder toBuilder() {
return new BuilderImpl(this);
}
public static Builder builder() {
return new BuilderImpl();
}
public interface Builder {
String logicalTableName();
Builder logicalTableName(String logicalTableName);
Builder schemaOnEncrypt(TableSchema<?> schemaOnEncrypt);
TableSchema<?> schemaOnEncrypt();
Builder allowedUnsignedAttributes(List<String> allowedUnsignedAttributes);
List<String> allowedUnsignedAttributes();
Builder allowedUnsignedAttributePrefix(String allowedUnsignedAttributePrefix);
String allowedUnsignedAttributePrefix();
<I extends IKeyring> Builder keyring(I keyring);
<I extends ICryptographicMaterialsManager> Builder cmm(I cmm);
Builder legacyOverride(LegacyOverride legacyOverride);
LegacyOverride legacyOverride();
Builder plaintextOverride(PlaintextOverride plaintextOverride);
PlaintextOverride plaintextOverride();
Builder algorithmSuiteId(DBEAlgorithmSuiteId algorithmSuiteId);
DBEAlgorithmSuiteId algorithmSuiteId();
DynamoDbEnhancedTableEncryptionConfig build();
}
protected static class BuilderImpl implements Builder {
protected String logicalTableName;
protected TableSchema<?> schemaOnEncrypt;
protected List<String> allowedUnsignedAttributes;
protected String allowedUnsignedAttributePrefix;
protected Keyring keyring;
protected CryptographicMaterialsManager cmm;
protected LegacyOverride legacyOverride;
protected PlaintextOverride plaintextOverride;
protected DBEAlgorithmSuiteId algorithmSuiteId;
protected BuilderImpl() {
}
protected BuilderImpl(DynamoDbEnhancedTableEncryptionConfig model) {
this.logicalTableName = model.logicalTableName();
this.schemaOnEncrypt = model.schemaOnEncrypt();
this.allowedUnsignedAttributes = model.allowedUnsignedAttributes();
this.allowedUnsignedAttributePrefix = model.allowedUnsignedAttributePrefix();
this.keyring = model.keyring();
this.cmm = model.cmm();
this.legacyOverride = model.legacyOverride();
this.plaintextOverride = model.plaintextOverride();
this.algorithmSuiteId = model.algorithmSuiteId();
}
public Builder logicalTableName(String logicalTableName) {
this.logicalTableName = logicalTableName;
return this;
}
public String logicalTableName() { return this.logicalTableName; }
public Builder schemaOnEncrypt(TableSchema<?> schemaOnEncrypt) {
this.schemaOnEncrypt = schemaOnEncrypt;
return this;
}
public TableSchema<?> schemaOnEncrypt() {
return this.schemaOnEncrypt;
}
public Builder allowedUnsignedAttributes(List<String> allowedUnsignedAttributes) {
this.allowedUnsignedAttributes = allowedUnsignedAttributes;
return this;
}
public List<String> allowedUnsignedAttributes() {
return this.allowedUnsignedAttributes;
}
public Builder allowedUnsignedAttributePrefix(
String allowedUnsignedAttributePrefix) {
this.allowedUnsignedAttributePrefix = allowedUnsignedAttributePrefix;
return this;
}
public String allowedUnsignedAttributePrefix() {
return this.allowedUnsignedAttributePrefix;
}
public <I extends IKeyring> Builder keyring(I keyring) {
this.keyring = Keyring.wrap(keyring);
return this;
}
public Keyring keyring() {
return this.keyring;
}
public <I extends ICryptographicMaterialsManager> Builder cmm(I cmm) {
this.cmm = CryptographicMaterialsManager.wrap(cmm);
return this;
}
public CryptographicMaterialsManager cmm() {
return this.cmm;
}
public Builder legacyOverride(LegacyOverride legacyOverride) {
this.legacyOverride = legacyOverride;
return this;
}
public LegacyOverride legacyOverride() {
return this.legacyOverride;
}
public Builder plaintextOverride(PlaintextOverride plaintextOverride) {
this.plaintextOverride = plaintextOverride;
return this;
}
public PlaintextOverride plaintextOverride() {
return this.plaintextOverride;
}
public Builder algorithmSuiteId(DBEAlgorithmSuiteId algorithmSuiteId) {
this.algorithmSuiteId = algorithmSuiteId;
return this;
}
public DBEAlgorithmSuiteId algorithmSuiteId() {
return this.algorithmSuiteId;
}
public DynamoDbEnhancedTableEncryptionConfig build() {
if (Objects.isNull(this.schemaOnEncrypt())) {
throw new IllegalArgumentException("Missing value for required field `schemaOnEncrypt`");
}
return new DynamoDbEnhancedTableEncryptionConfig(this);
}
}
}
| 5,032 |
0 | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/main/java/software/amazon/cryptography/dbencryptionsdk/dynamodb | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/main/java/software/amazon/cryptography/dbencryptionsdk/dynamodb/enhancedclient/DynamoDbEncryptionDoNothing.java | package software.amazon.cryptography.dbencryptionsdk.dynamodb.enhancedclient;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.BeanTableSchemaAttributeTag;
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@BeanTableSchemaAttributeTag(EncryptionAttributeTags.class)
public @interface DynamoDbEncryptionDoNothing {
}
| 5,033 |
0 | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/main/java/software/amazon/cryptography/dbencryptionsdk/dynamodb | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/main/java/software/amazon/cryptography/dbencryptionsdk/dynamodb/enhancedclient/CreateDynamoDbEncryptionInterceptorInput.java | package software.amazon.cryptography.dbencryptionsdk.dynamodb.enhancedclient;
import java.util.Map;
import java.util.Objects;
public class CreateDynamoDbEncryptionInterceptorInput {
private final Map<String, DynamoDbEnhancedTableEncryptionConfig> tableEncryptionConfigs;
protected CreateDynamoDbEncryptionInterceptorInput(BuilderImpl builder) {
this.tableEncryptionConfigs = builder.tableEncryptionConfigs();
}
public Map<String, DynamoDbEnhancedTableEncryptionConfig> tableEncryptionConfigs() {
return this.tableEncryptionConfigs;
}
public Builder toBuilder() {
return new BuilderImpl(this);
}
public static Builder builder() {
return new BuilderImpl();
}
public interface Builder {
Builder tableEncryptionConfigs(
Map<String, DynamoDbEnhancedTableEncryptionConfig> tableEncryptionConfigs);
Map<String, DynamoDbEnhancedTableEncryptionConfig> tableEncryptionConfigs();
CreateDynamoDbEncryptionInterceptorInput build();
}
static class BuilderImpl implements Builder {
protected Map<String, DynamoDbEnhancedTableEncryptionConfig> tableEncryptionConfigs;
protected BuilderImpl() {
}
protected BuilderImpl(CreateDynamoDbEncryptionInterceptorInput model) {
this.tableEncryptionConfigs = model.tableEncryptionConfigs();
}
public Builder tableEncryptionConfigs(
Map<String, DynamoDbEnhancedTableEncryptionConfig> tableEncryptionConfigs) {
this.tableEncryptionConfigs = tableEncryptionConfigs;
return this;
}
public Map<String, DynamoDbEnhancedTableEncryptionConfig> tableEncryptionConfigs() {
return this.tableEncryptionConfigs;
}
public CreateDynamoDbEncryptionInterceptorInput build() {
if (Objects.isNull(this.tableEncryptionConfigs())) {
throw new IllegalArgumentException("Missing value for required field `tableEncryptionConfigs`");
}
return new CreateDynamoDbEncryptionInterceptorInput(this);
}
}
}
| 5,034 |
0 | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/main/java/software/amazon/cryptography/dbencryptionsdk/dynamodb | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/main/java/software/amazon/cryptography/dbencryptionsdk/dynamodb/enhancedclient/DoNothingTag.java | package software.amazon.cryptography.dbencryptionsdk.dynamodb.enhancedclient;
import java.util.Collections;
import java.util.function.Consumer;
import software.amazon.awssdk.enhanced.dynamodb.AttributeValueType;
import software.amazon.awssdk.enhanced.dynamodb.mapper.StaticAttributeTag;
import software.amazon.awssdk.enhanced.dynamodb.mapper.StaticTableMetadata;
public class DoNothingTag implements StaticAttributeTag {
public static final String CUSTOM_DDB_ENCRYPTION_DO_NOTHING_PREFIX = "DynamoDbEncryption:DoNothing";
@Override
public Consumer<StaticTableMetadata.Builder> modifyMetadata(String attributeName, AttributeValueType attributeValueType) {
return metadata -> metadata
.addCustomMetadataObject(CUSTOM_DDB_ENCRYPTION_DO_NOTHING_PREFIX, Collections.singleton(attributeName));
}
}
| 5,035 |
0 | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/main/java/software/amazon/cryptography/dbencryptionsdk/dynamodb | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/main/java/software/amazon/cryptography/dbencryptionsdk/dynamodb/enhancedclient/DynamoDbEncryptionSignOnly.java | package software.amazon.cryptography.dbencryptionsdk.dynamodb.enhancedclient;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.BeanTableSchemaAttributeTag;
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@BeanTableSchemaAttributeTag(EncryptionAttributeTags.class)
public @interface DynamoDbEncryptionSignOnly {
}
| 5,036 |
0 | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/main/java/software/amazon/cryptography/dbencryptionsdk/dynamodb | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/main/java/software/amazon/cryptography/dbencryptionsdk/dynamodb/enhancedclient/EncryptionAttributeTags.java | package software.amazon.cryptography.dbencryptionsdk.dynamodb.enhancedclient;
import software.amazon.awssdk.enhanced.dynamodb.mapper.StaticAttributeTag;
public final class EncryptionAttributeTags {
private EncryptionAttributeTags() {
}
public static StaticAttributeTag attributeTagFor(DynamoDbEncryptionSignOnly annotation) {
return new SignOnlyTag();
}
public static StaticAttributeTag attributeTagFor(DynamoDbEncryptionDoNothing annotation) {
return new DoNothingTag();
}
}
| 5,037 |
0 | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/main/java/software/amazon/cryptography/dbencryptionsdk/dynamodb | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/main/java/software/amazon/cryptography/dbencryptionsdk/dynamodb/enhancedclient/DynamoDbEnhancedClientEncryption.java | package software.amazon.cryptography.dbencryptionsdk.dynamodb.enhancedclient;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import software.amazon.awssdk.enhanced.dynamodb.IndexMetadata;
import software.amazon.awssdk.enhanced.dynamodb.KeyAttributeMetadata;
import software.amazon.awssdk.enhanced.dynamodb.TableMetadata;
import software.amazon.awssdk.enhanced.dynamodb.AttributeConverter;
import software.amazon.awssdk.enhanced.dynamodb.TableSchema;
import software.amazon.cryptography.dbencryptionsdk.dynamodb.DynamoDbEncryptionInterceptor;
import software.amazon.cryptography.dbencryptionsdk.dynamodb.model.DynamoDbEncryptionException;
import software.amazon.cryptography.dbencryptionsdk.dynamodb.model.DynamoDbTablesEncryptionConfig;
import software.amazon.cryptography.dbencryptionsdk.dynamodb.model.DynamoDbTableEncryptionConfig;
import software.amazon.cryptography.dbencryptionsdk.structuredencryption.model.CryptoAction;
import static software.amazon.cryptography.dbencryptionsdk.dynamodb.enhancedclient.DoNothingTag.CUSTOM_DDB_ENCRYPTION_DO_NOTHING_PREFIX;
import static software.amazon.cryptography.dbencryptionsdk.dynamodb.enhancedclient.SignOnlyTag.CUSTOM_DDB_ENCRYPTION_SIGN_ONLY_PREFIX;
public class DynamoDbEnhancedClientEncryption {
public static DynamoDbEncryptionInterceptor CreateDynamoDbEncryptionInterceptor(
CreateDynamoDbEncryptionInterceptorInput input) {
Map<String, DynamoDbTableEncryptionConfig> tableConfigs = new HashMap<>();
input.tableEncryptionConfigs().forEach(
(name, config) -> tableConfigs.put(name, getTableConfig(config, name)));
return DynamoDbEncryptionInterceptor.builder()
.config(DynamoDbTablesEncryptionConfig.builder()
.tableEncryptionConfigs(tableConfigs)
.build())
.build();
}
private static Set<String> attributeNamesUsedInIndices(
final TableMetadata tableMetadata
) {
Set<String> allIndexAttributes = new HashSet<>();
tableMetadata.indices().stream()
.map(IndexMetadata::partitionKey)
.filter(Optional::isPresent)
.map(Optional::get)
.map(KeyAttributeMetadata::name)
.forEach(allIndexAttributes::add);
tableMetadata.indices().stream()
.map(IndexMetadata::sortKey)
.filter(Optional::isPresent)
.map(Optional::get)
.map(KeyAttributeMetadata::name)
.forEach(allIndexAttributes::add);
return allIndexAttributes;
}
private static DynamoDbTableEncryptionConfig getTableConfig(
final DynamoDbEnhancedTableEncryptionConfig configWithSchema,
final String tableName
) {
Map<String, CryptoAction> actions = new HashMap<>();
TableSchema<?> topTableSchema = configWithSchema.schemaOnEncrypt();
Set<String> signOnlyAttributes = getSignOnlyAttributes(topTableSchema);
Set<String> doNothingAttributes = getDoNothingAttributes(topTableSchema);
Set<String> keyAttributes = attributeNamesUsedInIndices(topTableSchema.tableMetadata());
if (!Collections.disjoint(keyAttributes, doNothingAttributes)) {
throw DynamoDbEncryptionException.builder()
.message(String.format(
"Cannot use @DynamoDbEncryptionDoNothing on primary key attributes. Found on Table Name: %s",
tableName))
.build();
} else if (!Collections.disjoint(signOnlyAttributes, doNothingAttributes)) {
throw DynamoDbEncryptionException.builder()
.message(String.format(
"Cannot use @DynamoDbEncryptionDoNothing and @DynamoDbEncryptionSignOnly on same attribute. Found on Table Name: %s",
tableName))
.build();
}
List<String> attributeNames = topTableSchema.attributeNames();
StringBuilder path = new StringBuilder();
path.append(tableName).append(".");
for (String attributeName : attributeNames) {
if (keyAttributes.contains(attributeName)) {
// key attributes are always SIGN_ONLY
actions.put(attributeName, CryptoAction.SIGN_ONLY);
} else if (signOnlyAttributes.contains(attributeName)) {
actions.put(attributeName, CryptoAction.SIGN_ONLY);
} else if (doNothingAttributes.contains(attributeName)) {
actions.put(attributeName, CryptoAction.DO_NOTHING);
} else {
// non-key attributes are ENCRYPT_AND_SIGN unless otherwise annotated
actions.put(attributeName, CryptoAction.ENCRYPT_AND_SIGN);
}
// Detect Encryption Flags that are Ignored b/c they are in a Nested Class
scanForIgnoredEncryptionTags(topTableSchema, attributeName, path);
}
DynamoDbTableEncryptionConfig.Builder builder = DynamoDbTableEncryptionConfig.builder();
String partitionName = topTableSchema.tableMetadata().primaryPartitionKey();
builder = builder.partitionKeyName(partitionName);
Optional<String> sortName = topTableSchema.tableMetadata().primarySortKey();
if (sortName.isPresent()) {
builder = builder.sortKeyName(sortName.get());
}
if (!Objects.isNull(configWithSchema.keyring())) {
builder = builder.keyring(configWithSchema.keyring());
}
if (!Objects.isNull(configWithSchema.cmm())) {
builder = builder.cmm(configWithSchema.cmm());
}
if (!Objects.isNull(configWithSchema.logicalTableName())) {
builder = builder.logicalTableName(configWithSchema.logicalTableName());
}
if (!Objects.isNull(configWithSchema.plaintextOverride())) {
builder = builder.plaintextOverride(configWithSchema.plaintextOverride());
}
return builder.allowedUnsignedAttributePrefix(configWithSchema.allowedUnsignedAttributePrefix())
.allowedUnsignedAttributes(configWithSchema.allowedUnsignedAttributes())
.attributeActionsOnEncrypt(actions)
.legacyOverride(configWithSchema.legacyOverride())
.build();
}
@SuppressWarnings("unchecked")
private static Set<String> getSignOnlyAttributes(TableSchema<?> tableSchema) {
return tableSchema.tableMetadata()
.customMetadataObject(CUSTOM_DDB_ENCRYPTION_SIGN_ONLY_PREFIX, Set.class)
.orElseGet(HashSet::new);
}
@SuppressWarnings("unchecked")
private static Set<String> getDoNothingAttributes(TableSchema<?> tableSchema) {
return tableSchema.tableMetadata()
.customMetadataObject(CUSTOM_DDB_ENCRYPTION_DO_NOTHING_PREFIX, Set.class)
.orElseGet(HashSet::new);
}
/**
* Detects DynamoDB Encryption Tags in Nested Enhanced Types.<p>
* DynamoDB Encryption Tags in Nested Classes are IGNORED by the
* Database Encryption SDK for DynamoDB.<p>
* As such, Detection of a nested DynamoDB Encryption Tag on a Nested Type
* triggers a Runtime Exception that MUST NOT BE ignored.<p>
* CAVEAT: Encryption Tags on fields of Nested Classes that are
* Flattened onto the top record are Respected.<p>
* The behavior of Flatten pushes the Attributes onto the top level record,
* making the "flattened sub-fields" equivalent to any other DynamoDB Attribute.<p>
* However, there still exists a possibility for IGNORED Encryption Tags,
* as any Encryption Tag on the field that will be "flattened" is ignored.<p>
* This method DOES NOT detect these "ignored-by-flattened" tags.
*/
private static void scanForIgnoredEncryptionTags(
final TableSchema<?> tableSchema,
final String attributeName,
final StringBuilder path
) {
AttributeConverter<?> attributeConverter = tableSchema.converterForAttribute(attributeName);
StringBuilder attributePath = new StringBuilder(path).append(attributeName).append(".");
if (
Objects.nonNull(attributeConverter) &&
Objects.nonNull(attributeConverter.type()) &&
attributeConverter.type().tableSchema().isPresent()
) {
TableSchema<?> subTableSchema = attributeConverter.type().tableSchema().get();
Set<String> signOnlyAttributes = getSignOnlyAttributes(subTableSchema);
if (signOnlyAttributes.size() > 0) {
throw DynamoDbEncryptionException.builder()
.message(String.format(
"Detected DynamoDbEncryption Tag %s on a nested attribute with Path %s. " +
"This is NOT Supported at this time!",
CUSTOM_DDB_ENCRYPTION_SIGN_ONLY_PREFIX,
attributePath.append(signOnlyAttributes.toArray()[0])))
.build();
}
Set<String> doNothingAttributes = getDoNothingAttributes(subTableSchema);
if (doNothingAttributes.size() > 0) {
throw DynamoDbEncryptionException.builder()
.message(String.format(
"Detected DynamoDbEncryption Tag %s on a nested attribute with Path %s. " +
"This is NOT Supported at this time!",
CUSTOM_DDB_ENCRYPTION_DO_NOTHING_PREFIX,
attributePath.append(doNothingAttributes.toArray()[0])))
.build();
}
List<String> subAttributeNames = subTableSchema.attributeNames();
for (String subAttributeName : subAttributeNames) {
scanForIgnoredEncryptionTags(subTableSchema, subAttributeName, attributePath);
}
}
}
}
| 5,038 |
0 | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/main/java/software/amazon/cryptography/dbencryptionsdk/dynamodb | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/main/java/software/amazon/cryptography/dbencryptionsdk/dynamodb/enhancedclient/SignOnlyTag.java | package software.amazon.cryptography.dbencryptionsdk.dynamodb.enhancedclient;
import java.util.Arrays;
import java.util.Collections;
import java.util.function.Consumer;
import software.amazon.awssdk.enhanced.dynamodb.AttributeValueType;
import software.amazon.awssdk.enhanced.dynamodb.mapper.StaticAttributeTag;
import software.amazon.awssdk.enhanced.dynamodb.mapper.StaticTableMetadata;
public class SignOnlyTag implements StaticAttributeTag {
public static final String CUSTOM_DDB_ENCRYPTION_SIGN_ONLY_PREFIX = "DynamoDbEncryption:SortOnly";
@Override
public Consumer<StaticTableMetadata.Builder> modifyMetadata(String attributeName, AttributeValueType attributeValueType) {
return metadata -> metadata
.addCustomMetadataObject(CUSTOM_DDB_ENCRYPTION_SIGN_ONLY_PREFIX, Collections.singleton(attributeName));
}
}
| 5,039 |
0 | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/main/java/software/amazon/cryptography/dbencryptionsdk/dynamodb | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/main/java/software/amazon/cryptography/dbencryptionsdk/dynamodb/internaldafny/__default.java | package software.amazon.cryptography.dbencryptionsdk.dynamodb.internaldafny;
public class __default extends software.amazon.cryptography.dbencryptionsdk.dynamodb.internaldafny._ExternBase___default {
}
| 5,040 |
0 | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/main/java/software/amazon/cryptography/dbencryptionsdk/dynamodb/internaldafny | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/main/java/software/amazon/cryptography/dbencryptionsdk/dynamodb/internaldafny/types/__default.java | package software.amazon.cryptography.dbencryptionsdk.dynamodb.internaldafny.types;
public class __default extends software.amazon.cryptography.dbencryptionsdk.dynamodb.internaldafny.types._ExternBase___default {
}
| 5,041 |
0 | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/main/java/software/amazon/cryptography/dbencryptionsdk/dynamodb/transforms | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/main/java/software/amazon/cryptography/dbencryptionsdk/dynamodb/transforms/internaldafny/__default.java | package software.amazon.cryptography.dbencryptionsdk.dynamodb.transforms.internaldafny;
public class __default extends software.amazon.cryptography.dbencryptionsdk.dynamodb.transforms.internaldafny._ExternBase___default {
}
| 5,042 |
0 | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/main/java/software/amazon/cryptography/dbencryptionsdk/dynamodb/itemencryptor | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/main/java/software/amazon/cryptography/dbencryptionsdk/dynamodb/itemencryptor/internaldafny/__default.java | package software.amazon.cryptography.dbencryptionsdk.dynamodb.itemencryptor.internaldafny;
public class __default extends software.amazon.cryptography.dbencryptionsdk.dynamodb.itemencryptor.internaldafny._ExternBase___default {
}
| 5,043 |
0 | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/main/java/software/amazon/cryptography/dbencryptionsdk/dynamodb/itemencryptor/internaldafny | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/main/java/software/amazon/cryptography/dbencryptionsdk/dynamodb/itemencryptor/internaldafny/legacy/InternalLegacyOverride.java | package software.amazon.cryptography.dbencryptionsdk.dynamodb.itemencryptor.internaldafny.legacy;
/**
* This file does *NOT* import a lot of things.
* This is because it is dealing with converting
* between different versions of the same name.
* The DynamoDbItemEncryptor module has Dafny and Java versions
* of the same type.
* This means that `EncryptItemOutput` for example
* needs to be disambiguated between the Dafny version and the Java version.
* In order to make it clearer at each call-site exactly what is happening
* the full import is used.
* IDEs tend to fight this so I'm sorry.
*/
import software.amazon.cryptography.dbencryptionsdk.structuredencryption.internaldafny.types.CryptoAction;
import software.amazon.cryptography.dbencryptionsdk.dynamodb.itemencryptor.internaldafny.types.Error;
import software.amazon.cryptography.dbencryptionsdk.dynamodb.internaldafny.types.LegacyPolicy;
import Wrappers_Compile.Option;
import dafny.DafnyMap;
import dafny.DafnySequence;
import Wrappers_Compile.Result;
import com.amazonaws.services.dynamodbv2.datamodeling.encryption.DynamoDBEncryptor;
import com.amazonaws.services.dynamodbv2.datamodeling.encryption.EncryptionContext;
import com.amazonaws.services.dynamodbv2.datamodeling.encryption.EncryptionFlags;
import dafny.TypeDescriptor;
import software.amazon.awssdk.core.SdkBytes;
import software.amazon.cryptography.dbencryptionsdk.dynamodb.ILegacyDynamoDbEncryptor;
import software.amazon.cryptography.dbencryptionsdk.dynamodb.itemencryptor.ToNative;
import java.util.*;
import java.util.function.BiConsumer;
import java.util.stream.Collectors;
public class InternalLegacyOverride {
private DynamoDBEncryptor encryptor;
private Map<String, Set<EncryptionFlags>> actions;
private EncryptionContext encryptionContext;
private LegacyPolicy _policy;
private DafnySequence<Character> materialDescriptionFieldName;
private DafnySequence<Character> signatureFieldName;
private InternalLegacyOverride(
DynamoDBEncryptor encryptor,
Map<String, Set<EncryptionFlags>> actions,
EncryptionContext encryptionContext,
LegacyPolicy policy
) {
this.encryptor = encryptor;
this.actions = actions;
this.encryptionContext = encryptionContext;
this._policy = policy;
// It is possible that these values
// have been customized by the customer.
this.materialDescriptionFieldName = software
.amazon
.smithy
.dafny
.conversion
.ToDafny
.Simple
.CharacterSequence(encryptor.getMaterialDescriptionFieldName());
this.signatureFieldName = software
.amazon
.smithy
.dafny
.conversion
.ToDafny
.Simple
.CharacterSequence(encryptor.getSignatureFieldName());
}
public static TypeDescriptor<InternalLegacyOverride> _typeDescriptor() {
return TypeDescriptor.referenceWithInitializer(InternalLegacyOverride.class, () -> null);
}
public Boolean IsLegacyInput(
software.amazon.cryptography.dbencryptionsdk.dynamodb.itemencryptor.internaldafny.types.DecryptItemInput input
) {
//= specification/dynamodb-encryption-client/decrypt-item.md#determining-legacy-items
//# An item MUST be determined to be encrypted under the legacy format if it contains
//# attributes for the material description and the signature.
return input.is_DecryptItemInput() &&
input._encryptedItem.contains(materialDescriptionFieldName) &&
input._encryptedItem.contains(signatureFieldName);
}
public LegacyPolicy policy() {
return _policy;
}
public Result<software.amazon.cryptography.dbencryptionsdk.dynamodb.itemencryptor.internaldafny.types.EncryptItemOutput, Error> EncryptItem(
software.amazon.cryptography.dbencryptionsdk.dynamodb.itemencryptor.internaldafny.types.EncryptItemInput input
) {
// Precondition: Policy MUST allow the caller to encrypt.
if (!_policy.is_FORCE__LEGACY__ENCRYPT__ALLOW__LEGACY__DECRYPT()) {
return createFailure("Legacy Policy does not support encrypt.");
}
try {
Map<String, software.amazon.awssdk.services.dynamodb.model.AttributeValue> plaintextItem = software
.amazon
.cryptography
.dbencryptionsdk
.dynamodb
.itemencryptor
.ToNative
.EncryptItemInput(input)
.plaintextItem();
final Map<String, com.amazonaws.services.dynamodbv2.model.AttributeValue> encryptedItem = encryptor
.encryptRecord(
V2MapToV1Map(plaintextItem),
actions,
encryptionContext
);
final software.amazon.cryptography.dbencryptionsdk.dynamodb.itemencryptor.model.EncryptItemOutput nativeOutput = software
.amazon
.cryptography
.dbencryptionsdk
.dynamodb
.itemencryptor
.model
.EncryptItemOutput
.builder()
.encryptedItem(V1MapToV2Map(encryptedItem))
.build();
final software.amazon.cryptography.dbencryptionsdk.dynamodb.itemencryptor.internaldafny.types.EncryptItemOutput dafnyOutput = software
.amazon
.cryptography
.dbencryptionsdk
.dynamodb
.itemencryptor
.ToDafny
.EncryptItemOutput(nativeOutput);
return Result.create_Success(dafnyOutput);
} catch (Exception ex) {
return Result.create_Failure(Error.create_Opaque(ex));
}
}
public Result<software.amazon.cryptography.dbencryptionsdk.dynamodb.itemencryptor.internaldafny.types.DecryptItemOutput, Error> DecryptItem(
software.amazon.cryptography.dbencryptionsdk.dynamodb.itemencryptor.internaldafny.types.DecryptItemInput input
) {
// Precondition: Policy MUST allow the caller to decrypt.
//= specification/dynamodb-encryption-client/decrypt-item.md#behavior
//# If a [Legacy Policy](./ddb-table-encryption-config.md#legacy-policy) of
//# `FORBID_LEGACY_ENCRYPT_FORBID_LEGACY_DECRYPT` is configured,
//# and the input item [is an item written in the legacy format](#determining-legacy-items),
//# this operation MUST fail.
if (!_policy.is_FORCE__LEGACY__ENCRYPT__ALLOW__LEGACY__DECRYPT() && !_policy.is_FORBID__LEGACY__ENCRYPT__ALLOW__LEGACY__DECRYPT()) {
return createFailure("Legacy Policy does not support decrypt.");
}
try {
Map<String, software.amazon.awssdk.services.dynamodb.model.AttributeValue> encryptedItem = software
.amazon
.cryptography
.dbencryptionsdk
.dynamodb
.itemencryptor
.ToNative
.DecryptItemInput(input)
.encryptedItem();
final Map<String, com.amazonaws.services.dynamodbv2.model.AttributeValue> plaintextItem = encryptor
.decryptRecord(
V2MapToV1Map(encryptedItem),
actions,
encryptionContext
);
final software.amazon.cryptography.dbencryptionsdk.dynamodb.itemencryptor.model.DecryptItemOutput nativeOutput = software
.amazon
.cryptography
.dbencryptionsdk
.dynamodb
.itemencryptor
.model
.DecryptItemOutput
.builder()
.plaintextItem(V1MapToV2Map(plaintextItem))
.build();
final software.amazon.cryptography.dbencryptionsdk.dynamodb.itemencryptor.internaldafny.types.DecryptItemOutput dafnyOutput = software
.amazon
.cryptography
.dbencryptionsdk
.dynamodb
.itemencryptor
.ToDafny
.DecryptItemOutput(nativeOutput);
return Result.create_Success(dafnyOutput);
} catch (Exception ex) {
return Result.create_Failure(Error.create_Opaque(ex));
}
}
public static Result<Option<InternalLegacyOverride>, Error> Build(
software.amazon.cryptography.dbencryptionsdk.dynamodb.itemencryptor.internaldafny.types.DynamoDbItemEncryptorConfig encryptorConfig
) {
// Check for early return (Postcondition): If there is no legacyOverride there is nothing to do.
if (encryptorConfig.dtor_legacyOverride().is_None()) {
return Result.create_Success(Option.create_None());
}
final software.amazon.cryptography.dbencryptionsdk.dynamodb.internaldafny.types.LegacyOverride legacyOverride = encryptorConfig
.dtor_legacyOverride()
.dtor_value();
final ILegacyDynamoDbEncryptor maybeEncryptor = software.amazon.cryptography.dbencryptionsdk.dynamodb.ToNative
.LegacyDynamoDbEncryptor(legacyOverride.dtor_encryptor());
// Precondition: The encryptor MUST be a DynamoDBEncryptor
if (!isDynamoDBEncryptor(maybeEncryptor)) {
return createFailure("Legacy encryptor is not supported");
}
// Preconditions: MUST be able to create valid encryption context
final Result<EncryptionContext, Error> maybeEncryptionContext = legacyEncryptionContext(encryptorConfig);
if (maybeEncryptionContext.is_Failure()) {
return Result.create_Failure(maybeEncryptionContext.dtor_error());
}
// Precondition: All actions MUST be supported types
final Result<Map<String, Set<EncryptionFlags>>, Error> maybeActions = legacyActions(legacyOverride.dtor_attributeActionsOnEncrypt());
if (maybeActions.is_Failure()) {
return Result.create_Failure(maybeEncryptionContext.dtor_error());
}
final InternalLegacyOverride internalLegacyOverride = new InternalLegacyOverride(
(DynamoDBEncryptor) maybeEncryptor,
maybeActions.dtor_value(),
maybeEncryptionContext.dtor_value(),
legacyOverride.dtor_policy()
);
return Result.create_Success(Option.create_Some(internalLegacyOverride));
}
// Everything below this point is an implementation detail
public static <T> Result<T, Error>createFailure(String message) {
final DafnySequence<Character> dafnyMessage = software.amazon.smithy.dafny.conversion.ToDafny.Simple.CharacterSequence(message);
final Error dafnyEx = Error.create_DynamoDbItemEncryptorException(dafnyMessage);
return Result.create_Failure(dafnyEx);
}
public static boolean isDynamoDBEncryptor(
software.amazon.cryptography.dbencryptionsdk.dynamodb.ILegacyDynamoDbEncryptor maybe
) {
System.out.println(maybe.getClass());
return maybe.getClass().equals(DynamoDBEncryptor.class);
}
public static String ToNativeString(DafnySequence< ? extends Character> s)
{
return software.amazon.smithy.dafny.conversion.ToNative.Simple.String(s);
}
public static DafnySequence<Character> ToDafnyString(String s)
{
return software.amazon.smithy.dafny.conversion.ToDafny.Simple.CharacterSequence(s);
}
public static Result<EncryptionContext, Error> legacyEncryptionContext(
software.amazon.cryptography.dbencryptionsdk.dynamodb.itemencryptor.internaldafny.types.DynamoDbItemEncryptorConfig config
) {
try {
EncryptionContext.Builder encryptionContextBuilder = new EncryptionContext
.Builder()
.withTableName(ToNativeString(config.dtor_logicalTableName()))
.withHashKeyName(ToNativeString(config.dtor_partitionKeyName()));
final EncryptionContext encryptionContext = config.dtor_sortKeyName().is_Some()
? encryptionContextBuilder.withRangeKeyName(ToNativeString(config.dtor_sortKeyName().dtor_value())).build()
: encryptionContextBuilder.build();
return Result.create_Success(encryptionContext);
} catch (Exception ex) {
return Result.create_Failure(Error.create_Opaque(ex));
}
}
public static Result<Map<String, Set<EncryptionFlags>>, Error> legacyActions(
DafnyMap<? extends DafnySequence<? extends Character>, ? extends CryptoAction> attributeActionsOnEncrypt
) {
try {
final EnumSet<EncryptionFlags> signOnly = EnumSet.of(EncryptionFlags.SIGN);
final EnumSet<EncryptionFlags> encryptAndSign = EnumSet.of(EncryptionFlags.ENCRYPT, EncryptionFlags.SIGN);
Map<String, Set<EncryptionFlags>> legacyActions = new HashMap<>();
BiConsumer<? super DafnySequence<? extends Character>, ? super CryptoAction> buildLegacyActions = (dafnyKey, value) -> {
final String key = ToNativeString(dafnyKey);
if (value.is_SIGN__ONLY()) {
legacyActions.put(key, signOnly);
} else if (value.is_ENCRYPT__AND__SIGN()) {
legacyActions.put(key, encryptAndSign);
} else if (value.is_DO__NOTHING()) {
// DDB-EC v1 is not explicit
} else {
// Exceptional Postcondition: Only ENCRYPT and SIGN are supported. Do Nothing is not supported
throw new IllegalArgumentException("Unsupported CryptoAction.");
}
};
attributeActionsOnEncrypt.forEach(buildLegacyActions);
return Result.create_Success(legacyActions);
} catch (IllegalArgumentException ex) {
final Error dafnyEx = Error.create_DynamoDbItemEncryptorException(ToDafnyString(ex.getMessage()));
return Result.create_Failure(dafnyEx);
} catch (Exception ex) {
return Result.create_Failure(Error.create_Opaque(ex));
}
}
public static com.amazonaws.services.dynamodbv2.model.AttributeValue V2AttributeToV1Attribute(
software.amazon.awssdk.services.dynamodb.model.AttributeValue value
) {
final com.amazonaws.services.dynamodbv2.model.AttributeValue attribute = new com.amazonaws.services.dynamodbv2.model.AttributeValue();
switch (value.type()) {
case B:
return attribute.withB(value.b().asByteBuffer());
case BOOL:
return attribute.withBOOL(value.bool());
case BS:
return attribute
.withBS(value.bs().stream().map(b -> b.asByteBuffer()).collect(Collectors.toList()));
case L:
return attribute
.withL(value.l().stream().map(a -> V2AttributeToV1Attribute(a)).collect(Collectors.toList()));
case M:
return attribute.withM(V2MapToV1Map(value.m()));
case N:
return attribute.withN(value.n());
case NS:
return attribute.withNS(value.ns());
case NUL:
return attribute.withNULL(value.nul());
case S:
return attribute.withS(value.s());
case SS:
return attribute.withSS(value.ss());
case UNKNOWN_TO_SDK_VERSION:
throw new IllegalArgumentException("omfg");
}
throw new IllegalArgumentException("omfg");
}
public static Map<String, com.amazonaws.services.dynamodbv2.model.AttributeValue> V2MapToV1Map(
Map<String, software.amazon.awssdk.services.dynamodb.model.AttributeValue> input
) {
return input
.entrySet()
.stream()
.collect(Collectors.toMap(
entry -> entry.getKey(),
entry -> V2AttributeToV1Attribute(entry.getValue()))
);
}
public static software.amazon.awssdk.services.dynamodb.model.AttributeValue V1AttributeToV2Attribute(
com.amazonaws.services.dynamodbv2.model.AttributeValue value
) {
final software.amazon.awssdk.services.dynamodb.model.AttributeValue.Builder attributeBuilder = software.amazon.awssdk.services.dynamodb.model.AttributeValue.builder();
if (Boolean.TRUE.equals(value.getNULL())) {
return attributeBuilder.nul(value.getNULL()).build();
} else if (Boolean.FALSE.equals(value.getNULL())) {
throw new UnsupportedOperationException("False-NULL is not supported in DynamoDB");
} else if (value.getBOOL() != null) {
return attributeBuilder.bool(value.getBOOL()).build();
} else if (value.getS() != null) {
return attributeBuilder.s(value.getS()).build();
} else if (value.getN() != null) {
return attributeBuilder.n(value.getN()).build();
} else if (value.getB() != null) {
return attributeBuilder.b(SdkBytes.fromByteBuffer(value.getB())).build();
} else if (value.getSS() != null) {
return attributeBuilder.ss(value.getSS()).build();
} else if (value.getNS() != null) {
return attributeBuilder.ns(value.getNS()).build();
} else if (value.getBS() != null) {
return attributeBuilder
.bs(value.getBS().stream().map(bb -> SdkBytes.fromByteBuffer(bb)).collect(Collectors.toList()))
.build();
} else if (value.getL() != null) {
return attributeBuilder
.l(value.getL().stream().map(a -> V1AttributeToV2Attribute(a)).collect(Collectors.toList()))
.build();
} else if (value.getM() != null) {
return attributeBuilder.m(V1MapToV2Map(value.getM())).build();
} else {
throw new IllegalArgumentException("Unsupported Value" + value);
}
}
public static Map<String, software.amazon.awssdk.services.dynamodb.model.AttributeValue> V1MapToV2Map(
Map<String, com.amazonaws.services.dynamodbv2.model.AttributeValue> input
) {
return input
.entrySet()
.stream()
.collect(Collectors.toMap(
entry -> entry.getKey(),
entry -> V1AttributeToV2Attribute(entry.getValue()))
);
}
}
| 5,044 |
0 | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/main/sdkv1/com/amazonaws/services/dynamodbv2 | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/main/sdkv1/com/amazonaws/services/dynamodbv2/datamodeling/AttributeEncryptor.java | /*
* Copyright 2014 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.services.dynamodbv2.datamodeling;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapperConfig.SaveBehavior;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMappingsRegistry.Mapping;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMappingsRegistry.Mappings;
import com.amazonaws.services.dynamodbv2.datamodeling.encryption.DoNotEncrypt;
import com.amazonaws.services.dynamodbv2.datamodeling.encryption.DoNotTouch;
import com.amazonaws.services.dynamodbv2.datamodeling.encryption.DynamoDBEncryptor;
import com.amazonaws.services.dynamodbv2.datamodeling.encryption.EncryptionContext;
import com.amazonaws.services.dynamodbv2.datamodeling.encryption.EncryptionFlags;
import com.amazonaws.services.dynamodbv2.datamodeling.encryption.HandleUnknownAttributes;
import com.amazonaws.services.dynamodbv2.datamodeling.encryption.TableAadOverride;
import com.amazonaws.services.dynamodbv2.datamodeling.encryption.providers.EncryptionMaterialsProvider;
import com.amazonaws.services.dynamodbv2.model.AttributeValue;
import java.util.Collections;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
/**
* Encrypts all non-key fields prior to storing them in DynamoDB. <em>This must be used with {@link
* SaveBehavior#PUT} or {@link SaveBehavior#CLOBBER}.</em>
*
* <p>For guidance on performing a safe data model change procedure, please see <a
* href="https://docs.aws.amazon.com/dynamodb-encryption-client/latest/devguide/data-model.html"
* target="_blank"> DynamoDB Encryption Client Developer Guide: Changing your data model</a>
*
* @author Greg Rubin
*/
public class AttributeEncryptor implements AttributeTransformer {
private final DynamoDBEncryptor encryptor;
private final Map<Class<?>, ModelClassMetadata> metadataCache = new ConcurrentHashMap<>();
public AttributeEncryptor(final DynamoDBEncryptor encryptor) {
this.encryptor = encryptor;
}
public AttributeEncryptor(final EncryptionMaterialsProvider encryptionMaterialsProvider) {
encryptor = DynamoDBEncryptor.getInstance(encryptionMaterialsProvider);
}
public DynamoDBEncryptor getEncryptor() {
return encryptor;
}
@Override
public Map<String, AttributeValue> transform(final Parameters<?> parameters) {
// one map of attributeActionsOnEncrypt per model class
final ModelClassMetadata metadata = getModelClassMetadata(parameters);
final Map<String, AttributeValue> attributeValues = parameters.getAttributeValues();
// If this class is marked as "DoNotTouch" then we know our encryptor will not change it at all
// so we may as well fast-return and do nothing. This also avoids emitting errors when they
// would not apply.
if (metadata.doNotTouch) {
return attributeValues;
}
// When AttributeEncryptor is used without SaveBehavior.PUT or CLOBBER, it is trying to
// transform only a subset
// of the actual fields stored in DynamoDB. This means that the generated signature will not
// cover any
// unmodified fields. Thus, upon untransform, the signature verification will fail as it won't
// cover all
// expected fields.
if (parameters.isPartialUpdate()) {
throw new DynamoDBMappingException(
"Use of AttributeEncryptor without SaveBehavior.PUT or SaveBehavior.CLOBBER is an error "
+ "and can result in data-corruption. This occured while trying to save "
+ parameters.getModelClass());
}
try {
return encryptor.encryptRecord(
attributeValues, metadata.getEncryptionFlags(), paramsToContext(parameters));
} catch (Exception ex) {
throw new DynamoDBMappingException(ex);
}
}
@Override
public Map<String, AttributeValue> untransform(final Parameters<?> parameters) {
final Map<String, Set<EncryptionFlags>> attributeActionsOnEncrypt = getEncryptionFlags(parameters);
try {
return encryptor.decryptRecord(
parameters.getAttributeValues(), attributeActionsOnEncrypt, paramsToContext(parameters));
} catch (Exception ex) {
throw new DynamoDBMappingException(ex);
}
}
/*
* For any attributes we see from DynamoDB that aren't modeled in the mapper class,
* we either ignore them (the default behavior), or include them for encryption/signing
* based on the presence of the @HandleUnknownAttributes annotation (unless the class
* has @DoNotTouch, then we don't include them).
*/
private Map<String, Set<EncryptionFlags>> getEncryptionFlags(final Parameters<?> parameters) {
final ModelClassMetadata metadata = getModelClassMetadata(parameters);
// If the class is annotated with @DoNotTouch, then none of the attributes are
// encrypted or signed, so we don't need to bother looking for unknown attributes.
if (metadata.getDoNotTouch()) {
return metadata.getEncryptionFlags();
}
final Set<EncryptionFlags> unknownAttributeBehavior = metadata.getUnknownAttributeBehavior();
final Map<String, Set<EncryptionFlags>> attributeActionsOnEncrypt = new HashMap<>();
attributeActionsOnEncrypt.putAll(metadata.getEncryptionFlags());
for (final String attributeName : parameters.getAttributeValues().keySet()) {
if (!attributeActionsOnEncrypt.containsKey(attributeName)
&& !encryptor.getSignatureFieldName().equals(attributeName)
&& !encryptor.getMaterialDescriptionFieldName().equals(attributeName)) {
attributeActionsOnEncrypt.put(attributeName, unknownAttributeBehavior);
}
}
return attributeActionsOnEncrypt;
}
private <T> ModelClassMetadata getModelClassMetadata(Parameters<T> parameters) {
// Due to the lack of explicit synchronization, it is possible that
// elements in the cache will be added multiple times. Since they will
// all be identical, this is okay. Avoiding explicit synchronization
// means that in the general (retrieval) case, should never block and
// should be extremely fast.
final Class<T> clazz = parameters.getModelClass();
ModelClassMetadata metadata = metadataCache.get(clazz);
if (metadata == null) {
Map<String, Set<EncryptionFlags>> attributeActionsOnEncrypt = new HashMap<>();
final boolean handleUnknownAttributes = handleUnknownAttributes(clazz);
final EnumSet<EncryptionFlags> unknownAttributeBehavior =
EnumSet.noneOf(EncryptionFlags.class);
if (shouldTouch(clazz)) {
Mappings mappings = DynamoDBMappingsRegistry.instance().mappingsOf(clazz);
for (Mapping mapping : mappings.getMappings()) {
final EnumSet<EncryptionFlags> flags = EnumSet.noneOf(EncryptionFlags.class);
StandardAnnotationMaps.FieldMap<?> fieldMap =
StandardAnnotationMaps.of(mapping.getter(), null);
if (shouldTouch(fieldMap)) {
if (shouldEncryptAttribute(clazz, mapping, fieldMap)) {
flags.add(EncryptionFlags.ENCRYPT);
}
flags.add(EncryptionFlags.SIGN);
}
attributeActionsOnEncrypt.put(mapping.getAttributeName(), Collections.unmodifiableSet(flags));
}
if (handleUnknownAttributes) {
unknownAttributeBehavior.add(EncryptionFlags.SIGN);
if (shouldEncrypt(clazz)) {
unknownAttributeBehavior.add(EncryptionFlags.ENCRYPT);
}
}
}
metadata =
new ModelClassMetadata(
Collections.unmodifiableMap(attributeActionsOnEncrypt),
doNotTouch(clazz),
Collections.unmodifiableSet(unknownAttributeBehavior));
metadataCache.put(clazz, metadata);
}
return metadata;
}
/** @return True if {@link DoNotTouch} is not present on the class level. False otherwise */
private boolean shouldTouch(Class<?> clazz) {
return !doNotTouch(clazz);
}
/** @return True if {@link DoNotTouch} is not present on the getter level. False otherwise. */
private boolean shouldTouch(StandardAnnotationMaps.FieldMap<?> fieldMap) {
return !doNotTouch(fieldMap);
}
/** @return True if {@link DoNotTouch} IS present on the class level. False otherwise. */
private boolean doNotTouch(Class<?> clazz) {
return clazz.isAnnotationPresent(DoNotTouch.class);
}
/** @return True if {@link DoNotTouch} IS present on the getter level. False otherwise. */
private boolean doNotTouch(StandardAnnotationMaps.FieldMap<?> fieldMap) {
return fieldMap.actualOf(DoNotTouch.class) != null;
}
/** @return True if {@link DoNotEncrypt} is NOT present on the class level. False otherwise. */
private boolean shouldEncrypt(Class<?> clazz) {
return !doNotEncrypt(clazz);
}
/** @return True if {@link DoNotEncrypt} IS present on the class level. False otherwise. */
private boolean doNotEncrypt(Class<?> clazz) {
return clazz.isAnnotationPresent(DoNotEncrypt.class);
}
/** @return True if {@link DoNotEncrypt} IS present on the getter level. False otherwise. */
private boolean doNotEncrypt(StandardAnnotationMaps.FieldMap<?> fieldMap) {
return fieldMap.actualOf(DoNotEncrypt.class) != null;
}
/** @return True if the attribute should be encrypted, false otherwise. */
private boolean shouldEncryptAttribute(
final Class<?> clazz,
final Mapping mapping,
final StandardAnnotationMaps.FieldMap<?> fieldMap) {
return !(doNotEncrypt(clazz)
|| doNotEncrypt(fieldMap)
|| mapping.isPrimaryKey()
|| mapping.isVersion());
}
private static EncryptionContext paramsToContext(Parameters<?> params) {
final Class<?> clazz = params.getModelClass();
final TableAadOverride override = clazz.getAnnotation(TableAadOverride.class);
final String tableName = ((override == null) ? params.getTableName() : override.tableName());
return new EncryptionContext.Builder()
.withHashKeyName(params.getHashKeyName())
.withRangeKeyName(params.getRangeKeyName())
.withTableName(tableName)
.withModeledClass(params.getModelClass())
.withAttributeValues(params.getAttributeValues())
.build();
}
private boolean handleUnknownAttributes(Class<?> clazz) {
return clazz.getAnnotation(HandleUnknownAttributes.class) != null;
}
private static class ModelClassMetadata {
private final Map<String, Set<EncryptionFlags>> encryptionFlags;
private final boolean doNotTouch;
private final Set<EncryptionFlags> unknownAttributeBehavior;
public ModelClassMetadata(
Map<String, Set<EncryptionFlags>> encryptionFlags,
boolean doNotTouch,
Set<EncryptionFlags> unknownAttributeBehavior) {
this.encryptionFlags = encryptionFlags;
this.doNotTouch = doNotTouch;
this.unknownAttributeBehavior = unknownAttributeBehavior;
}
public Map<String, Set<EncryptionFlags>> getEncryptionFlags() {
return encryptionFlags;
}
public boolean getDoNotTouch() {
return doNotTouch;
}
public Set<EncryptionFlags> getUnknownAttributeBehavior() {
return unknownAttributeBehavior;
}
}
}
| 5,045 |
0 | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/main/sdkv1/com/amazonaws/services/dynamodbv2/datamodeling | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/main/sdkv1/com/amazonaws/services/dynamodbv2/datamodeling/encryption/DynamoDBSigner.java | /*
* Copyright 2014 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.services.dynamodbv2.datamodeling.encryption;
import com.amazonaws.services.dynamodbv2.datamodeling.internal.AttributeValueMarshaller;
import com.amazonaws.services.dynamodbv2.datamodeling.internal.Utils;
import com.amazonaws.services.dynamodbv2.model.AttributeValue;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.security.GeneralSecurityException;
import java.security.Key;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.Signature;
import java.security.SignatureException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
/**
* For guidance on performing a safe data model change procedure, please see <a
* href="https://docs.aws.amazon.com/dynamodb-encryption-client/latest/devguide/data-model.html"
* target="_blank"> DynamoDB Encryption Client Developer Guide: Changing your data model</a>
*
* @author Greg Rubin
*/
// NOTE: This class must remain thread-safe.
class DynamoDBSigner {
private static final ConcurrentHashMap<String, DynamoDBSigner> cache =
new ConcurrentHashMap<String, DynamoDBSigner>();
protected static final Charset UTF8 = Charset.forName("UTF-8");
private final SecureRandom rnd;
private final SecretKey hmacComparisonKey;
private final String signingAlgorithm;
/**
* @param signingAlgorithm is the algorithm used for asymmetric signing (ex: SHA256withRSA). This
* is ignored for symmetric HMACs as that algorithm is fully specified by the key.
*/
static DynamoDBSigner getInstance(String signingAlgorithm, SecureRandom rnd) {
DynamoDBSigner result = cache.get(signingAlgorithm);
if (result == null) {
result = new DynamoDBSigner(signingAlgorithm, rnd);
cache.putIfAbsent(signingAlgorithm, result);
}
return result;
}
/**
* @param signingAlgorithm is the algorithm used for asymmetric signing (ex: SHA256withRSA). This
* is ignored for symmetric HMACs as that algorithm is fully specified by the key.
*/
private DynamoDBSigner(String signingAlgorithm, SecureRandom rnd) {
if (rnd == null) {
rnd = Utils.getRng();
}
this.rnd = rnd;
this.signingAlgorithm = signingAlgorithm;
// Shorter than the output of SHA256 to avoid weak keys.
// http://cs.nyu.edu/~dodis/ps/h-of-h.pdf
// http://link.springer.com/chapter/10.1007%2F978-3-642-32009-5_21
byte[] tmpKey = new byte[31];
rnd.nextBytes(tmpKey);
hmacComparisonKey = new SecretKeySpec(tmpKey, "HmacSHA256");
}
void verifySignature(
Map<String, AttributeValue> itemAttributes,
Map<String, Set<EncryptionFlags>> attributeActionsOnEncrypt,
byte[] associatedData,
Key verificationKey,
ByteBuffer signature)
throws GeneralSecurityException {
// System.out.println("verifySignature");
// System.out.println(itemAttributes);
// System.out.println(attributeActionsOnEncrypt);
// System.out.println("==========");
if (verificationKey instanceof DelegatedKey) {
DelegatedKey dKey = (DelegatedKey) verificationKey;
byte[] stringToSign = calculateStringToSign(itemAttributes, attributeActionsOnEncrypt, associatedData);
if (!dKey.verify(stringToSign, toByteArray(signature), dKey.getAlgorithm())) {
throw new SignatureException("Bad signature");
}
} else if (verificationKey instanceof SecretKey) {
byte[] calculatedSig =
calculateSignature(
itemAttributes, attributeActionsOnEncrypt, associatedData, (SecretKey) verificationKey);
if (!safeEquals(signature, calculatedSig)) {
throw new SignatureException("Bad signature");
}
} else if (verificationKey instanceof PublicKey) {
PublicKey integrityKey = (PublicKey) verificationKey;
byte[] stringToSign = calculateStringToSign(itemAttributes, attributeActionsOnEncrypt, associatedData);
Signature sig = Signature.getInstance(getSigningAlgorithm());
sig.initVerify(integrityKey);
sig.update(stringToSign);
if (!sig.verify(toByteArray(signature))) {
throw new SignatureException("Bad signature");
}
} else {
throw new IllegalArgumentException("No integrity key provided");
}
}
static byte[] calculateStringToSign(
Map<String, AttributeValue> itemAttributes,
Map<String, Set<EncryptionFlags>> attributeActionsOnEncrypt,
byte[] associatedData)
throws NoSuchAlgorithmException {
try {
ByteArrayOutputStream out = new ByteArrayOutputStream();
List<String> attrNames = new ArrayList<String>(itemAttributes.keySet());
Collections.sort(attrNames);
MessageDigest sha256 = MessageDigest.getInstance("SHA-256");
if (associatedData != null) {
out.write(sha256.digest(associatedData));
} else {
out.write(sha256.digest());
}
sha256.reset();
for (String name : attrNames) {
Set<EncryptionFlags> set = attributeActionsOnEncrypt.get(name);
if (set != null && set.contains(EncryptionFlags.SIGN)) {
AttributeValue tmp = itemAttributes.get(name);
out.write(sha256.digest(name.getBytes(UTF8)));
sha256.reset();
if (set.contains(EncryptionFlags.ENCRYPT)) {
sha256.update("ENCRYPTED".getBytes(UTF8));
} else {
sha256.update("PLAINTEXT".getBytes(UTF8));
}
out.write(sha256.digest());
sha256.reset();
sha256.update(AttributeValueMarshaller.marshall(tmp));
out.write(sha256.digest());
sha256.reset();
}
}
return out.toByteArray();
} catch (IOException ex) {
// Due to the objects in use, an IOException is not possible.
throw new RuntimeException("Unexpected exception", ex);
}
}
/** The itemAttributes have already been encrypted, if necessary, before the signing. */
byte[] calculateSignature(
Map<String, AttributeValue> itemAttributes,
Map<String, Set<EncryptionFlags>> attributeActionsOnEncrypt,
byte[] associatedData,
Key key)
throws GeneralSecurityException {
if (key instanceof DelegatedKey) {
return calculateSignature(itemAttributes, attributeActionsOnEncrypt, associatedData, (DelegatedKey) key);
} else if (key instanceof SecretKey) {
return calculateSignature(itemAttributes, attributeActionsOnEncrypt, associatedData, (SecretKey) key);
} else if (key instanceof PrivateKey) {
return calculateSignature(itemAttributes, attributeActionsOnEncrypt, associatedData, (PrivateKey) key);
} else {
throw new IllegalArgumentException("No integrity key provided");
}
}
byte[] calculateSignature(
Map<String, AttributeValue> itemAttributes,
Map<String, Set<EncryptionFlags>> attributeActionsOnEncrypt,
byte[] associatedData,
DelegatedKey key)
throws GeneralSecurityException {
byte[] stringToSign = calculateStringToSign(itemAttributes, attributeActionsOnEncrypt, associatedData);
return key.sign(stringToSign, key.getAlgorithm());
}
byte[] calculateSignature(
Map<String, AttributeValue> itemAttributes,
Map<String, Set<EncryptionFlags>> attributeActionsOnEncrypt,
byte[] associatedData,
SecretKey key)
throws GeneralSecurityException {
if (key instanceof DelegatedKey) {
return calculateSignature(itemAttributes, attributeActionsOnEncrypt, associatedData, (DelegatedKey) key);
}
byte[] stringToSign = calculateStringToSign(itemAttributes, attributeActionsOnEncrypt, associatedData);
Mac hmac = Mac.getInstance(key.getAlgorithm());
hmac.init(key);
hmac.update(stringToSign);
return hmac.doFinal();
}
byte[] calculateSignature(
Map<String, AttributeValue> itemAttributes,
Map<String, Set<EncryptionFlags>> attributeActionsOnEncrypt,
byte[] associatedData,
PrivateKey key)
throws GeneralSecurityException {
byte[] stringToSign = calculateStringToSign(itemAttributes, attributeActionsOnEncrypt, associatedData);
Signature sig = Signature.getInstance(signingAlgorithm);
sig.initSign(key, rnd);
sig.update(stringToSign);
return sig.sign();
}
String getSigningAlgorithm() {
return signingAlgorithm;
}
/** Constant-time equality check. */
private boolean safeEquals(ByteBuffer signature, byte[] calculatedSig) {
try {
signature.rewind();
Mac hmac = Mac.getInstance(hmacComparisonKey.getAlgorithm());
hmac.init(hmacComparisonKey);
hmac.update(signature);
byte[] signatureHash = hmac.doFinal();
hmac.reset();
hmac.update(calculatedSig);
byte[] calculatedHash = hmac.doFinal();
return MessageDigest.isEqual(signatureHash, calculatedHash);
} catch (GeneralSecurityException ex) {
// We've hardcoded these algorithms, so the error should not be possible.
throw new RuntimeException("Unexpected exception", ex);
}
}
private static byte[] toByteArray(ByteBuffer buffer) {
if (buffer.hasArray()) {
byte[] result = buffer.array();
buffer.rewind();
return result;
} else {
byte[] result = new byte[buffer.remaining()];
buffer.get(result);
buffer.rewind();
return result;
}
}
}
| 5,046 |
0 | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/main/sdkv1/com/amazonaws/services/dynamodbv2/datamodeling | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/main/sdkv1/com/amazonaws/services/dynamodbv2/datamodeling/encryption/TableAadOverride.java | /*
* Copyright 2015 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.services.dynamodbv2.datamodeling.encryption;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Overrides the default tablename used as part of the data signature with {@code tableName}
* instead. This can be useful when multiple tables are used interchangably and data should be able
* to be copied or moved between them without needing to be reencrypted.
*
* <p>For guidance on performing a safe data model change procedure, please see <a
* href="https://docs.aws.amazon.com/dynamodb-encryption-client/latest/devguide/data-model.html"
* target="_blank"> DynamoDB Encryption Client Developer Guide: Changing your data model</a>
*
* @author Greg Rubin
*/
@Target(value = {ElementType.TYPE})
@Retention(value = RetentionPolicy.RUNTIME)
public @interface TableAadOverride {
String tableName();
}
| 5,047 |
0 | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/main/sdkv1/com/amazonaws/services/dynamodbv2/datamodeling | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/main/sdkv1/com/amazonaws/services/dynamodbv2/datamodeling/encryption/DynamoDBEncryptor.java | /*
* Copyright 2014 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.services.dynamodbv2.datamodeling.encryption;
import com.amazonaws.services.dynamodbv2.datamodeling.AttributeEncryptor;
import com.amazonaws.services.dynamodbv2.datamodeling.encryption.materials.DecryptionMaterials;
import com.amazonaws.services.dynamodbv2.datamodeling.encryption.materials.EncryptionMaterials;
import com.amazonaws.services.dynamodbv2.datamodeling.encryption.providers.EncryptionMaterialsProvider;
import com.amazonaws.services.dynamodbv2.datamodeling.internal.AttributeValueMarshaller;
import com.amazonaws.services.dynamodbv2.datamodeling.internal.ByteBufferInputStream;
import com.amazonaws.services.dynamodbv2.datamodeling.internal.Utils;
import com.amazonaws.services.dynamodbv2.model.AttributeValue;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.EOFException;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.security.GeneralSecurityException;
import java.security.PrivateKey;
import java.security.SignatureException;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import software.amazon.cryptography.dbencryptionsdk.dynamodb.ILegacyDynamoDbEncryptor;
/**
* The low-level API used by {@link AttributeEncryptor} to perform crypto operations on the record
* attributes.
*
* <p>For guidance on performing a safe data model change procedure, please see <a
* href="https://docs.aws.amazon.com/dynamodb-encryption-client/latest/devguide/data-model.html"
* target="_blank"> DynamoDB Encryption Client Developer Guide: Changing your data model</a>
*
* @author Greg Rubin
*/
public class DynamoDBEncryptor implements ILegacyDynamoDbEncryptor {
private static final String DEFAULT_SIGNATURE_ALGORITHM = "SHA256withRSA";
private static final String DEFAULT_METADATA_FIELD = "*amzn-ddb-map-desc*";
private static final String DEFAULT_SIGNATURE_FIELD = "*amzn-ddb-map-sig*";
private static final String DEFAULT_DESCRIPTION_BASE = "amzn-ddb-map-"; // Same as the Mapper
private static final Charset UTF8 = Charset.forName("UTF-8");
private static final String SYMMETRIC_ENCRYPTION_MODE = "/CBC/PKCS5Padding";
private static final ConcurrentHashMap<String, Integer> BLOCK_SIZE_CACHE =
new ConcurrentHashMap<>();
private static final Function<String, Integer> BLOCK_SIZE_CALCULATOR =
(transformation) -> {
try {
final Cipher c = Cipher.getInstance(transformation);
return c.getBlockSize();
} catch (final GeneralSecurityException ex) {
throw new IllegalArgumentException("Algorithm does not exist", ex);
}
};
private static final int CURRENT_VERSION = 0;
private String signatureFieldName = DEFAULT_SIGNATURE_FIELD;
private String materialDescriptionFieldName = DEFAULT_METADATA_FIELD;
private EncryptionMaterialsProvider encryptionMaterialsProvider;
private final String descriptionBase;
private final String symmetricEncryptionModeHeader;
private final String signingAlgorithmHeader;
public static final String DEFAULT_SIGNING_ALGORITHM_HEADER =
DEFAULT_DESCRIPTION_BASE + "signingAlg";
private Function<EncryptionContext, EncryptionContext> encryptionContextOverrideOperator;
protected DynamoDBEncryptor(EncryptionMaterialsProvider provider, String descriptionBase) {
this.encryptionMaterialsProvider = provider;
this.descriptionBase = descriptionBase;
symmetricEncryptionModeHeader = this.descriptionBase + "sym-mode";
signingAlgorithmHeader = this.descriptionBase + "signingAlg";
}
public static DynamoDBEncryptor getInstance(
EncryptionMaterialsProvider provider, String descriptionbase) {
return new DynamoDBEncryptor(provider, descriptionbase);
}
public static DynamoDBEncryptor getInstance(EncryptionMaterialsProvider provider) {
return getInstance(provider, DEFAULT_DESCRIPTION_BASE);
}
/**
* Returns a decrypted version of the provided DynamoDb record. The signature is verified across
* all provided fields. All fields (except those listed in <code>doNotEncrypt</code> are
* decrypted.
*
* @param itemAttributes the DynamoDbRecord
* @param context additional information used to successfully select the encryption materials and
* decrypt the data. This should include (at least) the tableName and the materialDescription.
* @param doNotDecrypt those fields which should not be encrypted
* @return a plaintext version of the DynamoDb record
* @throws SignatureException if the signature is invalid or cannot be verified
* @throws GeneralSecurityException
*/
public Map<String, AttributeValue> decryptAllFieldsExcept(
Map<String, AttributeValue> itemAttributes, EncryptionContext context, String... doNotDecrypt)
throws GeneralSecurityException {
return decryptAllFieldsExcept(itemAttributes, context, Arrays.asList(doNotDecrypt));
}
/** @see #decryptAllFieldsExcept(Map, EncryptionContext, String...) */
public Map<String, AttributeValue> decryptAllFieldsExcept(
Map<String, AttributeValue> itemAttributes,
EncryptionContext context,
Collection<String> doNotDecrypt)
throws GeneralSecurityException {
Map<String, Set<EncryptionFlags>> attributeActionsOnEncrypt =
allDecryptionFlagsExcept(itemAttributes, doNotDecrypt);
return decryptRecord(itemAttributes, attributeActionsOnEncrypt, context);
}
/**
* Returns the decryption flags for all item attributes except for those explicitly specified to
* be excluded.
*
* @param doNotDecrypt fields to be excluded
*/
public Map<String, Set<EncryptionFlags>> allDecryptionFlagsExcept(
Map<String, AttributeValue> itemAttributes, String... doNotDecrypt) {
return allDecryptionFlagsExcept(itemAttributes, Arrays.asList(doNotDecrypt));
}
/**
* Returns the decryption flags for all item attributes except for those explicitly specified to
* be excluded.
*
* @param doNotDecrypt fields to be excluded
*/
public Map<String, Set<EncryptionFlags>> allDecryptionFlagsExcept(
Map<String, AttributeValue> itemAttributes, Collection<String> doNotDecrypt) {
Map<String, Set<EncryptionFlags>> attributeActionsOnEncrypt = new HashMap<String, Set<EncryptionFlags>>();
for (String fieldName : doNotDecrypt) {
attributeActionsOnEncrypt.put(fieldName, EnumSet.of(EncryptionFlags.SIGN));
}
for (String fieldName : itemAttributes.keySet()) {
if (!attributeActionsOnEncrypt.containsKey(fieldName)
&& !fieldName.equals(getMaterialDescriptionFieldName())
&& !fieldName.equals(getSignatureFieldName())) {
attributeActionsOnEncrypt.put(fieldName, EnumSet.of(EncryptionFlags.ENCRYPT, EncryptionFlags.SIGN));
}
}
return attributeActionsOnEncrypt;
}
/**
* Returns an encrypted version of the provided DynamoDb record. All fields are signed. All fields
* (except those listed in <code>doNotEncrypt</code>) are encrypted.
*
* @param itemAttributes a DynamoDb Record
* @param context additional information used to successfully select the encryption materials and
* encrypt the data. This should include (at least) the tableName.
* @param doNotEncrypt those fields which should not be encrypted
* @return a ciphertext version of the DynamoDb record
* @throws GeneralSecurityException
*/
public Map<String, AttributeValue> encryptAllFieldsExcept(
Map<String, AttributeValue> itemAttributes, EncryptionContext context, String... doNotEncrypt)
throws GeneralSecurityException {
return encryptAllFieldsExcept(itemAttributes, context, Arrays.asList(doNotEncrypt));
}
public Map<String, AttributeValue> encryptAllFieldsExcept(
Map<String, AttributeValue> itemAttributes,
EncryptionContext context,
Collection<String> doNotEncrypt)
throws GeneralSecurityException {
Map<String, Set<EncryptionFlags>> attributeActionsOnEncrypt =
allEncryptionFlagsExcept(itemAttributes, doNotEncrypt);
return encryptRecord(itemAttributes, attributeActionsOnEncrypt, context);
}
/**
* Returns the encryption flags for all item attributes except for those explicitly specified to
* be excluded.
*
* @param doNotEncrypt fields to be excluded
*/
public Map<String, Set<EncryptionFlags>> allEncryptionFlagsExcept(
Map<String, AttributeValue> itemAttributes, String... doNotEncrypt) {
return allEncryptionFlagsExcept(itemAttributes, Arrays.asList(doNotEncrypt));
}
/**
* Returns the encryption flags for all item attributes except for those explicitly specified to
* be excluded.
*
* @param doNotEncrypt fields to be excluded
*/
public Map<String, Set<EncryptionFlags>> allEncryptionFlagsExcept(
Map<String, AttributeValue> itemAttributes, Collection<String> doNotEncrypt) {
Map<String, Set<EncryptionFlags>> attributeActionsOnEncrypt = new HashMap<String, Set<EncryptionFlags>>();
for (String fieldName : doNotEncrypt) {
attributeActionsOnEncrypt.put(fieldName, EnumSet.of(EncryptionFlags.SIGN));
}
for (String fieldName : itemAttributes.keySet()) {
if (!attributeActionsOnEncrypt.containsKey(fieldName)) {
attributeActionsOnEncrypt.put(fieldName, EnumSet.of(EncryptionFlags.ENCRYPT, EncryptionFlags.SIGN));
}
}
return attributeActionsOnEncrypt;
}
public Map<String, AttributeValue> decryptRecord(
Map<String, AttributeValue> itemAttributes,
Map<String, Set<EncryptionFlags>> attributeActionsOnEncrypt,
EncryptionContext context)
throws GeneralSecurityException {
if (!itemContainsFieldsToDecryptOrSign(itemAttributes.keySet(), attributeActionsOnEncrypt)) {
return itemAttributes;
}
// Copy to avoid changing anyone elses objects
itemAttributes = new HashMap<String, AttributeValue>(itemAttributes);
Map<String, String> materialDescription = Collections.emptyMap();
DecryptionMaterials materials;
SecretKey decryptionKey;
DynamoDBSigner signer = DynamoDBSigner.getInstance(DEFAULT_SIGNATURE_ALGORITHM, Utils.getRng());
if (itemAttributes.containsKey(materialDescriptionFieldName)) {
materialDescription = unmarshallDescription(itemAttributes.get(materialDescriptionFieldName));
}
// Copy the material description and attribute values into the context
context =
new EncryptionContext.Builder(context)
.withMaterialDescription(materialDescription)
.withAttributeValues(itemAttributes)
.build();
Function<EncryptionContext, EncryptionContext> encryptionContextOverrideOperator =
getEncryptionContextOverrideOperator();
if (encryptionContextOverrideOperator != null) {
context = encryptionContextOverrideOperator.apply(context);
}
materials = encryptionMaterialsProvider.getDecryptionMaterials(context);
decryptionKey = materials.getDecryptionKey();
if (materialDescription.containsKey(signingAlgorithmHeader)) {
String signingAlg = materialDescription.get(signingAlgorithmHeader);
signer = DynamoDBSigner.getInstance(signingAlg, Utils.getRng());
}
ByteBuffer signature;
if (!itemAttributes.containsKey(signatureFieldName)
|| itemAttributes.get(signatureFieldName).getB() == null) {
signature = ByteBuffer.allocate(0);
} else {
signature = itemAttributes.get(signatureFieldName).getB().asReadOnlyBuffer();
}
itemAttributes.remove(signatureFieldName);
String associatedData = "TABLE>" + context.getTableName() + "<TABLE";
signer.verifySignature(
itemAttributes,
attributeActionsOnEncrypt,
associatedData.getBytes(UTF8),
materials.getVerificationKey(),
signature);
itemAttributes.remove(materialDescriptionFieldName);
actualDecryption(itemAttributes, attributeActionsOnEncrypt, decryptionKey, materialDescription);
return itemAttributes;
}
private boolean itemContainsFieldsToDecryptOrSign(
Set<String> attributeNamesToCheck, Map<String, Set<EncryptionFlags>> attributeActionsOnEncrypt) {
return attributeNamesToCheck.stream()
.filter(attributeActionsOnEncrypt::containsKey)
.anyMatch(attributeName -> !attributeActionsOnEncrypt.get(attributeName).isEmpty());
}
/**
* Returns the encrypted (and signed) record, which is a map of item attributes. There is no side
* effect on the input parameters upon calling this method.
*
* @param itemAttributes the input record
* @param attributeActionsOnEncrypt the corresponding encryption flags
* @param context encryption context
* @return a new instance of item attributes encrypted as necessary
* @throws GeneralSecurityException if failed to encrypt the record
*/
public Map<String, AttributeValue> encryptRecord(
Map<String, AttributeValue> itemAttributes,
Map<String, Set<EncryptionFlags>> attributeActionsOnEncrypt,
EncryptionContext context)
throws GeneralSecurityException {
if (attributeActionsOnEncrypt.isEmpty()) {
return itemAttributes;
}
// Copy to avoid changing anyone elses objects
itemAttributes = new HashMap<String, AttributeValue>(itemAttributes);
// Copy the attribute values into the context
context = new EncryptionContext.Builder(context).withAttributeValues(itemAttributes).build();
Function<EncryptionContext, EncryptionContext> encryptionContextOverrideOperator =
getEncryptionContextOverrideOperator();
if (encryptionContextOverrideOperator != null) {
context = encryptionContextOverrideOperator.apply(context);
}
EncryptionMaterials materials = encryptionMaterialsProvider.getEncryptionMaterials(context);
// We need to copy this because we modify it to record other encryption details
Map<String, String> materialDescription =
new HashMap<String, String>(materials.getMaterialDescription());
SecretKey encryptionKey = materials.getEncryptionKey();
actualEncryption(itemAttributes, attributeActionsOnEncrypt, materialDescription, encryptionKey);
// The description must be stored after encryption because its data
// is necessary for proper decryption.
final String signingAlgo = materialDescription.get(signingAlgorithmHeader);
DynamoDBSigner signer;
if (signingAlgo != null) {
signer = DynamoDBSigner.getInstance(signingAlgo, Utils.getRng());
} else {
signer = DynamoDBSigner.getInstance(DEFAULT_SIGNATURE_ALGORITHM, Utils.getRng());
}
if (materials.getSigningKey() instanceof PrivateKey) {
materialDescription.put(signingAlgorithmHeader, signer.getSigningAlgorithm());
}
if (!materialDescription.isEmpty()) {
itemAttributes.put(materialDescriptionFieldName, marshallDescription(materialDescription));
}
String associatedData = "TABLE>" + context.getTableName() + "<TABLE";
byte[] signature =
signer.calculateSignature(
itemAttributes,
attributeActionsOnEncrypt,
associatedData.getBytes(UTF8),
materials.getSigningKey());
AttributeValue signatureAttribute = new AttributeValue();
signatureAttribute.setB(ByteBuffer.wrap(signature));
itemAttributes.put(signatureFieldName, signatureAttribute);
return itemAttributes;
}
private void actualDecryption(
Map<String, AttributeValue> itemAttributes,
Map<String, Set<EncryptionFlags>> attributeActionsOnEncrypt,
SecretKey encryptionKey,
Map<String, String> materialDescription)
throws GeneralSecurityException {
final String encryptionMode =
encryptionKey != null
? encryptionKey.getAlgorithm() + materialDescription.get(symmetricEncryptionModeHeader)
: null;
Cipher cipher = null;
int blockSize = -1;
for (Map.Entry<String, AttributeValue> entry : itemAttributes.entrySet()) {
Set<EncryptionFlags> flags = attributeActionsOnEncrypt.get(entry.getKey());
if (flags != null && flags.contains(EncryptionFlags.ENCRYPT)) {
if (!flags.contains(EncryptionFlags.SIGN)) {
throw new IllegalArgumentException(
"All encrypted fields must be signed. Bad field: " + entry.getKey());
}
ByteBuffer plainText;
ByteBuffer cipherText = entry.getValue().getB().asReadOnlyBuffer();
cipherText.rewind();
if (encryptionKey instanceof DelegatedKey) {
plainText =
ByteBuffer.wrap(
((DelegatedKey) encryptionKey)
.decrypt(toByteArray(cipherText), null, encryptionMode));
} else {
if (cipher == null) {
blockSize = getBlockSize(encryptionMode);
cipher = Cipher.getInstance(encryptionMode);
}
byte[] iv = new byte[blockSize];
cipherText.get(iv);
cipher.init(Cipher.DECRYPT_MODE, encryptionKey, new IvParameterSpec(iv), Utils.getRng());
plainText = ByteBuffer.allocate(cipher.getOutputSize(cipherText.remaining()));
cipher.doFinal(cipherText, plainText);
plainText.rewind();
}
entry.setValue(AttributeValueMarshaller.unmarshall(plainText));
}
}
}
protected static int getBlockSize(final String encryptionMode) {
return BLOCK_SIZE_CACHE.computeIfAbsent(encryptionMode, BLOCK_SIZE_CALCULATOR);
}
/**
* This method has the side effect of replacing the plaintext attribute-values of "itemAttributes"
* with ciphertext attribute-values (which are always in the form of ByteBuffer) as per the
* corresponding attribute flags.
*/
private void actualEncryption(
Map<String, AttributeValue> itemAttributes,
Map<String, Set<EncryptionFlags>> attributeActionsOnEncrypt,
Map<String, String> materialDescription,
SecretKey encryptionKey)
throws GeneralSecurityException {
String encryptionMode = null;
if (encryptionKey != null) {
materialDescription.put(this.symmetricEncryptionModeHeader, SYMMETRIC_ENCRYPTION_MODE);
encryptionMode = encryptionKey.getAlgorithm() + SYMMETRIC_ENCRYPTION_MODE;
}
Cipher cipher = null;
int blockSize = -1;
for (Map.Entry<String, AttributeValue> entry : itemAttributes.entrySet()) {
Set<EncryptionFlags> flags = attributeActionsOnEncrypt.get(entry.getKey());
if (flags != null && flags.contains(EncryptionFlags.ENCRYPT)) {
if (!flags.contains(EncryptionFlags.SIGN)) {
throw new IllegalArgumentException(
"All encrypted fields must be signed. Bad field: " + entry.getKey());
}
ByteBuffer plainText = AttributeValueMarshaller.marshall(entry.getValue());
plainText.rewind();
ByteBuffer cipherText;
if (encryptionKey instanceof DelegatedKey) {
DelegatedKey dk = (DelegatedKey) encryptionKey;
cipherText = ByteBuffer.wrap(dk.encrypt(toByteArray(plainText), null, encryptionMode));
} else {
if (cipher == null) {
blockSize = getBlockSize(encryptionMode);
cipher = Cipher.getInstance(encryptionMode);
}
// Encryption format: <iv><ciphertext>
// Note a unique iv is generated per attribute
cipher.init(Cipher.ENCRYPT_MODE, encryptionKey, Utils.getRng());
cipherText = ByteBuffer.allocate(blockSize + cipher.getOutputSize(plainText.remaining()));
cipherText.position(blockSize);
cipher.doFinal(plainText, cipherText);
cipherText.flip();
final byte[] iv = cipher.getIV();
if (iv.length != blockSize) {
throw new IllegalStateException(
String.format(
"Generated IV length (%d) not equal to block size (%d)", iv.length, blockSize));
}
cipherText.put(iv);
cipherText.rewind();
}
// Replace the plaintext attribute value with the encrypted content
entry.setValue(new AttributeValue().withB(cipherText));
}
}
}
/**
* Get the name of the DynamoDB field used to store the signature. Defaults to {@link
* #DEFAULT_SIGNATURE_FIELD}.
*
* @return the name of the DynamoDB field used to store the signature
*/
public String getSignatureFieldName() {
return signatureFieldName;
}
/**
* Set the name of the DynamoDB field used to store the signature.
*
* @param signatureFieldName
*/
public void setSignatureFieldName(final String signatureFieldName) {
this.signatureFieldName = signatureFieldName;
}
/**
* Get the name of the DynamoDB field used to store metadata used by the DynamoDBEncryptedMapper.
* Defaults to {@link #DEFAULT_METADATA_FIELD}.
*
* @return the name of the DynamoDB field used to store metadata used by the
* DynamoDBEncryptedMapper
*/
public String getMaterialDescriptionFieldName() {
return materialDescriptionFieldName;
}
/**
* Set the name of the DynamoDB field used to store metadata used by the DynamoDBEncryptedMapper
*
* @param materialDescriptionFieldName
*/
public void setMaterialDescriptionFieldName(final String materialDescriptionFieldName) {
this.materialDescriptionFieldName = materialDescriptionFieldName;
}
/**
* Marshalls the <code>description</code> into a ByteBuffer by outputting each key (modified
* UTF-8) followed by its value (also in modified UTF-8).
*
* @param description
* @return the description encoded as an AttributeValue with a ByteBuffer value
* @see java.io.DataOutput#writeUTF(String)
*/
protected static AttributeValue marshallDescription(Map<String, String> description) {
try {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
DataOutputStream out = new DataOutputStream(bos);
out.writeInt(CURRENT_VERSION);
for (Map.Entry<String, String> entry : description.entrySet()) {
byte[] bytes = entry.getKey().getBytes(UTF8);
out.writeInt(bytes.length);
out.write(bytes);
bytes = entry.getValue().getBytes(UTF8);
out.writeInt(bytes.length);
out.write(bytes);
}
out.close();
AttributeValue result = new AttributeValue();
result.setB(ByteBuffer.wrap(bos.toByteArray()));
return result;
} catch (IOException ex) {
// Due to the objects in use, an IOException is not possible.
throw new RuntimeException("Unexpected exception", ex);
}
}
public String getSigningAlgorithmHeader() {
return signingAlgorithmHeader;
}
/** @see #marshallDescription(Map) */
protected static Map<String, String> unmarshallDescription(AttributeValue attributeValue) {
attributeValue.getB().mark();
try (DataInputStream in =
new DataInputStream(new ByteBufferInputStream(attributeValue.getB()))) {
Map<String, String> result = new HashMap<String, String>();
int version = in.readInt();
if (version != CURRENT_VERSION) {
throw new IllegalArgumentException("Unsupported description version");
}
String key, value;
int keyLength, valueLength;
try {
while (in.available() > 0) {
keyLength = in.readInt();
byte[] bytes = new byte[keyLength];
if (in.read(bytes) != keyLength) {
throw new IllegalArgumentException("Malformed description");
}
key = new String(bytes, UTF8);
valueLength = in.readInt();
bytes = new byte[valueLength];
if (in.read(bytes) != valueLength) {
throw new IllegalArgumentException("Malformed description");
}
value = new String(bytes, UTF8);
result.put(key, value);
}
} catch (EOFException eof) {
throw new IllegalArgumentException("Malformed description", eof);
}
return result;
} catch (IOException ex) {
// Due to the objects in use, an IOException is not possible.
throw new RuntimeException("Unexpected exception", ex);
} finally {
attributeValue.getB().reset();
}
}
/**
* @param encryptionContextOverrideOperator the nullable operator which will be used to override
* the EncryptionContext.
* @see com.amazonaws.services.dynamodbv2.datamodeling.encryption.utils.EncryptionContextOperators
*/
public final void setEncryptionContextOverrideOperator(
Function<EncryptionContext, EncryptionContext> encryptionContextOverrideOperator) {
this.encryptionContextOverrideOperator = encryptionContextOverrideOperator;
}
/**
* @return the operator used to override the EncryptionContext
* @see #setEncryptionContextOverrideOperator(Function)
*/
public final Function<EncryptionContext, EncryptionContext>
getEncryptionContextOverrideOperator() {
return encryptionContextOverrideOperator;
}
private static byte[] toByteArray(ByteBuffer buffer) {
buffer = buffer.duplicate();
// We can only return the array directly if:
// 1. The ByteBuffer exposes an array
// 2. The ByteBuffer starts at the beginning of the array
// 3. The ByteBuffer uses the entire array
if (buffer.hasArray() && buffer.arrayOffset() == 0) {
byte[] result = buffer.array();
if (buffer.remaining() == result.length) {
return result;
}
}
byte[] result = new byte[buffer.remaining()];
buffer.get(result);
return result;
}
}
| 5,048 |
0 | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/main/sdkv1/com/amazonaws/services/dynamodbv2/datamodeling | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/main/sdkv1/com/amazonaws/services/dynamodbv2/datamodeling/encryption/DoNotTouch.java | /*
* Copyright 2014 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.services.dynamodbv2.datamodeling.encryption;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDB;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Prevents the associated item from being encrypted or signed.
*
* <p>For guidance on performing a safe data model change procedure, please see <a
* href="https://docs.aws.amazon.com/dynamodb-encryption-client/latest/devguide/data-model.html"
* target="_blank"> DynamoDB Encryption Client Developer Guide: Changing your data model</a>
*
* @author Greg Rubin
*/
@DynamoDB
@Target(value = {ElementType.TYPE, ElementType.METHOD, ElementType.FIELD})
@Retention(value = RetentionPolicy.RUNTIME)
public @interface DoNotTouch {}
| 5,049 |
0 | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/main/sdkv1/com/amazonaws/services/dynamodbv2/datamodeling | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/main/sdkv1/com/amazonaws/services/dynamodbv2/datamodeling/encryption/DoNotEncrypt.java | /*
* Copyright 2014 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.services.dynamodbv2.datamodeling.encryption;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDB;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Prevents the associated item (class or attribute) from being encrypted.
*
* <p>For guidance on performing a safe data model change procedure, please see <a
* href="https://docs.aws.amazon.com/dynamodb-encryption-client/latest/devguide/data-model.html"
* target="_blank"> DynamoDB Encryption Client Developer Guide: Changing your data model</a>
*
* @author Greg Rubin
*/
@DynamoDB
@Target(value = {ElementType.TYPE, ElementType.METHOD, ElementType.FIELD})
@Retention(value = RetentionPolicy.RUNTIME)
public @interface DoNotEncrypt {}
| 5,050 |
0 | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/main/sdkv1/com/amazonaws/services/dynamodbv2/datamodeling | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/main/sdkv1/com/amazonaws/services/dynamodbv2/datamodeling/encryption/EncryptionContext.java | /*
* Copyright 2014 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.services.dynamodbv2.datamodeling.encryption;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper;
import com.amazonaws.services.dynamodbv2.datamodeling.encryption.materials.DecryptionMaterials;
import com.amazonaws.services.dynamodbv2.datamodeling.encryption.materials.EncryptionMaterials;
import com.amazonaws.services.dynamodbv2.datamodeling.encryption.providers.EncryptionMaterialsProvider;
import com.amazonaws.services.dynamodbv2.model.AttributeValue;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
/**
* This class serves to provide additional useful data to {@link EncryptionMaterialsProvider}s so
* they can more intelligently select the proper {@link EncryptionMaterials} or {@link
* DecryptionMaterials} for use. Any of the methods are permitted to return null.
*
* <p>For the simplest cases, all a developer needs to provide in the context are:
*
* <ul>
* <li>TableName
* <li>HashKeyName
* <li>RangeKeyName (if present)
* </ul>
*
* This class is immutable.
*
* @author Greg Rubin
*/
public final class EncryptionContext {
private final String tableName;
private final Map<String, AttributeValue> attributeValues;
private final Class<?> modeledClass;
private final Object developerContext;
private final String hashKeyName;
private final String rangeKeyName;
private final Map<String, String> materialDescription;
private EncryptionContext(Builder builder) {
tableName = builder.getTableName();
attributeValues = builder.getAttributeValues();
modeledClass = builder.getModeledClass();
developerContext = builder.getDeveloperContext();
hashKeyName = builder.getHashKeyName();
rangeKeyName = builder.getRangeKeyName();
materialDescription = builder.getMaterialDescription();
}
/** Returns the name of the DynamoDB Table this record is associated with. */
public String getTableName() {
return tableName;
}
/** Returns the DynamoDB record about to be encrypted/decrypted. */
public Map<String, AttributeValue> getAttributeValues() {
return attributeValues;
}
/**
* When used for an object mapping layer (such as {@link DynamoDBMapper}) this represents the
* class being mapped to/from DynamoDB.
*/
public Class<?> getModeledClass() {
return modeledClass;
}
/**
* This object has no meaning (and will not be set or examined) by any core libraries. It exists
* to allow custom object mappers and data access layers to pass data to {@link
* EncryptionMaterialsProvider}s through the {@link DynamoDBEncryptor}.
*/
public Object getDeveloperContext() {
return developerContext;
}
/** Returns the name of the HashKey attribute for the record to be encrypted/decrypted. */
public String getHashKeyName() {
return hashKeyName;
}
/** Returns the name of the RangeKey attribute for the record to be encrypted/decrypted. */
public String getRangeKeyName() {
return rangeKeyName;
}
public Map<String, String> getMaterialDescription() {
return materialDescription;
}
/**
* Builder class for {@link EncryptionContext}. Mutable objects (other than <code>developerContext
* </code>) will undergo a defensive copy prior to being stored in the builder.
*
* <p>This class is <em>not</em> thread-safe.
*/
public static final class Builder {
private String tableName = null;
private Map<String, AttributeValue> attributeValues = null;
private Class<?> modeledClass = null;
private Object developerContext = null;
private String hashKeyName = null;
private String rangeKeyName = null;
private Map<String, String> materialDescription = null;
/** Defaults all fields to <code>null</code>. */
public Builder() {}
/** Copy constructor. This will perform a shallow copy of the <code>DeveloperContext</code>. */
public Builder(EncryptionContext context) {
tableName = context.getTableName();
attributeValues = context.getAttributeValues();
modeledClass = context.getModeledClass();
developerContext = context.getDeveloperContext();
hashKeyName = context.getHashKeyName();
rangeKeyName = context.getRangeKeyName();
materialDescription = context.getMaterialDescription();
}
public EncryptionContext build() {
return new EncryptionContext(this);
}
public Builder withTableName(String tableName) {
this.tableName = tableName;
return this;
}
public Builder withAttributeValues(Map<String, AttributeValue> attributeValues) {
this.attributeValues =
Collections.unmodifiableMap(new HashMap<String, AttributeValue>(attributeValues));
return this;
}
public Builder withModeledClass(Class<?> modeledClass) {
this.modeledClass = modeledClass;
return this;
}
public Builder withDeveloperContext(Object developerContext) {
this.developerContext = developerContext;
return this;
}
public Builder withHashKeyName(String hashKeyName) {
this.hashKeyName = hashKeyName;
return this;
}
public Builder withRangeKeyName(String rangeKeyName) {
this.rangeKeyName = rangeKeyName;
return this;
}
public Builder withMaterialDescription(Map<String, String> materialDescription) {
this.materialDescription =
Collections.unmodifiableMap(new HashMap<String, String>(materialDescription));
return this;
}
public String getTableName() {
return tableName;
}
public Map<String, AttributeValue> getAttributeValues() {
return attributeValues;
}
public Class<?> getModeledClass() {
return modeledClass;
}
public Object getDeveloperContext() {
return developerContext;
}
public String getHashKeyName() {
return hashKeyName;
}
public String getRangeKeyName() {
return rangeKeyName;
}
public Map<String, String> getMaterialDescription() {
return materialDescription;
}
}
@Override
public String toString() {
return "EncryptionContext [tableName="
+ tableName
+ ", attributeValues="
+ attributeValues
+ ", modeledClass="
+ modeledClass
+ ", developerContext="
+ developerContext
+ ", hashKeyName="
+ hashKeyName
+ ", rangeKeyName="
+ rangeKeyName
+ ", materialDescription="
+ materialDescription
+ "]";
}
}
| 5,051 |
0 | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/main/sdkv1/com/amazonaws/services/dynamodbv2/datamodeling | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/main/sdkv1/com/amazonaws/services/dynamodbv2/datamodeling/encryption/DelegatedKey.java | /*
* Copyright 2014 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.services.dynamodbv2.datamodeling.encryption;
import java.security.GeneralSecurityException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
/**
* Identifies keys which should not be used directly with {@link Cipher} but instead contain their
* own cryptographic logic. This can be used to wrap more complex logic, HSM integration, or
* service-calls.
*
* <p>Most delegated keys will only support a subset of these operations. (For example, AES keys
* will generally not support {@link #sign(byte[], String)} or {@link #verify(byte[], byte[],
* String)} and HMAC keys will generally not support anything except <code>sign</code> and <code>
* verify</code>.) {@link UnsupportedOperationException} should be thrown in these cases.
*
* @author Greg Rubin
*/
public interface DelegatedKey extends SecretKey {
/**
* Encrypts the provided plaintext and returns a byte-array containing the ciphertext.
*
* @param plainText
* @param additionalAssociatedData Optional additional data which must then also be provided for
* successful decryption. Both <code>null</code> and arrays of length 0 are treated
* identically. Not all keys will support this parameter.
* @param algorithm the transformation to be used when encrypting the data
* @return ciphertext the ciphertext produced by this encryption operation
* @throws UnsupportedOperationException if encryption is not supported or if <code>
* additionalAssociatedData</code> is provided, but not supported.
*/
public byte[] encrypt(byte[] plainText, byte[] additionalAssociatedData, String algorithm)
throws InvalidKeyException, IllegalBlockSizeException, BadPaddingException,
NoSuchAlgorithmException, NoSuchPaddingException;
/**
* Decrypts the provided ciphertext and returns a byte-array containing the plaintext.
*
* @param cipherText
* @param additionalAssociatedData Optional additional data which was provided during encryption.
* Both <code>null</code> and arrays of length 0 are treated identically. Not all keys will
* support this parameter.
* @param algorithm the transformation to be used when decrypting the data
* @return plaintext the result of decrypting the input ciphertext
* @throws UnsupportedOperationException if decryption is not supported or if <code>
* additionalAssociatedData</code> is provided, but not supported.
*/
public byte[] decrypt(byte[] cipherText, byte[] additionalAssociatedData, String algorithm)
throws InvalidKeyException, IllegalBlockSizeException, BadPaddingException,
NoSuchAlgorithmException, NoSuchPaddingException, InvalidAlgorithmParameterException;
/**
* Wraps (encrypts) the provided <code>key</code> to make it safe for storage or transmission.
*
* @param key
* @param additionalAssociatedData Optional additional data which must then also be provided for
* successful unwrapping. Both <code>null</code> and arrays of length 0 are treated
* identically. Not all keys will support this parameter.
* @param algorithm the transformation to be used when wrapping the key
* @return the wrapped key
* @throws UnsupportedOperationException if wrapping is not supported or if <code>
* additionalAssociatedData</code> is provided, but not supported.
*/
public byte[] wrap(Key key, byte[] additionalAssociatedData, String algorithm)
throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException,
IllegalBlockSizeException;
/**
* Unwraps (decrypts) the provided <code>wrappedKey</code> to recover the original key.
*
* @param wrappedKey
* @param additionalAssociatedData Optional additional data which was provided during wrapping.
* Both <code>null</code> and arrays of length 0 are treated identically. Not all keys will
* support this parameter.
* @param algorithm the transformation to be used when unwrapping the key
* @return the unwrapped key
* @throws UnsupportedOperationException if wrapping is not supported or if <code>
* additionalAssociatedData</code> is provided, but not supported.
*/
public Key unwrap(
byte[] wrappedKey,
String wrappedKeyAlgorithm,
int wrappedKeyType,
byte[] additionalAssociatedData,
String algorithm)
throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException;
/**
* Calculates and returns a signature for <code>dataToSign</code>.
*
* @param dataToSign
* @param algorithm
* @return the signature
* @throws UnsupportedOperationException if signing is not supported
*/
public byte[] sign(byte[] dataToSign, String algorithm) throws GeneralSecurityException;
/**
* Checks the provided signature for correctness.
*
* @param dataToSign
* @param signature
* @param algorithm
* @return true if and only if the <code>signature</code> matches the <code>dataToSign</code>.
* @throws UnsupportedOperationException if signature validation is not supported
*/
public boolean verify(byte[] dataToSign, byte[] signature, String algorithm);
}
| 5,052 |
0 | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/main/sdkv1/com/amazonaws/services/dynamodbv2/datamodeling | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/main/sdkv1/com/amazonaws/services/dynamodbv2/datamodeling/encryption/EncryptionFlags.java | /*
* Copyright 2014 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.services.dynamodbv2.datamodeling.encryption;
/** @author Greg Rubin */
public enum EncryptionFlags {
ENCRYPT,
SIGN
}
| 5,053 |
0 | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/main/sdkv1/com/amazonaws/services/dynamodbv2/datamodeling | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/main/sdkv1/com/amazonaws/services/dynamodbv2/datamodeling/encryption/HandleUnknownAttributes.java | /*
* Copyright 2015 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.services.dynamodbv2.datamodeling.encryption;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Marker annotation that indicates that attributes found during unmarshalling that are in the
* DynamoDB item but not modeled in the mapper model class should be included in for
* decryption/signature verification. The default behavior (without this annotation) is to ignore
* them, which can lead to signature verification failures when attributes are removed from model
* classes.
*
* <p>If this annotation is added to a class with @DoNotEncrypt, then the unknown attributes will
* only be included in the signature calculation, and if it's added to a class with default
* encryption behavior, the unknown attributes will be signed and decrypted.
*
* <p>For guidance on performing a safe data model change procedure, please see <a
* href="https://docs.aws.amazon.com/dynamodb-encryption-client/latest/devguide/data-model.html"
* target="_blank"> DynamoDB Encryption Client Developer Guide: Changing your data model</a>
*
* @author Dan Cavallaro
*/
@Target(value = {ElementType.TYPE})
@Retention(value = RetentionPolicy.RUNTIME)
public @interface HandleUnknownAttributes {}
| 5,054 |
0 | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/main/sdkv1/com/amazonaws/services/dynamodbv2/datamodeling/encryption | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/main/sdkv1/com/amazonaws/services/dynamodbv2/datamodeling/encryption/materials/WrappedRawMaterials.java | /*
* Copyright 2014 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.services.dynamodbv2.datamodeling.encryption.materials;
import com.amazonaws.services.dynamodbv2.datamodeling.encryption.DelegatedKey;
import com.amazonaws.services.dynamodbv2.datamodeling.internal.Base64;
import com.amazonaws.services.dynamodbv2.datamodeling.internal.Utils;
import java.security.GeneralSecurityException;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.KeyPair;
import java.security.NoSuchAlgorithmException;
import java.util.Collections;
import java.util.Map;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
/**
* Represents cryptographic materials used to manage unique record-level keys. This class
* specifically implements Envelope Encryption where a unique content key is randomly generated each
* time this class is constructed which is then encrypted with the Wrapping Key and then persisted
* in the Description. If a wrapped key is present in the Description, then that content key is
* unwrapped and used to decrypt the actual data in the record.
*
* <p>Other possibly implementations might use a Key-Derivation Function to derive a unique key per
* record.
*
* @author Greg Rubin
*/
public class WrappedRawMaterials extends AbstractRawMaterials {
/**
* The key-name in the Description which contains the algorithm use to wrap content key. Example
* values are "AESWrap", or "RSA/ECB/OAEPWithSHA-256AndMGF1Padding".
*/
public static final String KEY_WRAPPING_ALGORITHM = "amzn-ddb-wrap-alg";
/**
* The key-name in the Description which contains the algorithm used by the content key. Example
* values are "AES", or "Blowfish".
*/
public static final String CONTENT_KEY_ALGORITHM = "amzn-ddb-env-alg";
/** The key-name in the Description which which contains the wrapped content key. */
public static final String ENVELOPE_KEY = "amzn-ddb-env-key";
private static final String DEFAULT_ALGORITHM = "AES/256";
protected final Key wrappingKey;
protected final Key unwrappingKey;
private final SecretKey envelopeKey;
public WrappedRawMaterials(Key wrappingKey, Key unwrappingKey, KeyPair signingPair)
throws GeneralSecurityException {
this(wrappingKey, unwrappingKey, signingPair, Collections.<String, String>emptyMap());
}
public WrappedRawMaterials(
Key wrappingKey, Key unwrappingKey, KeyPair signingPair, Map<String, String> description)
throws GeneralSecurityException {
super(signingPair, description);
this.wrappingKey = wrappingKey;
this.unwrappingKey = unwrappingKey;
this.envelopeKey = initEnvelopeKey();
}
public WrappedRawMaterials(Key wrappingKey, Key unwrappingKey, SecretKey macKey)
throws GeneralSecurityException {
this(wrappingKey, unwrappingKey, macKey, Collections.<String, String>emptyMap());
}
public WrappedRawMaterials(
Key wrappingKey, Key unwrappingKey, SecretKey macKey, Map<String, String> description)
throws GeneralSecurityException {
super(macKey, description);
this.wrappingKey = wrappingKey;
this.unwrappingKey = unwrappingKey;
this.envelopeKey = initEnvelopeKey();
}
@Override
public SecretKey getDecryptionKey() {
return envelopeKey;
}
@Override
public SecretKey getEncryptionKey() {
return envelopeKey;
}
/**
* Called by the constructors. If there is already a key associated with this record (usually
* signified by a value stored in the description in the key {@link #ENVELOPE_KEY}) it extracts it
* and returns it. Otherwise it generates a new key, stores a wrapped version in the Description,
* and returns the key to the caller.
*
* @return the content key (which is returned by both {@link #getDecryptionKey()} and {@link
* #getEncryptionKey()}.
* @throws GeneralSecurityException
*/
protected SecretKey initEnvelopeKey() throws GeneralSecurityException {
Map<String, String> description = getMaterialDescription();
if (description.containsKey(ENVELOPE_KEY)) {
if (unwrappingKey == null) {
throw new IllegalStateException("No private decryption key provided.");
}
byte[] encryptedKey = Base64.decode(description.get(ENVELOPE_KEY));
String wrappingAlgorithm = unwrappingKey.getAlgorithm();
if (description.containsKey(KEY_WRAPPING_ALGORITHM)) {
wrappingAlgorithm = description.get(KEY_WRAPPING_ALGORITHM);
}
return unwrapKey(description, encryptedKey, wrappingAlgorithm);
} else {
SecretKey key =
description.containsKey(CONTENT_KEY_ALGORITHM)
? generateContentKey(description.get(CONTENT_KEY_ALGORITHM))
: generateContentKey(DEFAULT_ALGORITHM);
String wrappingAlg =
description.containsKey(KEY_WRAPPING_ALGORITHM)
? description.get(KEY_WRAPPING_ALGORITHM)
: getTransformation(wrappingKey.getAlgorithm());
byte[] encryptedKey = wrapKey(key, wrappingAlg);
description.put(ENVELOPE_KEY, Base64.encodeToString(encryptedKey));
description.put(CONTENT_KEY_ALGORITHM, key.getAlgorithm());
description.put(KEY_WRAPPING_ALGORITHM, wrappingAlg);
setMaterialDescription(description);
return key;
}
}
public byte[] wrapKey(SecretKey key, String wrappingAlg)
throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException,
IllegalBlockSizeException {
if (wrappingKey instanceof DelegatedKey) {
return ((DelegatedKey) wrappingKey).wrap(key, null, wrappingAlg);
} else {
Cipher cipher = Cipher.getInstance(wrappingAlg);
cipher.init(Cipher.WRAP_MODE, wrappingKey, Utils.getRng());
byte[] encryptedKey = cipher.wrap(key);
return encryptedKey;
}
}
protected SecretKey unwrapKey(
Map<String, String> description, byte[] encryptedKey, String wrappingAlgorithm)
throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException {
if (unwrappingKey instanceof DelegatedKey) {
return (SecretKey)
((DelegatedKey) unwrappingKey)
.unwrap(
encryptedKey,
description.get(CONTENT_KEY_ALGORITHM),
Cipher.SECRET_KEY,
null,
wrappingAlgorithm);
} else {
Cipher cipher = Cipher.getInstance(wrappingAlgorithm);
// This can be of the form "AES/256" as well as "AES" e.g.,
// but we want to set the SecretKey with just "AES" in either case
String[] algPieces = description.get(CONTENT_KEY_ALGORITHM).split("/", 2);
String contentKeyAlgorithm = algPieces[0];
cipher.init(Cipher.UNWRAP_MODE, unwrappingKey, Utils.getRng());
return (SecretKey) cipher.unwrap(encryptedKey, contentKeyAlgorithm, Cipher.SECRET_KEY);
}
}
protected SecretKey generateContentKey(final String algorithm) throws NoSuchAlgorithmException {
String[] pieces = algorithm.split("/", 2);
KeyGenerator kg = KeyGenerator.getInstance(pieces[0]);
int keyLen = 0;
if (pieces.length == 2) {
try {
keyLen = Integer.parseInt(pieces[1]);
} catch (NumberFormatException ex) {
keyLen = 0;
}
}
if (keyLen > 0) {
kg.init(keyLen, Utils.getRng());
} else {
kg.init(Utils.getRng());
}
return kg.generateKey();
}
private static String getTransformation(final String algorithm) {
if (algorithm.equalsIgnoreCase("RSA")) {
return "RSA/ECB/OAEPWithSHA-256AndMGF1Padding";
} else if (algorithm.equalsIgnoreCase("AES")) {
return "AESWrap";
} else {
return algorithm;
}
}
}
| 5,055 |
0 | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/main/sdkv1/com/amazonaws/services/dynamodbv2/datamodeling/encryption | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/main/sdkv1/com/amazonaws/services/dynamodbv2/datamodeling/encryption/materials/AbstractRawMaterials.java | /*
* Copyright 2014 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.services.dynamodbv2.datamodeling.encryption.materials;
import java.security.Key;
import java.security.KeyPair;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import javax.crypto.SecretKey;
/** @author Greg Rubin */
public abstract class AbstractRawMaterials implements DecryptionMaterials, EncryptionMaterials {
private Map<String, String> description;
private final Key signingKey;
private final Key verificationKey;
@SuppressWarnings("unchecked")
protected AbstractRawMaterials(KeyPair signingPair) {
this(signingPair, Collections.EMPTY_MAP);
}
protected AbstractRawMaterials(KeyPair signingPair, Map<String, String> description) {
this.signingKey = signingPair.getPrivate();
this.verificationKey = signingPair.getPublic();
setMaterialDescription(description);
}
@SuppressWarnings("unchecked")
protected AbstractRawMaterials(SecretKey macKey) {
this(macKey, Collections.EMPTY_MAP);
}
protected AbstractRawMaterials(SecretKey macKey, Map<String, String> description) {
this.signingKey = macKey;
this.verificationKey = macKey;
this.description = Collections.unmodifiableMap(new HashMap<String, String>(description));
}
@Override
public Map<String, String> getMaterialDescription() {
return new HashMap<String, String>(description);
}
public void setMaterialDescription(Map<String, String> description) {
this.description = Collections.unmodifiableMap(new HashMap<String, String>(description));
}
@Override
public Key getSigningKey() {
return signingKey;
}
@Override
public Key getVerificationKey() {
return verificationKey;
}
}
| 5,056 |
0 | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/main/sdkv1/com/amazonaws/services/dynamodbv2/datamodeling/encryption | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/main/sdkv1/com/amazonaws/services/dynamodbv2/datamodeling/encryption/materials/EncryptionMaterials.java | /*
* Copyright 2014 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.services.dynamodbv2.datamodeling.encryption.materials;
import java.security.Key;
import javax.crypto.SecretKey;
/** @author Greg Rubin */
public interface EncryptionMaterials extends CryptographicMaterials {
public SecretKey getEncryptionKey();
public Key getSigningKey();
}
| 5,057 |
0 | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/main/sdkv1/com/amazonaws/services/dynamodbv2/datamodeling/encryption | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/main/sdkv1/com/amazonaws/services/dynamodbv2/datamodeling/encryption/materials/AsymmetricRawMaterials.java | /*
* Copyright 2014 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.services.dynamodbv2.datamodeling.encryption.materials;
import java.security.GeneralSecurityException;
import java.security.KeyPair;
import java.util.Collections;
import java.util.Map;
import javax.crypto.SecretKey;
/** @author Greg Rubin */
public class AsymmetricRawMaterials extends WrappedRawMaterials {
@SuppressWarnings("unchecked")
public AsymmetricRawMaterials(KeyPair encryptionKey, KeyPair signingPair)
throws GeneralSecurityException {
this(encryptionKey, signingPair, Collections.EMPTY_MAP);
}
public AsymmetricRawMaterials(
KeyPair encryptionKey, KeyPair signingPair, Map<String, String> description)
throws GeneralSecurityException {
super(encryptionKey.getPublic(), encryptionKey.getPrivate(), signingPair, description);
}
@SuppressWarnings("unchecked")
public AsymmetricRawMaterials(KeyPair encryptionKey, SecretKey macKey)
throws GeneralSecurityException {
this(encryptionKey, macKey, Collections.EMPTY_MAP);
}
public AsymmetricRawMaterials(
KeyPair encryptionKey, SecretKey macKey, Map<String, String> description)
throws GeneralSecurityException {
super(encryptionKey.getPublic(), encryptionKey.getPrivate(), macKey, description);
}
}
| 5,058 |
0 | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/main/sdkv1/com/amazonaws/services/dynamodbv2/datamodeling/encryption | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/main/sdkv1/com/amazonaws/services/dynamodbv2/datamodeling/encryption/materials/SymmetricRawMaterials.java | /*
* Copyright 2014 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.services.dynamodbv2.datamodeling.encryption.materials;
import java.security.KeyPair;
import java.util.Collections;
import java.util.Map;
import javax.crypto.SecretKey;
/** @author Greg Rubin */
public class SymmetricRawMaterials extends AbstractRawMaterials {
private final SecretKey cryptoKey;
@SuppressWarnings("unchecked")
public SymmetricRawMaterials(SecretKey encryptionKey, KeyPair signingPair) {
this(encryptionKey, signingPair, Collections.EMPTY_MAP);
}
public SymmetricRawMaterials(
SecretKey encryptionKey, KeyPair signingPair, Map<String, String> description) {
super(signingPair, description);
this.cryptoKey = encryptionKey;
}
@SuppressWarnings("unchecked")
public SymmetricRawMaterials(SecretKey encryptionKey, SecretKey macKey) {
this(encryptionKey, macKey, Collections.EMPTY_MAP);
}
public SymmetricRawMaterials(
SecretKey encryptionKey, SecretKey macKey, Map<String, String> description) {
super(macKey, description);
this.cryptoKey = encryptionKey;
}
@Override
public SecretKey getEncryptionKey() {
return cryptoKey;
}
@Override
public SecretKey getDecryptionKey() {
return cryptoKey;
}
}
| 5,059 |
0 | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/main/sdkv1/com/amazonaws/services/dynamodbv2/datamodeling/encryption | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/main/sdkv1/com/amazonaws/services/dynamodbv2/datamodeling/encryption/materials/DecryptionMaterials.java | /*
* Copyright 2014 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.services.dynamodbv2.datamodeling.encryption.materials;
import java.security.Key;
import javax.crypto.SecretKey;
/** @author Greg Rubin */
public interface DecryptionMaterials extends CryptographicMaterials {
public SecretKey getDecryptionKey();
public Key getVerificationKey();
}
| 5,060 |
0 | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/main/sdkv1/com/amazonaws/services/dynamodbv2/datamodeling/encryption | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/main/sdkv1/com/amazonaws/services/dynamodbv2/datamodeling/encryption/materials/CryptographicMaterials.java | /*
* Copyright 2014 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.services.dynamodbv2.datamodeling.encryption.materials;
import java.util.Map;
/** @author Greg Rubin */
public interface CryptographicMaterials {
public Map<String, String> getMaterialDescription();
}
| 5,061 |
0 | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/main/sdkv1/com/amazonaws/services/dynamodbv2/datamodeling/encryption | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/main/sdkv1/com/amazonaws/services/dynamodbv2/datamodeling/encryption/providers/SymmetricStaticProvider.java | /*
* Copyright 2014 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.services.dynamodbv2.datamodeling.encryption.providers;
import com.amazonaws.services.dynamodbv2.datamodeling.encryption.EncryptionContext;
import com.amazonaws.services.dynamodbv2.datamodeling.encryption.materials.CryptographicMaterials;
import com.amazonaws.services.dynamodbv2.datamodeling.encryption.materials.DecryptionMaterials;
import com.amazonaws.services.dynamodbv2.datamodeling.encryption.materials.EncryptionMaterials;
import com.amazonaws.services.dynamodbv2.datamodeling.encryption.materials.SymmetricRawMaterials;
import java.security.KeyPair;
import java.util.Collections;
import java.util.Map;
import javax.crypto.SecretKey;
/**
* A provider which always returns the same provided symmetric encryption/decryption key and the
* same signing/verification key(s).
*
* @author Greg Rubin
*/
public class SymmetricStaticProvider implements EncryptionMaterialsProvider {
private final SymmetricRawMaterials materials;
/**
* @param encryptionKey the value to be returned by {@link
* #getEncryptionMaterials(EncryptionContext)} and {@link
* #getDecryptionMaterials(EncryptionContext)}
* @param signingPair the keypair used to sign/verify the data stored in Dynamo. If only the
* public key is provided, then this provider may be used for decryption, but not encryption.
*/
public SymmetricStaticProvider(SecretKey encryptionKey, KeyPair signingPair) {
this(encryptionKey, signingPair, Collections.<String, String>emptyMap());
}
/**
* @param encryptionKey the value to be returned by {@link
* #getEncryptionMaterials(EncryptionContext)} and {@link
* #getDecryptionMaterials(EncryptionContext)}
* @param signingPair the keypair used to sign/verify the data stored in Dynamo. If only the
* public key is provided, then this provider may be used for decryption, but not encryption.
* @param description the value to be returned by {@link
* CryptographicMaterials#getMaterialDescription()} for any {@link CryptographicMaterials}
* returned by this object.
*/
public SymmetricStaticProvider(
SecretKey encryptionKey, KeyPair signingPair, Map<String, String> description) {
materials = new SymmetricRawMaterials(encryptionKey, signingPair, description);
}
/**
* @param encryptionKey the value to be returned by {@link
* #getEncryptionMaterials(EncryptionContext)} and {@link
* #getDecryptionMaterials(EncryptionContext)}
* @param macKey the key used to sign/verify the data stored in Dynamo.
*/
public SymmetricStaticProvider(SecretKey encryptionKey, SecretKey macKey) {
this(encryptionKey, macKey, Collections.<String, String>emptyMap());
}
/**
* @param encryptionKey the value to be returned by {@link
* #getEncryptionMaterials(EncryptionContext)} and {@link
* #getDecryptionMaterials(EncryptionContext)}
* @param macKey the key used to sign/verify the data stored in Dynamo.
* @param description the value to be returned by {@link
* CryptographicMaterials#getMaterialDescription()} for any {@link CryptographicMaterials}
* returned by this object.
*/
public SymmetricStaticProvider(
SecretKey encryptionKey, SecretKey macKey, Map<String, String> description) {
materials = new SymmetricRawMaterials(encryptionKey, macKey, description);
}
/**
* Returns the <code>encryptionKey</code> provided to the constructor if and only if <code>
* materialDescription</code> is a super-set (may be equal) to the <code>description</code>
* provided to the constructor.
*/
@Override
public DecryptionMaterials getDecryptionMaterials(EncryptionContext context) {
if (context
.getMaterialDescription()
.entrySet()
.containsAll(materials.getMaterialDescription().entrySet())) {
return materials;
} else {
return null;
}
}
/** Returns the <code>encryptionKey</code> provided to the constructor. */
@Override
public EncryptionMaterials getEncryptionMaterials(EncryptionContext context) {
return materials;
}
/** Does nothing. */
@Override
public void refresh() {
// Do Nothing
}
}
| 5,062 |
0 | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/main/sdkv1/com/amazonaws/services/dynamodbv2/datamodeling/encryption | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/main/sdkv1/com/amazonaws/services/dynamodbv2/datamodeling/encryption/providers/WrappedMaterialsProvider.java | /*
* Copyright 2014 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.services.dynamodbv2.datamodeling.encryption.providers;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMappingException;
import com.amazonaws.services.dynamodbv2.datamodeling.encryption.EncryptionContext;
import com.amazonaws.services.dynamodbv2.datamodeling.encryption.materials.CryptographicMaterials;
import com.amazonaws.services.dynamodbv2.datamodeling.encryption.materials.DecryptionMaterials;
import com.amazonaws.services.dynamodbv2.datamodeling.encryption.materials.EncryptionMaterials;
import com.amazonaws.services.dynamodbv2.datamodeling.encryption.materials.WrappedRawMaterials;
import java.security.GeneralSecurityException;
import java.security.Key;
import java.security.KeyPair;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import javax.crypto.SecretKey;
/**
* This provider will use create a unique (random) symmetric key upon each call to {@link
* #getEncryptionMaterials(EncryptionContext)}. Practically, this means each record in DynamoDB will
* be encrypted under a unique record key. A wrapped/encrypted copy of this record key is stored in
* the MaterialsDescription field of that record and is unwrapped/decrypted upon reading that
* record.
*
* <p>This is generally a more secure way of encrypting data than with the {@link
* SymmetricStaticProvider}.
*
* @see WrappedRawMaterials
* @author Greg Rubin
*/
public class WrappedMaterialsProvider implements EncryptionMaterialsProvider {
private final Key wrappingKey;
private final Key unwrappingKey;
private final KeyPair sigPair;
private final SecretKey macKey;
private final Map<String, String> description;
/**
* @param wrappingKey The key used to wrap/encrypt the symmetric record key. (May be the same as
* the <code>unwrappingKey</code>.)
* @param unwrappingKey The key used to unwrap/decrypt the symmetric record key. (May be the same
* as the <code>wrappingKey</code>.) If null, then this provider may only be used for
* decryption, but not encryption.
* @param signingPair the keypair used to sign/verify the data stored in Dynamo. If only the
* public key is provided, then this provider may only be used for decryption, but not
* encryption.
*/
public WrappedMaterialsProvider(Key wrappingKey, Key unwrappingKey, KeyPair signingPair) {
this(wrappingKey, unwrappingKey, signingPair, Collections.<String, String>emptyMap());
}
/**
* @param wrappingKey The key used to wrap/encrypt the symmetric record key. (May be the same as
* the <code>unwrappingKey</code>.)
* @param unwrappingKey The key used to unwrap/decrypt the symmetric record key. (May be the same
* as the <code>wrappingKey</code>.) If null, then this provider may only be used for
* decryption, but not encryption.
* @param signingPair the keypair used to sign/verify the data stored in Dynamo. If only the
* public key is provided, then this provider may only be used for decryption, but not
* encryption.
* @param description description the value to be returned by {@link
* CryptographicMaterials#getMaterialDescription()} for any {@link CryptographicMaterials}
* returned by this object.
*/
public WrappedMaterialsProvider(
Key wrappingKey, Key unwrappingKey, KeyPair signingPair, Map<String, String> description) {
this.wrappingKey = wrappingKey;
this.unwrappingKey = unwrappingKey;
this.sigPair = signingPair;
this.macKey = null;
this.description = Collections.unmodifiableMap(new HashMap<String, String>(description));
}
/**
* @param wrappingKey The key used to wrap/encrypt the symmetric record key. (May be the same as
* the <code>unwrappingKey</code>.)
* @param unwrappingKey The key used to unwrap/decrypt the symmetric record key. (May be the same
* as the <code>wrappingKey</code>.) If null, then this provider may only be used for
* decryption, but not encryption.
* @param macKey the key used to sign/verify the data stored in Dynamo.
*/
public WrappedMaterialsProvider(Key wrappingKey, Key unwrappingKey, SecretKey macKey) {
this(wrappingKey, unwrappingKey, macKey, Collections.<String, String>emptyMap());
}
/**
* @param wrappingKey The key used to wrap/encrypt the symmetric record key. (May be the same as
* the <code>unwrappingKey</code>.)
* @param unwrappingKey The key used to unwrap/decrypt the symmetric record key. (May be the same
* as the <code>wrappingKey</code>.) If null, then this provider may only be used for
* decryption, but not encryption.
* @param macKey the key used to sign/verify the data stored in Dynamo.
* @param description description the value to be returned by {@link
* CryptographicMaterials#getMaterialDescription()} for any {@link CryptographicMaterials}
* returned by this object.
*/
public WrappedMaterialsProvider(
Key wrappingKey, Key unwrappingKey, SecretKey macKey, Map<String, String> description) {
this.wrappingKey = wrappingKey;
this.unwrappingKey = unwrappingKey;
this.sigPair = null;
this.macKey = macKey;
this.description = Collections.unmodifiableMap(new HashMap<String, String>(description));
}
@Override
public DecryptionMaterials getDecryptionMaterials(EncryptionContext context) {
try {
if (macKey != null) {
return new WrappedRawMaterials(
wrappingKey, unwrappingKey, macKey, context.getMaterialDescription());
} else {
return new WrappedRawMaterials(
wrappingKey, unwrappingKey, sigPair, context.getMaterialDescription());
}
} catch (GeneralSecurityException ex) {
throw new DynamoDBMappingException("Unable to decrypt envelope key", ex);
}
}
@Override
public EncryptionMaterials getEncryptionMaterials(EncryptionContext context) {
try {
if (macKey != null) {
return new WrappedRawMaterials(wrappingKey, unwrappingKey, macKey, description);
} else {
return new WrappedRawMaterials(wrappingKey, unwrappingKey, sigPair, description);
}
} catch (GeneralSecurityException ex) {
throw new DynamoDBMappingException("Unable to encrypt envelope key", ex);
}
}
@Override
public void refresh() {
// Do nothing
}
}
| 5,063 |
0 | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/main/sdkv1/com/amazonaws/services/dynamodbv2/datamodeling/encryption | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/main/sdkv1/com/amazonaws/services/dynamodbv2/datamodeling/encryption/providers/CachingMostRecentProvider.java | // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package com.amazonaws.services.dynamodbv2.datamodeling.encryption.providers;
import static com.amazonaws.services.dynamodbv2.datamodeling.internal.Utils.checkNotNull;
import com.amazonaws.services.dynamodbv2.datamodeling.encryption.EncryptionContext;
import com.amazonaws.services.dynamodbv2.datamodeling.encryption.materials.DecryptionMaterials;
import com.amazonaws.services.dynamodbv2.datamodeling.encryption.materials.EncryptionMaterials;
import com.amazonaws.services.dynamodbv2.datamodeling.encryption.providers.store.ProviderStore;
import com.amazonaws.services.dynamodbv2.datamodeling.internal.TTLCache;
import com.amazonaws.services.dynamodbv2.datamodeling.internal.TTLCache.EntryLoader;
import java.util.concurrent.TimeUnit;
/**
* This meta-Provider encrypts data with the most recent version of keying materials from a {@link
* ProviderStore} and decrypts using whichever version is appropriate. It also caches the results
* from the {@link ProviderStore} to avoid excessive load on the backing systems.
*/
public class CachingMostRecentProvider implements EncryptionMaterialsProvider {
private static final long INITIAL_VERSION = 0;
private static final String PROVIDER_CACHE_KEY_DELIM = "#";
private static final int DEFAULT_CACHE_MAX_SIZE = 1000;
private final long ttlInNanos;
private final ProviderStore keystore;
protected final String defaultMaterialName;
private final TTLCache<EncryptionMaterialsProvider> providerCache;
private final TTLCache<Long> versionCache;
private final EntryLoader<Long> versionLoader =
new EntryLoader<Long>() {
@Override
public Long load(String entryKey) {
return keystore.getMaxVersion(entryKey);
}
};
private final EntryLoader<EncryptionMaterialsProvider> providerLoader =
new EntryLoader<EncryptionMaterialsProvider>() {
@Override
public EncryptionMaterialsProvider load(String entryKey) {
final String[] parts = entryKey.split(PROVIDER_CACHE_KEY_DELIM, 2);
if (parts.length != 2) {
throw new IllegalStateException("Invalid cache key for provider cache: " + entryKey);
}
return keystore.getProvider(parts[0], Long.parseLong(parts[1]));
}
};
/**
* Creates a new {@link CachingMostRecentProvider}.
*
* @param keystore The key store that this provider will use to determine which material and which
* version of material to use
* @param materialName The name of the materials associated with this provider
* @param ttlInMillis The length of time in milliseconds to cache the most recent provider
*/
public CachingMostRecentProvider(
final ProviderStore keystore, final String materialName, final long ttlInMillis) {
this(keystore, materialName, ttlInMillis, DEFAULT_CACHE_MAX_SIZE);
}
/**
* Creates a new {@link CachingMostRecentProvider}.
*
* @param keystore The key store that this provider will use to determine which material and which
* version of material to use
* @param materialName The name of the materials associated with this provider
* @param ttlInMillis The length of time in milliseconds to cache the most recent provider
* @param maxCacheSize The maximum size of the underlying caches this provider uses. Entries will
* be evicted from the cache once this size is exceeded.
*/
public CachingMostRecentProvider(
final ProviderStore keystore,
final String materialName,
final long ttlInMillis,
final int maxCacheSize) {
this.keystore = checkNotNull(keystore, "keystore must not be null");
this.defaultMaterialName = materialName;
this.ttlInNanos = TimeUnit.MILLISECONDS.toNanos(ttlInMillis);
this.providerCache = new TTLCache<>(maxCacheSize, ttlInMillis, providerLoader);
this.versionCache = new TTLCache<>(maxCacheSize, ttlInMillis, versionLoader);
}
@Override
public EncryptionMaterials getEncryptionMaterials(EncryptionContext context) {
final String materialName = getMaterialName(context);
final long currentVersion = versionCache.load(materialName);
if (currentVersion < 0) {
// The material hasn't been created yet, so specify a loading function
// to create the first version of materials and update both caches.
// We want this to be done as part of the cache load to ensure that this logic
// only happens once in a multithreaded environment,
// in order to limit calls to the keystore's dependencies.
final String cacheKey = buildCacheKey(materialName, INITIAL_VERSION);
EncryptionMaterialsProvider newProvider =
providerCache.load(
cacheKey,
s -> {
// Create the new material in the keystore
final String[] parts = s.split(PROVIDER_CACHE_KEY_DELIM, 2);
if (parts.length != 2) {
throw new IllegalStateException("Invalid cache key for provider cache: " + s);
}
EncryptionMaterialsProvider provider =
keystore.getOrCreate(parts[0], Long.parseLong(parts[1]));
// We now should have version 0 in our keystore.
// Update the version cache for this material as a side effect
versionCache.put(materialName, INITIAL_VERSION);
// Return the new materials to be put into the cache
return provider;
});
return newProvider.getEncryptionMaterials(context);
} else {
final String cacheKey = buildCacheKey(materialName, currentVersion);
return providerCache.load(cacheKey).getEncryptionMaterials(context);
}
}
public DecryptionMaterials getDecryptionMaterials(EncryptionContext context) {
final long version =
keystore.getVersionFromMaterialDescription(context.getMaterialDescription());
final String materialName = getMaterialName(context);
final String cacheKey = buildCacheKey(materialName, version);
EncryptionMaterialsProvider provider = providerCache.load(cacheKey);
return provider.getDecryptionMaterials(context);
}
/** Completely empties the cache of both the current and old versions. */
@Override
public void refresh() {
versionCache.clear();
providerCache.clear();
}
public String getMaterialName() {
return defaultMaterialName;
}
public long getTtlInMills() {
return TimeUnit.NANOSECONDS.toMillis(ttlInNanos);
}
/**
* The current version of the materials being used for encryption. Returns -1 if we do not
* currently have a current version.
*/
public long getCurrentVersion() {
return versionCache.load(getMaterialName());
}
/**
* The last time the current version was updated. Returns 0 if we do not currently have a current
* version.
*/
public long getLastUpdated() {
// We cache a version of -1 to mean that there is not a current version
if (versionCache.load(getMaterialName()) < 0) {
return 0;
}
// Otherwise, return the last update time of that entry
return TimeUnit.NANOSECONDS.toMillis(versionCache.getLastUpdated(getMaterialName()));
}
protected String getMaterialName(final EncryptionContext context) {
return defaultMaterialName;
}
private static String buildCacheKey(final String materialName, final long version) {
StringBuilder result = new StringBuilder(materialName);
result.append(PROVIDER_CACHE_KEY_DELIM);
result.append(version);
return result.toString();
}
}
| 5,064 |
0 | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/main/sdkv1/com/amazonaws/services/dynamodbv2/datamodeling/encryption | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/main/sdkv1/com/amazonaws/services/dynamodbv2/datamodeling/encryption/providers/EncryptionMaterialsProvider.java | /*
* Copyright 2014 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.services.dynamodbv2.datamodeling.encryption.providers;
import com.amazonaws.services.dynamodbv2.datamodeling.encryption.EncryptionContext;
import com.amazonaws.services.dynamodbv2.datamodeling.encryption.materials.DecryptionMaterials;
import com.amazonaws.services.dynamodbv2.datamodeling.encryption.materials.EncryptionMaterials;
/**
* Interface for providing encryption materials. Implementations are free to use any strategy for
* providing encryption materials, such as simply providing static material that doesn't change, or
* more complicated implementations, such as integrating with existing key management systems.
*
* @author Greg Rubin
*/
public interface EncryptionMaterialsProvider {
/**
* Retrieves encryption materials matching the specified description from some source.
*
* @param context Information to assist in selecting a the proper return value. The implementation
* is free to determine the minimum necessary for successful processing.
* @return The encryption materials that match the description, or null if no matching encryption
* materials found.
*/
public DecryptionMaterials getDecryptionMaterials(EncryptionContext context);
/**
* Returns EncryptionMaterials which the caller can use for encryption. Each implementation of
* EncryptionMaterialsProvider can choose its own strategy for loading encryption material. For
* example, an implementation might load encryption material from an existing key management
* system, or load new encryption material when keys are rotated.
*
* @param context Information to assist in selecting a the proper return value. The implementation
* is free to determine the minimum necessary for successful processing.
* @return EncryptionMaterials which the caller can use to encrypt or decrypt data.
*/
public EncryptionMaterials getEncryptionMaterials(EncryptionContext context);
/**
* Forces this encryption materials provider to refresh its encryption material. For many
* implementations of encryption materials provider, this may simply be a no-op, such as any
* encryption materials provider implementation that vends static/non-changing encryption
* material. For other implementations that vend different encryption material throughout their
* lifetime, this method should force the encryption materials provider to refresh its encryption
* material.
*/
public void refresh();
}
| 5,065 |
0 | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/main/sdkv1/com/amazonaws/services/dynamodbv2/datamodeling/encryption | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/main/sdkv1/com/amazonaws/services/dynamodbv2/datamodeling/encryption/providers/KeyStoreMaterialsProvider.java | /*
* Copyright 2014 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.services.dynamodbv2.datamodeling.encryption.providers;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMappingException;
import com.amazonaws.services.dynamodbv2.datamodeling.encryption.EncryptionContext;
import com.amazonaws.services.dynamodbv2.datamodeling.encryption.materials.AsymmetricRawMaterials;
import com.amazonaws.services.dynamodbv2.datamodeling.encryption.materials.DecryptionMaterials;
import com.amazonaws.services.dynamodbv2.datamodeling.encryption.materials.EncryptionMaterials;
import com.amazonaws.services.dynamodbv2.datamodeling.encryption.materials.SymmetricRawMaterials;
import java.security.GeneralSecurityException;
import java.security.KeyPair;
import java.security.KeyStore;
import java.security.KeyStore.Entry;
import java.security.KeyStore.PrivateKeyEntry;
import java.security.KeyStore.ProtectionParameter;
import java.security.KeyStore.SecretKeyEntry;
import java.security.KeyStore.TrustedCertificateEntry;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.UnrecoverableEntryException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;
/** @author Greg Rubin */
public class KeyStoreMaterialsProvider implements EncryptionMaterialsProvider {
private final Map<String, String> description;
private final String encryptionAlias;
private final String signingAlias;
private final ProtectionParameter encryptionProtection;
private final ProtectionParameter signingProtection;
private final KeyStore keyStore;
private final AtomicReference<CurrentMaterials> currMaterials =
new AtomicReference<KeyStoreMaterialsProvider.CurrentMaterials>();
public KeyStoreMaterialsProvider(
KeyStore keyStore,
String encryptionAlias,
String signingAlias,
Map<String, String> description)
throws KeyStoreException, NoSuchAlgorithmException, UnrecoverableEntryException {
this(keyStore, encryptionAlias, signingAlias, null, null, description);
}
public KeyStoreMaterialsProvider(
KeyStore keyStore,
String encryptionAlias,
String signingAlias,
ProtectionParameter encryptionProtection,
ProtectionParameter signingProtection,
Map<String, String> description)
throws KeyStoreException, NoSuchAlgorithmException, UnrecoverableEntryException {
super();
this.keyStore = keyStore;
this.encryptionAlias = encryptionAlias;
this.signingAlias = signingAlias;
this.encryptionProtection = encryptionProtection;
this.signingProtection = signingProtection;
this.description = Collections.unmodifiableMap(new HashMap<String, String>(description));
validateKeys();
loadKeys();
}
@Override
public DecryptionMaterials getDecryptionMaterials(EncryptionContext context) {
CurrentMaterials materials = currMaterials.get();
if (context.getMaterialDescription().entrySet().containsAll(description.entrySet())) {
if (materials.encryptionEntry instanceof SecretKeyEntry) {
return materials.symRawMaterials;
} else {
try {
return makeAsymMaterials(materials, context.getMaterialDescription());
} catch (GeneralSecurityException ex) {
throw new DynamoDBMappingException("Unable to decrypt envelope key", ex);
}
}
} else {
return null;
}
}
@Override
public EncryptionMaterials getEncryptionMaterials(EncryptionContext context) {
CurrentMaterials materials = currMaterials.get();
if (materials.encryptionEntry instanceof SecretKeyEntry) {
return materials.symRawMaterials;
} else {
try {
return makeAsymMaterials(materials, description);
} catch (GeneralSecurityException ex) {
throw new DynamoDBMappingException("Unable to encrypt envelope key", ex);
}
}
}
private AsymmetricRawMaterials makeAsymMaterials(
CurrentMaterials materials, Map<String, String> description) throws GeneralSecurityException {
KeyPair encryptionPair = entry2Pair(materials.encryptionEntry);
if (materials.signingEntry instanceof SecretKeyEntry) {
return new AsymmetricRawMaterials(
encryptionPair, ((SecretKeyEntry) materials.signingEntry).getSecretKey(), description);
} else {
return new AsymmetricRawMaterials(
encryptionPair, entry2Pair(materials.signingEntry), description);
}
}
private static KeyPair entry2Pair(Entry entry) {
PublicKey pub = null;
PrivateKey priv = null;
if (entry instanceof PrivateKeyEntry) {
PrivateKeyEntry pk = (PrivateKeyEntry) entry;
if (pk.getCertificate() != null) {
pub = pk.getCertificate().getPublicKey();
}
priv = pk.getPrivateKey();
} else if (entry instanceof TrustedCertificateEntry) {
TrustedCertificateEntry tc = (TrustedCertificateEntry) entry;
pub = tc.getTrustedCertificate().getPublicKey();
} else {
throw new IllegalArgumentException(
"Only entry types PrivateKeyEntry and TrustedCertificateEntry are supported.");
}
return new KeyPair(pub, priv);
}
/**
* Reloads the keys from the underlying keystore by calling {@link KeyStore#getEntry(String,
* ProtectionParameter)} again for each of them.
*/
@Override
public void refresh() {
try {
loadKeys();
} catch (GeneralSecurityException ex) {
throw new DynamoDBMappingException("Unable to load keys from keystore", ex);
}
}
private void validateKeys() throws KeyStoreException {
if (!keyStore.containsAlias(encryptionAlias)) {
throw new IllegalArgumentException("Keystore does not contain alias: " + encryptionAlias);
}
if (!keyStore.containsAlias(signingAlias)) {
throw new IllegalArgumentException("Keystore does not contain alias: " + signingAlias);
}
}
private void loadKeys()
throws NoSuchAlgorithmException, UnrecoverableEntryException, KeyStoreException {
Entry encryptionEntry = keyStore.getEntry(encryptionAlias, encryptionProtection);
Entry signingEntry = keyStore.getEntry(signingAlias, signingProtection);
CurrentMaterials newMaterials = new CurrentMaterials(encryptionEntry, signingEntry);
currMaterials.set(newMaterials);
}
private class CurrentMaterials {
public final Entry encryptionEntry;
public final Entry signingEntry;
public final SymmetricRawMaterials symRawMaterials;
public CurrentMaterials(Entry encryptionEntry, Entry signingEntry) {
super();
this.encryptionEntry = encryptionEntry;
this.signingEntry = signingEntry;
if (encryptionEntry instanceof SecretKeyEntry) {
if (signingEntry instanceof SecretKeyEntry) {
this.symRawMaterials =
new SymmetricRawMaterials(
((SecretKeyEntry) encryptionEntry).getSecretKey(),
((SecretKeyEntry) signingEntry).getSecretKey(),
description);
} else {
this.symRawMaterials =
new SymmetricRawMaterials(
((SecretKeyEntry) encryptionEntry).getSecretKey(),
entry2Pair(signingEntry),
description);
}
} else {
this.symRawMaterials = null;
}
}
}
}
| 5,066 |
0 | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/main/sdkv1/com/amazonaws/services/dynamodbv2/datamodeling/encryption | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/main/sdkv1/com/amazonaws/services/dynamodbv2/datamodeling/encryption/providers/AsymmetricStaticProvider.java | /*
* Copyright 2014 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.services.dynamodbv2.datamodeling.encryption.providers;
import java.security.KeyPair;
import java.util.Collections;
import java.util.Map;
import javax.crypto.SecretKey;
/**
* This is a thin wrapper around the {@link WrappedMaterialsProvider}, using the provided <code>
* encryptionKey</code> for wrapping and unwrapping the record key. Please see that class for
* detailed documentation.
*
* @author Greg Rubin
*/
public class AsymmetricStaticProvider extends WrappedMaterialsProvider {
public AsymmetricStaticProvider(KeyPair encryptionKey, KeyPair signingPair) {
this(encryptionKey, signingPair, Collections.<String, String>emptyMap());
}
public AsymmetricStaticProvider(KeyPair encryptionKey, SecretKey macKey) {
this(encryptionKey, macKey, Collections.<String, String>emptyMap());
}
public AsymmetricStaticProvider(
KeyPair encryptionKey, KeyPair signingPair, Map<String, String> description) {
super(encryptionKey.getPublic(), encryptionKey.getPrivate(), signingPair, description);
}
public AsymmetricStaticProvider(
KeyPair encryptionKey, SecretKey macKey, Map<String, String> description) {
super(encryptionKey.getPublic(), encryptionKey.getPrivate(), macKey, description);
}
}
| 5,067 |
0 | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/main/sdkv1/com/amazonaws/services/dynamodbv2/datamodeling/encryption | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/main/sdkv1/com/amazonaws/services/dynamodbv2/datamodeling/encryption/providers/DirectKmsMaterialProvider.java | /*
* Copyright 2014 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.services.dynamodbv2.datamodeling.encryption.providers;
import static com.amazonaws.services.dynamodbv2.datamodeling.encryption.materials.WrappedRawMaterials.CONTENT_KEY_ALGORITHM;
import static com.amazonaws.services.dynamodbv2.datamodeling.encryption.materials.WrappedRawMaterials.ENVELOPE_KEY;
import static com.amazonaws.services.dynamodbv2.datamodeling.encryption.materials.WrappedRawMaterials.KEY_WRAPPING_ALGORITHM;
import static com.amazonaws.services.dynamodbv2.datamodeling.internal.Utils.loadVersion;
import com.amazonaws.AmazonWebServiceRequest;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMappingException;
import com.amazonaws.services.dynamodbv2.datamodeling.encryption.EncryptionContext;
import com.amazonaws.services.dynamodbv2.datamodeling.encryption.materials.DecryptionMaterials;
import com.amazonaws.services.dynamodbv2.datamodeling.encryption.materials.EncryptionMaterials;
import com.amazonaws.services.dynamodbv2.datamodeling.encryption.materials.SymmetricRawMaterials;
import com.amazonaws.services.dynamodbv2.datamodeling.encryption.materials.WrappedRawMaterials;
import com.amazonaws.services.dynamodbv2.datamodeling.internal.Base64;
import com.amazonaws.services.dynamodbv2.datamodeling.internal.Hkdf;
import com.amazonaws.services.dynamodbv2.model.AttributeValue;
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.GenerateDataKeyRequest;
import com.amazonaws.services.kms.model.GenerateDataKeyResult;
import com.amazonaws.util.StringUtils;
import java.nio.ByteBuffer;
import java.security.NoSuchAlgorithmException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
/**
* Generates a unique data key for each record in DynamoDB and protects that key using {@link
* AWSKMS}. Currently, the HashKey, RangeKey, and TableName will be included in the KMS
* EncryptionContext for wrapping/unwrapping the key. This means that records cannot be copied/moved
* between tables without re-encryption.
*
* @see <a href="http://docs.aws.amazon.com/kms/latest/developerguide/encrypt-context.html">KMS
* Encryption Context</a>
*/
public class DirectKmsMaterialProvider implements EncryptionMaterialsProvider {
static final String USER_AGENT_PREFIX = "DynamodbEncryptionSdkJava/";
private static final String USER_AGENT = USER_AGENT_PREFIX + loadVersion();
private static final String COVERED_ATTR_CTX_KEY = "aws-kms-ec-attr";
private static final String SIGNING_KEY_ALGORITHM = "amzn-ddb-sig-alg";
private static final String TABLE_NAME_EC_KEY = "*aws-kms-table*";
private static final String DEFAULT_ENC_ALG = "AES/256";
private static final String DEFAULT_SIG_ALG = "HmacSHA256/256";
private static final String KEY_COVERAGE = "*keys*";
private static final String KDF_ALG = "HmacSHA256";
private static final String KDF_SIG_INFO = "Signing";
private static final String KDF_ENC_INFO = "Encryption";
private final AWSKMS kms;
private final String encryptionKeyId;
private final Map<String, String> description;
private final String dataKeyAlg;
private final int dataKeyLength;
private final String dataKeyDesc;
private final String sigKeyAlg;
private final int sigKeyLength;
private final String sigKeyDesc;
public DirectKmsMaterialProvider(AWSKMS kms) {
this(kms, null);
}
public DirectKmsMaterialProvider(
AWSKMS kms, String encryptionKeyId, Map<String, String> materialDescription) {
this.kms = kms;
this.encryptionKeyId = encryptionKeyId;
this.description =
materialDescription != null
? Collections.unmodifiableMap(new HashMap<>(materialDescription))
: Collections.<String, String>emptyMap();
dataKeyDesc =
description.containsKey(WrappedRawMaterials.CONTENT_KEY_ALGORITHM)
? description.get(WrappedRawMaterials.CONTENT_KEY_ALGORITHM)
: DEFAULT_ENC_ALG;
String[] parts = dataKeyDesc.split("/", 2);
this.dataKeyAlg = parts[0];
this.dataKeyLength = parts.length == 2 ? Integer.parseInt(parts[1]) : 256;
sigKeyDesc =
description.containsKey(SIGNING_KEY_ALGORITHM)
? description.get(SIGNING_KEY_ALGORITHM)
: DEFAULT_SIG_ALG;
parts = sigKeyDesc.split("/", 2);
this.sigKeyAlg = parts[0];
this.sigKeyLength = parts.length == 2 ? Integer.parseInt(parts[1]) : 256;
}
public DirectKmsMaterialProvider(AWSKMS kms, String encryptionKeyId) {
this(kms, encryptionKeyId, Collections.<String, String>emptyMap());
}
@Override
public DecryptionMaterials getDecryptionMaterials(EncryptionContext context) {
final Map<String, String> materialDescription = context.getMaterialDescription();
final Map<String, String> ec = new HashMap<>();
final String providedEncAlg = materialDescription.get(CONTENT_KEY_ALGORITHM);
final String providedSigAlg = materialDescription.get(SIGNING_KEY_ALGORITHM);
ec.put("*" + CONTENT_KEY_ALGORITHM + "*", providedEncAlg);
ec.put("*" + SIGNING_KEY_ALGORITHM + "*", providedSigAlg);
populateKmsEcFromEc(context, ec);
DecryptRequest request = appendUserAgent(new DecryptRequest());
request.setCiphertextBlob(
ByteBuffer.wrap(Base64.decode(materialDescription.get(ENVELOPE_KEY))));
request.setEncryptionContext(ec);
final DecryptResult decryptResult = decrypt(request, context);
validateEncryptionKeyId(decryptResult.getKeyId(), context);
final Hkdf kdf;
try {
kdf = Hkdf.getInstance(KDF_ALG);
} catch (NoSuchAlgorithmException e) {
throw new DynamoDBMappingException(e);
}
kdf.init(toArray(decryptResult.getPlaintext()));
final String[] encAlgParts = providedEncAlg.split("/", 2);
int encLength = encAlgParts.length == 2 ? Integer.parseInt(encAlgParts[1]) : 256;
final String[] sigAlgParts = providedSigAlg.split("/", 2);
int sigLength = sigAlgParts.length == 2 ? Integer.parseInt(sigAlgParts[1]) : 256;
final SecretKey encryptionKey =
new SecretKeySpec(kdf.deriveKey(KDF_ENC_INFO, encLength / 8), encAlgParts[0]);
final SecretKey macKey =
new SecretKeySpec(kdf.deriveKey(KDF_SIG_INFO, sigLength / 8), sigAlgParts[0]);
return new SymmetricRawMaterials(encryptionKey, macKey, materialDescription);
}
@Override
public EncryptionMaterials getEncryptionMaterials(EncryptionContext context) {
final Map<String, String> ec = new HashMap<>();
ec.put("*" + CONTENT_KEY_ALGORITHM + "*", dataKeyDesc);
ec.put("*" + SIGNING_KEY_ALGORITHM + "*", sigKeyDesc);
populateKmsEcFromEc(context, ec);
final String keyId = selectEncryptionKeyId(context);
if (StringUtils.isNullOrEmpty(keyId)) {
throw new DynamoDBMappingException("Encryption key id is empty.");
}
final GenerateDataKeyRequest req = appendUserAgent(new GenerateDataKeyRequest());
req.setKeyId(keyId);
// NumberOfBytes parameter is used because we're not using this key as an AES-256 key,
// we're using it as an HKDF-SHA256 key.
req.setNumberOfBytes(256 / 8);
req.setEncryptionContext(ec);
final GenerateDataKeyResult dataKeyResult = generateDataKey(req, context);
final Map<String, String> materialDescription = new HashMap<>();
materialDescription.putAll(description);
materialDescription.put(COVERED_ATTR_CTX_KEY, KEY_COVERAGE);
materialDescription.put(KEY_WRAPPING_ALGORITHM, "kms");
materialDescription.put(CONTENT_KEY_ALGORITHM, dataKeyDesc);
materialDescription.put(SIGNING_KEY_ALGORITHM, sigKeyDesc);
materialDescription.put(
ENVELOPE_KEY, Base64.encodeToString(toArray(dataKeyResult.getCiphertextBlob())));
final Hkdf kdf;
try {
kdf = Hkdf.getInstance(KDF_ALG);
} catch (NoSuchAlgorithmException e) {
throw new DynamoDBMappingException(e);
}
kdf.init(toArray(dataKeyResult.getPlaintext()));
final SecretKey encryptionKey =
new SecretKeySpec(kdf.deriveKey(KDF_ENC_INFO, dataKeyLength / 8), dataKeyAlg);
final SecretKey signatureKey =
new SecretKeySpec(kdf.deriveKey(KDF_SIG_INFO, sigKeyLength / 8), sigKeyAlg);
return new SymmetricRawMaterials(encryptionKey, signatureKey, materialDescription);
}
/**
* Get encryption key id that is used to create the {@link EncryptionMaterials}.
*
* @return encryption key id.
*/
protected String getEncryptionKeyId() {
return this.encryptionKeyId;
}
/**
* Select encryption key id to be used to generate data key. The default implementation of this
* method returns {@link DirectKmsMaterialProvider#encryptionKeyId}.
*
* @param context encryption context.
* @return the encryptionKeyId.
* @throws DynamoDBMappingException when we fails to select a valid encryption key id.
*/
protected String selectEncryptionKeyId(EncryptionContext context)
throws DynamoDBMappingException {
return getEncryptionKeyId();
}
/**
* Validate the encryption key id. The default implementation of this method does not validate
* encryption key id.
*
* @param encryptionKeyId encryption key id from {@link DecryptResult}.
* @param context encryption context.
* @throws DynamoDBMappingException when encryptionKeyId is invalid.
*/
protected void validateEncryptionKeyId(String encryptionKeyId, EncryptionContext context)
throws DynamoDBMappingException {
// No action taken.
}
/**
* Decrypts ciphertext. The default implementation calls KMS to decrypt the ciphertext using the
* parameters provided in the {@link DecryptRequest}. Subclass can override the default
* implementation to provide additional request parameters using attributes within the {@link
* EncryptionContext}.
*
* @param request request parameters to decrypt the given ciphertext.
* @param context additional useful data to decrypt the ciphertext.
* @return the decrypted plaintext for the given ciphertext.
*/
protected DecryptResult decrypt(final DecryptRequest request, final EncryptionContext context) {
return kms.decrypt(request);
}
/**
* Returns a data encryption key that you can use in your application to encrypt data locally. The
* default implementation calls KMS to generate the data key using the parameters provided in the
* {@link GenerateDataKeyRequest}. Subclass can override the default implementation to provide
* additional request parameters using attributes within the {@link EncryptionContext}.
*
* @param request request parameters to generate the data key.
* @param context additional useful data to generate the data key.
* @return the newly generated data key which includes both the plaintext and ciphertext.
*/
protected GenerateDataKeyResult generateDataKey(
final GenerateDataKeyRequest request, final EncryptionContext context) {
return kms.generateDataKey(request);
}
/**
* Extracts relevant information from {@code context} and uses it to populate fields in {@code
* kmsEc}. Subclass can override the default implementation to provide an alternative encryption
* context in calls to KMS. Currently, the default implementation includes these fields:
*
* <dl>
* <dt>{@code HashKeyName}
* <dd>{@code HashKeyValue}
* <dt>{@code RangeKeyName}
* <dd>{@code RangeKeyValue}
* <dt>{@link #TABLE_NAME_EC_KEY}
* <dd>{@code TableName}
* </dl>
*/
protected void populateKmsEcFromEc(EncryptionContext context, Map<String, String> kmsEc) {
final String hashKeyName = context.getHashKeyName();
if (hashKeyName != null) {
final AttributeValue hashKey = context.getAttributeValues().get(hashKeyName);
if (hashKey.getN() != null) {
kmsEc.put(hashKeyName, hashKey.getN());
} else if (hashKey.getS() != null) {
kmsEc.put(hashKeyName, hashKey.getS());
} else if (hashKey.getB() != null) {
kmsEc.put(hashKeyName, Base64.encodeToString(toArray(hashKey.getB())));
} else {
throw new UnsupportedOperationException(
"DirectKmsMaterialProvider only supports String, Number, and Binary HashKeys");
}
}
final String rangeKeyName = context.getRangeKeyName();
if (rangeKeyName != null) {
final AttributeValue rangeKey = context.getAttributeValues().get(rangeKeyName);
if (rangeKey.getN() != null) {
kmsEc.put(rangeKeyName, rangeKey.getN());
} else if (rangeKey.getS() != null) {
kmsEc.put(rangeKeyName, rangeKey.getS());
} else if (rangeKey.getB() != null) {
kmsEc.put(rangeKeyName, Base64.encodeToString(toArray(rangeKey.getB())));
} else {
throw new UnsupportedOperationException(
"DirectKmsMaterialProvider only supports String, Number, and Binary RangeKeys");
}
}
final String tableName = context.getTableName();
if (tableName != null) {
kmsEc.put(TABLE_NAME_EC_KEY, tableName);
}
}
private static byte[] toArray(final ByteBuffer buff) {
final ByteBuffer dup = buff.asReadOnlyBuffer();
byte[] result = new byte[dup.remaining()];
dup.get(result);
return result;
}
private static <X extends AmazonWebServiceRequest> X appendUserAgent(final X request) {
request.getRequestClientOptions().appendUserAgent(USER_AGENT);
return request;
}
@Override
public void refresh() {
// No action needed
}
}
| 5,068 |
0 | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/main/sdkv1/com/amazonaws/services/dynamodbv2/datamodeling/encryption/providers | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/main/sdkv1/com/amazonaws/services/dynamodbv2/datamodeling/encryption/providers/store/ProviderStore.java | /*
* Copyright 2015 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.services.dynamodbv2.datamodeling.encryption.providers.store;
import com.amazonaws.services.dynamodbv2.datamodeling.encryption.providers.EncryptionMaterialsProvider;
import java.util.Map;
/**
* Provides a standard way to retrieve and optionally create {@link EncryptionMaterialsProvider}s
* backed by some form of persistent storage.
*
* @author rubin
*/
public abstract class ProviderStore {
/**
* Returns the most recent provider with the specified name. If there are no providers with this
* name, it will create one with version 0.
*/
public EncryptionMaterialsProvider getProvider(final String materialName) {
final long currVersion = getMaxVersion(materialName);
if (currVersion >= 0) {
return getProvider(materialName, currVersion);
} else {
return getOrCreate(materialName, 0);
}
}
/**
* Returns the provider with the specified name and version.
*
* @throws IndexOutOfBoundsException if {@code version} is not a valid version
*/
public abstract EncryptionMaterialsProvider getProvider(
final String materialName, final long version);
/**
* Creates a new provider with a version one greater than the current max version. If multiple
* clients attempt to create a provider with this same version simultaneously, they will properly
* coordinate and the result will be that a single provider is created and that all ProviderStores
* return the same one.
*/
public EncryptionMaterialsProvider newProvider(final String materialName) {
final long nextId = getMaxVersion(materialName) + 1;
return getOrCreate(materialName, nextId);
}
/**
* Returns the provider with the specified name and version and creates it if it doesn't exist.
*
* @throws UnsupportedOperationException if a new provider cannot be created
*/
public EncryptionMaterialsProvider getOrCreate(final String materialName, final long nextId) {
try {
return getProvider(materialName, nextId);
} catch (final IndexOutOfBoundsException ex) {
throw new UnsupportedOperationException("This ProviderStore does not support creation.", ex);
}
}
/**
* Returns the maximum version number associated with {@code materialName}. If there are no
* versions, returns -1.
*/
public abstract long getMaxVersion(final String materialName);
/** Extracts the material version from {@code description}. */
public abstract long getVersionFromMaterialDescription(final Map<String, String> description);
}
| 5,069 |
0 | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/main/sdkv1/com/amazonaws/services/dynamodbv2/datamodeling/encryption/providers | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/main/sdkv1/com/amazonaws/services/dynamodbv2/datamodeling/encryption/providers/store/MetaStore.java | /*
* Copyright 2015 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.services.dynamodbv2.datamodeling.encryption.providers.store;
import com.amazonaws.AmazonClientException;
import com.amazonaws.services.dynamodbv2.AmazonDynamoDB;
import com.amazonaws.services.dynamodbv2.datamodeling.encryption.DynamoDBEncryptor;
import com.amazonaws.services.dynamodbv2.datamodeling.encryption.EncryptionContext;
import com.amazonaws.services.dynamodbv2.datamodeling.encryption.providers.EncryptionMaterialsProvider;
import com.amazonaws.services.dynamodbv2.datamodeling.encryption.providers.WrappedMaterialsProvider;
import com.amazonaws.services.dynamodbv2.datamodeling.internal.Utils;
import com.amazonaws.services.dynamodbv2.model.AttributeDefinition;
import com.amazonaws.services.dynamodbv2.model.AttributeValue;
import com.amazonaws.services.dynamodbv2.model.ComparisonOperator;
import com.amazonaws.services.dynamodbv2.model.Condition;
import com.amazonaws.services.dynamodbv2.model.ConditionalCheckFailedException;
import com.amazonaws.services.dynamodbv2.model.CreateTableResult;
import com.amazonaws.services.dynamodbv2.model.ExpectedAttributeValue;
import com.amazonaws.services.dynamodbv2.model.GetItemRequest;
import com.amazonaws.services.dynamodbv2.model.KeySchemaElement;
import com.amazonaws.services.dynamodbv2.model.KeyType;
import com.amazonaws.services.dynamodbv2.model.ProvisionedThroughput;
import com.amazonaws.services.dynamodbv2.model.PutItemRequest;
import com.amazonaws.services.dynamodbv2.model.QueryRequest;
import com.amazonaws.services.dynamodbv2.model.ScalarAttributeType;
import java.nio.ByteBuffer;
import java.security.GeneralSecurityException;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
/**
* Provides a simple collection of EncryptionMaterialProviders backed by an encrypted DynamoDB
* table. This can be used to build key hierarchies or meta providers.
*
* <p>Currently, this only supports AES-256 in AESWrap mode and HmacSHA256 for the providers
* persisted in the table.
*
* @author rubin
*/
public class MetaStore extends ProviderStore {
private static final String INTEGRITY_ALGORITHM_FIELD = "intAlg";
private static final String INTEGRITY_KEY_FIELD = "int";
private static final String ENCRYPTION_ALGORITHM_FIELD = "encAlg";
private static final String ENCRYPTION_KEY_FIELD = "enc";
private static final Pattern COMBINED_PATTERN = Pattern.compile("([^#]+)#(\\d*)");
private static final String DEFAULT_INTEGRITY = "HmacSHA256";
private static final String DEFAULT_ENCRYPTION = "AES";
private static final String MATERIAL_TYPE_VERSION = "t";
private static final String META_ID = "amzn-ddb-meta-id";
private static final String DEFAULT_HASH_KEY = "N";
private static final String DEFAULT_RANGE_KEY = "V";
/** Default no-op implementation of {@link ExtraDataSupplier}. */
private static final EmptyExtraDataSupplier EMPTY_EXTRA_DATA_SUPPLIER =
new EmptyExtraDataSupplier();
/** DDB fields that must be encrypted. */
private static final Set<String> ENCRYPTED_FIELDS;
static {
final Set<String> tempEncryptedFields = new HashSet<>();
tempEncryptedFields.add(MATERIAL_TYPE_VERSION);
tempEncryptedFields.add(ENCRYPTION_KEY_FIELD);
tempEncryptedFields.add(ENCRYPTION_ALGORITHM_FIELD);
tempEncryptedFields.add(INTEGRITY_KEY_FIELD);
tempEncryptedFields.add(INTEGRITY_ALGORITHM_FIELD);
ENCRYPTED_FIELDS = tempEncryptedFields;
}
private final Map<String, ExpectedAttributeValue> doesNotExist;
private final Set<String> doNotEncrypt;
private final String tableName;
private final AmazonDynamoDB ddb;
private final DynamoDBEncryptor encryptor;
private final EncryptionContext ddbCtx;
private final ExtraDataSupplier extraDataSupplier;
/** Provides extra data that should be persisted along with the standard material data. */
public interface ExtraDataSupplier {
/**
* Gets the extra data attributes for the specified material name.
*
* @param materialName material name.
* @param version version number.
* @return plain text of the extra data.
*/
Map<String, AttributeValue> getAttributes(final String materialName, final long version);
/**
* Gets the extra data field names that should be signed only but not encrypted.
*
* @return signed only fields.
*/
Set<String> getSignedOnlyFieldNames();
}
/**
* Create a new MetaStore with specified table name.
*
* @param ddb Interface for accessing DynamoDB.
* @param tableName DynamoDB table name for this {@link MetaStore}.
* @param encryptor used to perform crypto operations on the record attributes.
*/
public MetaStore(
final AmazonDynamoDB ddb, final String tableName, final DynamoDBEncryptor encryptor) {
this(ddb, tableName, encryptor, EMPTY_EXTRA_DATA_SUPPLIER);
}
/**
* Create a new MetaStore with specified table name and extra data supplier.
*
* @param ddb Interface for accessing DynamoDB.
* @param tableName DynamoDB table name for this {@link MetaStore}.
* @param encryptor used to perform crypto operations on the record attributes
* @param extraDataSupplier provides extra data that should be stored along with the material.
*/
public MetaStore(
final AmazonDynamoDB ddb,
final String tableName,
final DynamoDBEncryptor encryptor,
final ExtraDataSupplier extraDataSupplier) {
this.ddb = checkNotNull(ddb, "ddb must not be null");
this.tableName = checkNotNull(tableName, "tableName must not be null");
this.encryptor = checkNotNull(encryptor, "encryptor must not be null");
this.extraDataSupplier = checkNotNull(extraDataSupplier, "extraDataSupplier must not be null");
this.ddbCtx =
new EncryptionContext.Builder()
.withTableName(this.tableName)
.withHashKeyName(DEFAULT_HASH_KEY)
.withRangeKeyName(DEFAULT_RANGE_KEY)
.build();
final Map<String, ExpectedAttributeValue> tmpExpected = new HashMap<>();
tmpExpected.put(DEFAULT_HASH_KEY, new ExpectedAttributeValue().withExists(false));
tmpExpected.put(DEFAULT_RANGE_KEY, new ExpectedAttributeValue().withExists(false));
doesNotExist = Collections.unmodifiableMap(tmpExpected);
this.doNotEncrypt = getSignedOnlyFields(extraDataSupplier);
}
@Override
public EncryptionMaterialsProvider getProvider(final String materialName, final long version) {
Map<String, AttributeValue> item = getMaterialItem(materialName, version);
return decryptProvider(item);
}
@Override
public EncryptionMaterialsProvider getOrCreate(final String materialName, final long nextId) {
final Map<String, AttributeValue> plaintext = createMaterialItem(materialName, nextId);
final Map<String, AttributeValue> ciphertext = conditionalPut(getEncryptedText(plaintext));
return decryptProvider(ciphertext);
}
@Override
public long getMaxVersion(final String materialName) {
final List<Map<String, AttributeValue>> items =
ddb.query(
new QueryRequest()
.withTableName(tableName)
.withConsistentRead(Boolean.TRUE)
.withKeyConditions(
Collections.singletonMap(
DEFAULT_HASH_KEY,
new Condition()
.withComparisonOperator(ComparisonOperator.EQ)
.withAttributeValueList(new AttributeValue().withS(materialName))))
.withLimit(1)
.withScanIndexForward(false)
.withAttributesToGet(DEFAULT_RANGE_KEY))
.getItems();
if (items.isEmpty()) {
return -1L;
} else {
return Long.parseLong(items.get(0).get(DEFAULT_RANGE_KEY).getN());
}
}
@Override
public long getVersionFromMaterialDescription(final Map<String, String> description) {
final Matcher m = COMBINED_PATTERN.matcher(description.get(META_ID));
if (m.matches()) {
return Long.parseLong(m.group(2));
} else {
throw new IllegalArgumentException("No meta id found");
}
}
/**
* This API retrieves the intermediate keys from the source region and replicates it in the target
* region.
*
* @param materialName material name of the encryption material.
* @param version version of the encryption material.
* @param targetMetaStore target MetaStore where the encryption material to be stored.
*/
public void replicate(
final String materialName, final long version, final MetaStore targetMetaStore) {
try {
Map<String, AttributeValue> item = getMaterialItem(materialName, version);
final Map<String, AttributeValue> plainText = getPlainText(item);
final Map<String, AttributeValue> encryptedText = targetMetaStore.getEncryptedText(plainText);
final PutItemRequest put =
new PutItemRequest()
.withTableName(targetMetaStore.tableName)
.withItem(encryptedText)
.withExpected(doesNotExist);
targetMetaStore.ddb.putItem(put);
} catch (ConditionalCheckFailedException e) {
// Item already present.
}
}
private Map<String, AttributeValue> getMaterialItem(
final String materialName, final long version) {
final Map<String, AttributeValue> ddbKey = new HashMap<>();
ddbKey.put(DEFAULT_HASH_KEY, new AttributeValue().withS(materialName));
ddbKey.put(DEFAULT_RANGE_KEY, new AttributeValue().withN(Long.toString(version)));
final Map<String, AttributeValue> item = ddbGet(ddbKey);
if (item == null || item.isEmpty()) {
throw new IndexOutOfBoundsException("No material found: " + materialName + "#" + version);
}
return item;
}
/**
* Creates a DynamoDB Table with the correct properties to be used with a ProviderStore.
*
* @param ddb interface for accessing DynamoDB
* @param tableName name of table that stores the meta data of the material.
* @param provisionedThroughput required provisioned throughput of the this table.
* @return result of create table request.
*/
public static CreateTableResult createTable(
final AmazonDynamoDB ddb,
final String tableName,
final ProvisionedThroughput provisionedThroughput) {
return ddb.createTable(
Arrays.asList(
new AttributeDefinition(DEFAULT_HASH_KEY, ScalarAttributeType.S),
new AttributeDefinition(DEFAULT_RANGE_KEY, ScalarAttributeType.N)),
tableName,
Arrays.asList(
new KeySchemaElement(DEFAULT_HASH_KEY, KeyType.HASH),
new KeySchemaElement(DEFAULT_RANGE_KEY, KeyType.RANGE)),
provisionedThroughput);
}
/**
* Empty extra data supplier. This default class is intended to simplify the default
* implementation of {@link MetaStore}.
*/
private static class EmptyExtraDataSupplier implements ExtraDataSupplier {
@Override
public Map<String, AttributeValue> getAttributes(String materialName, long version) {
return Collections.emptyMap();
}
@Override
public Set<String> getSignedOnlyFieldNames() {
return Collections.emptySet();
}
}
/**
* Get a set of fields that must be signed but not encrypted.
*
* @param extraDataSupplier extra data supplier that is used to return sign only field names.
* @return fields that must be signed.
*/
private static Set<String> getSignedOnlyFields(final ExtraDataSupplier extraDataSupplier) {
final Set<String> signedOnlyFields = extraDataSupplier.getSignedOnlyFieldNames();
for (final String signedOnlyField : signedOnlyFields) {
if (ENCRYPTED_FIELDS.contains(signedOnlyField)) {
throw new IllegalArgumentException(signedOnlyField + " must be encrypted");
}
}
// fields that should not be encrypted
final Set<String> doNotEncryptFields = new HashSet<>();
doNotEncryptFields.add(DEFAULT_HASH_KEY);
doNotEncryptFields.add(DEFAULT_RANGE_KEY);
doNotEncryptFields.addAll(signedOnlyFields);
return Collections.unmodifiableSet(doNotEncryptFields);
}
private Map<String, AttributeValue> conditionalPut(final Map<String, AttributeValue> item) {
try {
final PutItemRequest put =
new PutItemRequest().withTableName(tableName).withItem(item).withExpected(doesNotExist);
ddb.putItem(put);
return item;
} catch (final ConditionalCheckFailedException ex) {
final Map<String, AttributeValue> ddbKey = new HashMap<>();
ddbKey.put(DEFAULT_HASH_KEY, item.get(DEFAULT_HASH_KEY));
ddbKey.put(DEFAULT_RANGE_KEY, item.get(DEFAULT_RANGE_KEY));
return ddbGet(ddbKey);
}
}
private Map<String, AttributeValue> ddbGet(final Map<String, AttributeValue> ddbKey) {
return ddb.getItem(
new GetItemRequest().withTableName(tableName).withConsistentRead(true).withKey(ddbKey))
.getItem();
}
/**
* Build an material item for a given material name and version with newly generated encryption
* and integrity keys.
*
* @param materialName material name.
* @param version version of the material.
* @return newly generated plaintext material item.
*/
private Map<String, AttributeValue> createMaterialItem(
final String materialName, final long version) {
final SecretKeySpec encryptionKey = new SecretKeySpec(Utils.getRandom(32), DEFAULT_ENCRYPTION);
final SecretKeySpec integrityKey = new SecretKeySpec(Utils.getRandom(32), DEFAULT_INTEGRITY);
final Map<String, AttributeValue> plaintext = new HashMap<String, AttributeValue>();
plaintext.put(DEFAULT_HASH_KEY, new AttributeValue().withS(materialName));
plaintext.put(DEFAULT_RANGE_KEY, new AttributeValue().withN(Long.toString(version)));
plaintext.put(MATERIAL_TYPE_VERSION, new AttributeValue().withS("0"));
plaintext.put(
ENCRYPTION_KEY_FIELD,
new AttributeValue().withB(ByteBuffer.wrap(encryptionKey.getEncoded())));
plaintext.put(
ENCRYPTION_ALGORITHM_FIELD, new AttributeValue().withS(encryptionKey.getAlgorithm()));
plaintext.put(
INTEGRITY_KEY_FIELD,
new AttributeValue().withB(ByteBuffer.wrap(integrityKey.getEncoded())));
plaintext.put(
INTEGRITY_ALGORITHM_FIELD, new AttributeValue().withS(integrityKey.getAlgorithm()));
plaintext.putAll(extraDataSupplier.getAttributes(materialName, version));
return plaintext;
}
private EncryptionMaterialsProvider decryptProvider(final Map<String, AttributeValue> item) {
final Map<String, AttributeValue> plaintext = getPlainText(item);
final String type = plaintext.get(MATERIAL_TYPE_VERSION).getS();
final SecretKey encryptionKey;
final SecretKey integrityKey;
// This switch statement is to make future extensibility easier and more obvious
switch (type) {
case "0": // Only currently supported type
encryptionKey =
new SecretKeySpec(
plaintext.get(ENCRYPTION_KEY_FIELD).getB().array(),
plaintext.get(ENCRYPTION_ALGORITHM_FIELD).getS());
integrityKey =
new SecretKeySpec(
plaintext.get(INTEGRITY_KEY_FIELD).getB().array(),
plaintext.get(INTEGRITY_ALGORITHM_FIELD).getS());
break;
default:
throw new IllegalStateException("Unsupported material type: " + type);
}
return new WrappedMaterialsProvider(
encryptionKey, encryptionKey, integrityKey, buildDescription(plaintext));
}
/**
* Decrypts attributes in the ciphertext item using {@link DynamoDBEncryptor}. except the
* attribute names specified in doNotEncrypt.
*
* @param ciphertext the ciphertext to be decrypted.
* @throws AmazonClientException when failed to decrypt material item.
* @return decrypted item.
*/
private Map<String, AttributeValue> getPlainText(final Map<String, AttributeValue> ciphertext) {
try {
return encryptor.decryptAllFieldsExcept(ciphertext, ddbCtx, doNotEncrypt);
} catch (final GeneralSecurityException e) {
throw new AmazonClientException(e);
}
}
/**
* Encrypts attributes in the plaintext item using {@link DynamoDBEncryptor}. except the attribute
* names specified in doNotEncrypt.
*
* @throws AmazonClientException when failed to encrypt material item.
* @param plaintext plaintext to be encrypted.
*/
private Map<String, AttributeValue> getEncryptedText(Map<String, AttributeValue> plaintext) {
try {
return encryptor.encryptAllFieldsExcept(plaintext, ddbCtx, doNotEncrypt);
} catch (final GeneralSecurityException e) {
throw new AmazonClientException(e);
}
}
private Map<String, String> buildDescription(final Map<String, AttributeValue> plaintext) {
return Collections.singletonMap(
META_ID,
plaintext.get(DEFAULT_HASH_KEY).getS() + "#" + plaintext.get(DEFAULT_RANGE_KEY).getN());
}
private static <V> V checkNotNull(final V ref, final String errMsg) {
if (ref == null) {
throw new NullPointerException(errMsg);
} else {
return ref;
}
}
}
| 5,070 |
0 | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/main/sdkv1/com/amazonaws/services/dynamodbv2/datamodeling/encryption | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/main/sdkv1/com/amazonaws/services/dynamodbv2/datamodeling/encryption/utils/EncryptionContextOperators.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.services.dynamodbv2.datamodeling.encryption.utils;
import com.amazonaws.services.dynamodbv2.datamodeling.encryption.EncryptionContext;
import java.util.Map;
import java.util.function.UnaryOperator;
/** Implementations of common operators for overriding the EncryptionContext */
public class EncryptionContextOperators {
// Prevent instantiation
private EncryptionContextOperators() {}
/**
* An operator for overriding EncryptionContext's table name for a specific DynamoDBEncryptor. If
* any table names or the encryption context itself is null, then it returns the original
* EncryptionContext.
*
* @param originalTableName the name of the table that should be overridden in the Encryption
* Context
* @param newTableName the table name that should be used in the Encryption Context
* @return A UnaryOperator that produces a new EncryptionContext with the supplied table name
*/
public static UnaryOperator<EncryptionContext> overrideEncryptionContextTableName(
String originalTableName, String newTableName) {
return encryptionContext -> {
if (encryptionContext == null
|| encryptionContext.getTableName() == null
|| originalTableName == null
|| newTableName == null) {
return encryptionContext;
}
if (originalTableName.equals(encryptionContext.getTableName())) {
return new EncryptionContext.Builder(encryptionContext).withTableName(newTableName).build();
} else {
return encryptionContext;
}
};
}
/**
* An operator for mapping multiple table names in the Encryption Context to a new table name. If
* the table name for a given EncryptionContext is missing, then it returns the original
* EncryptionContext. Similarly, it returns the original EncryptionContext if the value it is
* overridden to is null, or if the original table name is null.
*
* @param tableNameOverrideMap a map specifying the names of tables that should be overridden, and
* the values to which they should be overridden. If the given table name corresponds to null,
* or isn't in the map, then the table name won't be overridden.
* @return A UnaryOperator that produces a new EncryptionContext with the supplied table name
*/
public static UnaryOperator<EncryptionContext> overrideEncryptionContextTableNameUsingMap(
Map<String, String> tableNameOverrideMap) {
return encryptionContext -> {
if (tableNameOverrideMap == null
|| encryptionContext == null
|| encryptionContext.getTableName() == null) {
return encryptionContext;
}
String newTableName = tableNameOverrideMap.get(encryptionContext.getTableName());
if (newTableName != null) {
return new EncryptionContext.Builder(encryptionContext).withTableName(newTableName).build();
} else {
return encryptionContext;
}
};
}
}
| 5,071 |
0 | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/main/sdkv1/com/amazonaws/services/dynamodbv2/datamodeling | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/main/sdkv1/com/amazonaws/services/dynamodbv2/datamodeling/internal/TTLCache.java | // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package com.amazonaws.services.dynamodbv2.datamodeling.internal;
import static com.amazonaws.services.dynamodbv2.datamodeling.internal.Utils.checkNotNull;
import com.amazonaws.annotation.ThreadSafe;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.locks.ReentrantLock;
import java.util.function.Function;
/**
* A cache, backed by an LRUCache, that uses a loader to calculate values on cache miss or expired
* TTL.
*
* <p>Note that this cache does not proactively evict expired entries, however will immediately
* evict entries discovered to be expired on load.
*
* @param <T> value type
*/
@ThreadSafe
public final class TTLCache<T> {
/** Used for the internal cache. */
private final LRUCache<LockedState<T>> cache;
/** Time to live for entries in the cache. */
private final long ttlInNanos;
/** Used for loading new values into the cache on cache miss or expiration. */
private final EntryLoader<T> defaultLoader;
// Mockable time source, to allow us to test TTL behavior.
// package access for tests
MsClock clock = MsClock.WALLCLOCK;
private static final long TTL_GRACE_IN_NANO = TimeUnit.MILLISECONDS.toNanos(500);
/**
* @param maxSize the maximum number of entries of the cache
* @param ttlInMillis the time to live value for entries of the cache, in milliseconds
*/
public TTLCache(final int maxSize, final long ttlInMillis, final EntryLoader<T> loader) {
if (maxSize < 1) {
throw new IllegalArgumentException("maxSize " + maxSize + " must be at least 1");
}
if (ttlInMillis < 1) {
throw new IllegalArgumentException("ttlInMillis " + maxSize + " must be at least 1");
}
this.ttlInNanos = TimeUnit.MILLISECONDS.toNanos(ttlInMillis);
this.cache = new LRUCache<>(maxSize);
this.defaultLoader = checkNotNull(loader, "loader must not be null");
}
/**
* Uses the default loader to calculate the value at key and insert it into the cache, if it
* doesn't already exist or is expired according to the TTL.
*
* <p>This immediately evicts entries past the TTL such that a load failure results in the removal
* of the entry.
*
* <p>Entries that are not expired according to the TTL are returned without recalculating the
* value.
*
* <p>Within a grace period past the TTL, the cache may either return the cached value without
* recalculating or use the loader to recalculate the value. This is implemented such that, in a
* multi-threaded environment, only one thread per cache key uses the loader to recalculate the
* value at one time.
*
* @param key The cache key to load the value at
* @return The value of the given value (already existing or re-calculated).
*/
public T load(final String key) {
return load(key, defaultLoader::load);
}
/**
* Uses the inputted function to calculate the value at key and insert it into the cache, if it
* doesn't already exist or is expired according to the TTL.
*
* <p>This immediately evicts entries past the TTL such that a load failure results in the removal
* of the entry.
*
* <p>Entries that are not expired according to the TTL are returned without recalculating the
* value.
*
* <p>Within a grace period past the TTL, the cache may either return the cached value without
* recalculating or use the loader to recalculate the value. This is implemented such that, in a
* multi-threaded environment, only one thread per cache key uses the loader to recalculate the
* value at one time.
*
* <p>Returns the value of the given key (already existing or re-calculated).
*
* @param key The cache key to load the value at
* @param f The function to use to load the value, given key as input
* @return The value of the given value (already existing or re-calculated).
*/
public T load(final String key, Function<String, T> f) {
final LockedState<T> ls = cache.get(key);
if (ls == null) {
// The entry doesn't exist yet, so load a new one.
return loadNewEntryIfAbsent(key, f);
} else if (clock.timestampNano() - ls.getState().lastUpdatedNano
> ttlInNanos + TTL_GRACE_IN_NANO) {
// The data has expired past the grace period.
// Evict the old entry and load a new entry.
cache.remove(key);
return loadNewEntryIfAbsent(key, f);
} else if (clock.timestampNano() - ls.getState().lastUpdatedNano <= ttlInNanos) {
// The data hasn't expired. Return as-is from the cache.
return ls.getState().data;
} else if (!ls.tryLock()) {
// We are in the TTL grace period. If we couldn't grab the lock, then some other
// thread is currently loading the new value. Because we are in the grace period,
// use the cached data instead of waiting for the lock.
return ls.getState().data;
}
// We are in the grace period and have acquired a lock.
// Update the cache with the value determined by the loading function.
try {
T loadedData = f.apply(key);
ls.update(loadedData, clock.timestampNano());
return ls.getState().data;
} finally {
ls.unlock();
}
}
// Synchronously calculate the value for a new entry in the cache if it doesn't already exist.
// Otherwise return the cached value.
// It is important that this is the only place where we use the loader for a new entry,
// given that we don't have the entry yet to lock on.
// This ensures that the loading function is only called once if multiple threads
// attempt to add a new entry for the same key at the same time.
private synchronized T loadNewEntryIfAbsent(final String key, Function<String, T> f) {
// If the entry already exists in the cache, return it
final LockedState<T> cachedState = cache.get(key);
if (cachedState != null) {
return cachedState.getState().data;
}
// Otherwise, load the data and create a new entry
T loadedData = f.apply(key);
LockedState<T> ls = new LockedState<>(loadedData, clock.timestampNano());
cache.add(key, ls);
return loadedData;
}
/**
* Put a new entry in the cache. Returns the value previously at that key in the cache, or null if
* the entry previously didn't exist or is expired.
*/
public synchronized T put(final String key, final T value) {
LockedState<T> ls = new LockedState<>(value, clock.timestampNano());
LockedState<T> oldLockedState = cache.add(key, ls);
if (oldLockedState == null
|| clock.timestampNano() - oldLockedState.getState().lastUpdatedNano
> ttlInNanos + TTL_GRACE_IN_NANO) {
return null;
}
return oldLockedState.getState().data;
}
/**
* Get when the entry at this key was last updated. Returns 0 if the entry doesn't exist at key.
*/
public long getLastUpdated(String key) {
LockedState<T> ls = cache.get(key);
if (ls == null) {
return 0;
}
return ls.getState().lastUpdatedNano;
}
/** Returns the current size of the cache. */
public int size() {
return cache.size();
}
/** Returns the maximum size of the cache. */
public int getMaxSize() {
return cache.getMaxSize();
}
/** Clears all entries from the cache. */
public void clear() {
cache.clear();
}
@Override
public String toString() {
return cache.toString();
}
public interface EntryLoader<T> {
T load(String entryKey);
}
// An object which stores a state alongside a lock,
// and performs updates to that state atomically.
// The state may only be updated if the lock is acquired by the current thread.
private static class LockedState<T> {
private final ReentrantLock lock = new ReentrantLock(true);
private final AtomicReference<State<T>> state;
public LockedState(T data, long createTimeNano) {
state = new AtomicReference<>(new State<>(data, createTimeNano));
}
public State<T> getState() {
return state.get();
}
public void unlock() {
lock.unlock();
}
public boolean tryLock() {
return lock.tryLock();
}
public void update(T data, long createTimeNano) {
if (!lock.isHeldByCurrentThread()) {
throw new IllegalStateException("Lock not held by current thread");
}
state.set(new State<>(data, createTimeNano));
}
}
// An object that holds some data and the time at which this object was created
private static class State<T> {
public final T data;
public final long lastUpdatedNano;
public State(T data, long lastUpdatedNano) {
this.data = data;
this.lastUpdatedNano = lastUpdatedNano;
}
}
}
| 5,072 |
0 | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/main/sdkv1/com/amazonaws/services/dynamodbv2/datamodeling | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/main/sdkv1/com/amazonaws/services/dynamodbv2/datamodeling/internal/Hkdf.java | /*
* Copyright 2014 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.services.dynamodbv2.datamodeling.internal;
import com.amazonaws.util.StringUtils;
import java.security.GeneralSecurityException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.Provider;
import java.util.Arrays;
import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.ShortBufferException;
import javax.crypto.spec.SecretKeySpec;
/**
* HMAC-based Key Derivation Function.
*
* @see <a href="http://tools.ietf.org/html/rfc5869">RFC 5869</a>
*/
public final class Hkdf {
private static final byte[] EMPTY_ARRAY = new byte[0];
private final String algorithm;
private final Provider provider;
private SecretKey prk = null;
/**
* Returns an <code>Hkdf</code> object using the specified algorithm.
*
* @param algorithm the standard name of the requested MAC algorithm. See the Mac section in the
* <a href=
* "http://docs.oracle.com/javase/7/docs/technotes/guides/security/StandardNames.html#Mac" >
* Java Cryptography Architecture Standard Algorithm Name Documentation</a> for information
* about standard algorithm names.
* @return the new <code>Hkdf</code> object
* @throws NoSuchAlgorithmException if no Provider supports a MacSpi implementation for the
* specified algorithm.
*/
public static Hkdf getInstance(final String algorithm) throws NoSuchAlgorithmException {
// Constructed specifically to sanity-test arguments.
Mac mac = Mac.getInstance(algorithm);
return new Hkdf(algorithm, mac.getProvider());
}
/**
* Returns an <code>Hkdf</code> object using the specified algorithm.
*
* @param algorithm the standard name of the requested MAC algorithm. See the Mac section in the
* <a href=
* "http://docs.oracle.com/javase/7/docs/technotes/guides/security/StandardNames.html#Mac" >
* Java Cryptography Architecture Standard Algorithm Name Documentation</a> for information
* about standard algorithm names.
* @param provider the name of the provider
* @return the new <code>Hkdf</code> object
* @throws NoSuchAlgorithmException if a MacSpi implementation for the specified algorithm is not
* available from the specified provider.
* @throws NoSuchProviderException if the specified provider is not registered in the security
* provider list.
*/
public static Hkdf getInstance(final String algorithm, final String provider)
throws NoSuchAlgorithmException, NoSuchProviderException {
// Constructed specifically to sanity-test arguments.
Mac mac = Mac.getInstance(algorithm, provider);
return new Hkdf(algorithm, mac.getProvider());
}
/**
* Returns an <code>Hkdf</code> object using the specified algorithm.
*
* @param algorithm the standard name of the requested MAC algorithm. See the Mac section in the
* <a href=
* "http://docs.oracle.com/javase/7/docs/technotes/guides/security/StandardNames.html#Mac" >
* Java Cryptography Architecture Standard Algorithm Name Documentation</a> for information
* about standard algorithm names.
* @param provider the provider
* @return the new <code>Hkdf</code> object
* @throws NoSuchAlgorithmException if a MacSpi implementation for the specified algorithm is not
* available from the specified provider.
*/
public static Hkdf getInstance(final String algorithm, final Provider provider)
throws NoSuchAlgorithmException {
// Constructed specifically to sanity-test arguments.
Mac mac = Mac.getInstance(algorithm, provider);
return new Hkdf(algorithm, mac.getProvider());
}
/**
* Initializes this Hkdf with input keying material. A default salt of HashLen zeros will be used
* (where HashLen is the length of the return value of the supplied algorithm).
*
* @param ikm the Input Keying Material
*/
public void init(final byte[] ikm) {
init(ikm, null);
}
/**
* Initializes this Hkdf with input keying material and a salt. If <code>
* salt</code> is <code>null</code> or of length 0, then a default salt of HashLen zeros will be
* used (where HashLen is the length of the return value of the supplied algorithm).
*
* @param salt the salt used for key extraction (optional)
* @param ikm the Input Keying Material
*/
public void init(final byte[] ikm, final byte[] salt) {
byte[] realSalt = (salt == null) ? EMPTY_ARRAY : salt.clone();
byte[] rawKeyMaterial = EMPTY_ARRAY;
try {
Mac extractionMac = Mac.getInstance(algorithm, provider);
if (realSalt.length == 0) {
realSalt = new byte[extractionMac.getMacLength()];
Arrays.fill(realSalt, (byte) 0);
}
extractionMac.init(new SecretKeySpec(realSalt, algorithm));
rawKeyMaterial = extractionMac.doFinal(ikm);
SecretKeySpec key = new SecretKeySpec(rawKeyMaterial, algorithm);
Arrays.fill(rawKeyMaterial, (byte) 0); // Zeroize temporary array
unsafeInitWithoutKeyExtraction(key);
} catch (GeneralSecurityException e) {
// We've already checked all of the parameters so no exceptions
// should be possible here.
throw new RuntimeException("Unexpected exception", e);
} finally {
Arrays.fill(rawKeyMaterial, (byte) 0); // Zeroize temporary array
}
}
/**
* Initializes this Hkdf to use the provided key directly for creation of new keys. If <code>
* rawKey</code> is not securely generated and uniformly distributed over the total key-space,
* then this will result in an insecure key derivation function (KDF). <em>DO NOT USE THIS UNLESS
* YOU ARE ABSOLUTELY POSITIVE THIS IS THE CORRECT THING TO DO.</em>
*
* @param rawKey the pseudorandom key directly used to derive keys
* @throws InvalidKeyException if the algorithm for <code>rawKey</code> does not match the
* algorithm this Hkdf was created with
*/
public void unsafeInitWithoutKeyExtraction(final SecretKey rawKey) throws InvalidKeyException {
if (!rawKey.getAlgorithm().equals(algorithm)) {
throw new InvalidKeyException(
"Algorithm for the provided key must match the algorithm for this Hkdf. Expected "
+ algorithm
+ " but found "
+ rawKey.getAlgorithm());
}
this.prk = rawKey;
}
private Hkdf(final String algorithm, final Provider provider) {
if (!algorithm.startsWith("Hmac")) {
throw new IllegalArgumentException(
"Invalid algorithm " + algorithm + ". Hkdf may only be used with Hmac algorithms.");
}
this.algorithm = algorithm;
this.provider = provider;
}
/**
* Returns a pseudorandom key of <code>length</code> bytes.
*
* @param info optional context and application specific information (can be a zero-length
* string). This will be treated as UTF-8.
* @param length the length of the output key in bytes
* @return a pseudorandom key of <code>length</code> bytes.
* @throws IllegalStateException if this object has not been initialized
*/
public byte[] deriveKey(final String info, final int length) throws IllegalStateException {
return deriveKey((info != null ? info.getBytes(StringUtils.UTF8) : null), length);
}
/**
* Returns a pseudorandom key of <code>length</code> bytes.
*
* @param info optional context and application specific information (can be a zero-length array).
* @param length the length of the output key in bytes
* @return a pseudorandom key of <code>length</code> bytes.
* @throws IllegalStateException if this object has not been initialized
*/
public byte[] deriveKey(final byte[] info, final int length) throws IllegalStateException {
byte[] result = new byte[length];
try {
deriveKey(info, length, result, 0);
} catch (ShortBufferException ex) {
// This exception is impossible as we ensure the buffer is long
// enough
throw new RuntimeException(ex);
}
return result;
}
/**
* Derives a pseudorandom key of <code>length</code> bytes and stores the result in <code>output
* </code>.
*
* @param info optional context and application specific information (can be a zero-length array).
* @param length the length of the output key in bytes
* @param output the buffer where the pseudorandom key will be stored
* @param offset the offset in <code>output</code> where the key will be stored
* @throws ShortBufferException if the given output buffer is too small to hold the result
* @throws IllegalStateException if this object has not been initialized
*/
public void deriveKey(final byte[] info, final int length, final byte[] output, final int offset)
throws ShortBufferException, IllegalStateException {
assertInitialized();
if (length < 0) {
throw new IllegalArgumentException("Length must be a non-negative value.");
}
if (output.length < offset + length) {
throw new ShortBufferException();
}
Mac mac = createMac();
if (length > 255 * mac.getMacLength()) {
throw new IllegalArgumentException(
"Requested keys may not be longer than 255 times the underlying HMAC length.");
}
byte[] t = EMPTY_ARRAY;
try {
int loc = 0;
byte i = 1;
while (loc < length) {
mac.update(t);
mac.update(info);
mac.update(i);
t = mac.doFinal();
for (int x = 0; x < t.length && loc < length; x++, loc++) {
output[loc] = t[x];
}
i++;
}
} finally {
Arrays.fill(t, (byte) 0); // Zeroize temporary array
}
}
private Mac createMac() {
try {
Mac mac = Mac.getInstance(algorithm, provider);
mac.init(prk);
return mac;
} catch (NoSuchAlgorithmException ex) {
// We've already validated that this algorithm is correct.
throw new RuntimeException(ex);
} catch (InvalidKeyException ex) {
// We've already validated that this key is correct.
throw new RuntimeException(ex);
}
}
/**
* Throws an <code>IllegalStateException</code> if this object has not been initialized.
*
* @throws IllegalStateException if this object has not been initialized
*/
private void assertInitialized() throws IllegalStateException {
if (prk == null) {
throw new IllegalStateException("Hkdf has not been initialized");
}
}
}
| 5,073 |
0 | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/main/sdkv1/com/amazonaws/services/dynamodbv2/datamodeling | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/main/sdkv1/com/amazonaws/services/dynamodbv2/datamodeling/internal/Base64.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.services.dynamodbv2.datamodeling.internal;
import java.util.Base64.Decoder;
import java.util.Base64.Encoder;
/** A class for decoding Base64 strings and encoding bytes as Base64 strings. */
public class Base64 {
private static final Decoder DECODER = java.util.Base64.getMimeDecoder();
private static final Encoder ENCODER = java.util.Base64.getEncoder();
private Base64() {}
/**
* Encode the bytes as a Base64 string.
*
* <p>See the Basic encoder in {@link java.util.Base64}
*/
public static String encodeToString(byte[] bytes) {
return ENCODER.encodeToString(bytes);
}
/**
* Decode the Base64 string as bytes, ignoring illegal characters.
*
* <p>See the Mime Decoder in {@link java.util.Base64}
*/
public static byte[] decode(String str) {
if (str == null) {
return null;
}
return DECODER.decode(str);
}
}
| 5,074 |
0 | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/main/sdkv1/com/amazonaws/services/dynamodbv2/datamodeling | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/main/sdkv1/com/amazonaws/services/dynamodbv2/datamodeling/internal/Utils.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.services.dynamodbv2.datamodeling.internal;
import java.io.IOException;
import java.security.SecureRandom;
import java.util.Properties;
public class Utils {
private static final ThreadLocal<SecureRandom> RND =
new ThreadLocal<SecureRandom>() {
@Override
protected SecureRandom initialValue() {
final SecureRandom result = new SecureRandom();
result.nextBoolean(); // Force seeding
return result;
}
};
private Utils() {
// Prevent instantiation
}
public static SecureRandom getRng() {
return RND.get();
}
public static byte[] getRandom(int len) {
final byte[] result = new byte[len];
getRng().nextBytes(result);
return result;
}
public static <V> V checkNotNull(final V ref, final String errMsg) {
if (ref == null) {
throw new NullPointerException(errMsg);
} else {
return ref;
}
}
/*
* Loads the version of the library
*/
public static String loadVersion() {
return "2.0.3-legacy";
}
}
| 5,075 |
0 | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/main/sdkv1/com/amazonaws/services/dynamodbv2/datamodeling | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/main/sdkv1/com/amazonaws/services/dynamodbv2/datamodeling/internal/LRUCache.java | // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package com.amazonaws.services.dynamodbv2.datamodeling.internal;
import com.amazonaws.annotation.ThreadSafe;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;
/**
* A bounded cache that has a LRU eviction policy when the cache is full.
*
* @param <T> value type
*/
@ThreadSafe
public final class LRUCache<T> {
/** Used for the internal cache. */
private final Map<String, T> map;
/** Maximum size of the cache. */
private final int maxSize;
/** @param maxSize the maximum number of entries of the cache */
public LRUCache(final int maxSize) {
if (maxSize < 1) {
throw new IllegalArgumentException("maxSize " + maxSize + " must be at least 1");
}
this.maxSize = maxSize;
map = Collections.synchronizedMap(new LRUHashMap<>(maxSize));
}
/** Adds an entry to the cache, evicting the earliest entry if necessary. */
public T add(final String key, final T value) {
return map.put(key, value);
}
/** Returns the value of the given key; or null of no such entry exists. */
public T get(final String key) {
return map.get(key);
}
/** Returns the current size of the cache. */
public int size() {
return map.size();
}
/** Returns the maximum size of the cache. */
public int getMaxSize() {
return maxSize;
}
public void clear() {
map.clear();
}
public T remove(String key) {
return map.remove(key);
}
@Override
public String toString() {
return map.toString();
}
@SuppressWarnings("serial")
private static class LRUHashMap<T> extends LinkedHashMap<String, T> {
private final int maxSize;
private LRUHashMap(final int maxSize) {
super(10, 0.75F, true);
this.maxSize = maxSize;
}
@Override
protected boolean removeEldestEntry(final Entry<String, T> eldest) {
return size() > maxSize;
}
}
}
| 5,076 |
0 | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/main/sdkv1/com/amazonaws/services/dynamodbv2/datamodeling | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/main/sdkv1/com/amazonaws/services/dynamodbv2/datamodeling/internal/MsClock.java | /*
* Copyright 2020 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.services.dynamodbv2.datamodeling.internal;
interface MsClock {
MsClock WALLCLOCK = System::nanoTime;
public long timestampNano();
}
| 5,077 |
0 | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/main/sdkv1/com/amazonaws/services/dynamodbv2/datamodeling | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/main/sdkv1/com/amazonaws/services/dynamodbv2/datamodeling/internal/AttributeValueMarshaller.java | /*
* Copyright 2014 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.services.dynamodbv2.datamodeling.internal;
import com.amazonaws.services.dynamodbv2.model.AttributeValue;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/** @author Greg Rubin */
public class AttributeValueMarshaller {
private static final Charset UTF8 = Charset.forName("UTF-8");
private static final int TRUE_FLAG = 1;
private static final int FALSE_FLAG = 0;
private AttributeValueMarshaller() {
// Prevent instantiation
}
/**
* Marshalls the data using a TLV (Tag-Length-Value) encoding. The tag may be 'b', 'n', 's', '?',
* '\0' to represent a ByteBuffer, Number, String, Boolean, or Null respectively. The tag may also
* be capitalized (for 'b', 'n', and 's',) to represent an array of that type. If an array is
* stored, then a four-byte big-endian integer is written representing the number of array
* elements. If a ByteBuffer is stored, the length of the buffer is stored as a four-byte
* big-endian integer and the buffer then copied directly. Both Numbers and Strings are treated
* identically and are stored as UTF8 encoded Unicode, proceeded by the length of the encoded
* string (in bytes) as a four-byte big-endian integer. Boolean is encoded as a single byte, 0 for
* <code>false</code> and 1 for <code>true</code> (and so has no Length parameter). The Null tag
* ('\0') takes neither a Length nor a Value parameter.
*
* <p>The tags 'L' and 'M' are for the document types List and Map respectively. These are encoded
* recursively with the Length being the size of the collection. In the case of List, the value is
* a Length number of marshalled AttributeValues. If the case of Map, the value is a Length number
* of AttributeValue Pairs where the first must always have a String value.
*
* <p>This implementation does <em>not</em> recognize loops. If an AttributeValue contains itself
* (even indirectly) this code will recurse infinitely.
*
* @param attributeValue
* @return the serialized AttributeValue
* @see java.io.DataInput
*/
public static ByteBuffer marshall(final AttributeValue attributeValue) {
try (ByteArrayOutputStream resultBytes = new ByteArrayOutputStream();
DataOutputStream out = new DataOutputStream(resultBytes); ) {
marshall(attributeValue, out);
out.close();
resultBytes.close();
return ByteBuffer.wrap(resultBytes.toByteArray());
} catch (final IOException ex) {
// Due to the objects in use, an IOException is not possible.
throw new RuntimeException("Unexpected exception", ex);
}
}
private static void marshall(final AttributeValue attributeValue, final DataOutputStream out)
throws IOException {
if (attributeValue.getB() != null) {
out.writeChar('b');
writeBytes(attributeValue.getB(), out);
} else if (attributeValue.getBS() != null) {
out.writeChar('B');
writeBytesList(attributeValue.getBS(), out);
} else if (attributeValue.getN() != null) {
out.writeChar('n');
writeString(trimZeros(attributeValue.getN()), out);
} else if (attributeValue.getNS() != null) {
out.writeChar('N');
final List<String> ns = new ArrayList<String>(attributeValue.getNS().size());
for (final String n : attributeValue.getNS()) {
ns.add(trimZeros(n));
}
writeStringList(ns, out);
} else if (attributeValue.getS() != null) {
out.writeChar('s');
writeString(attributeValue.getS(), out);
} else if (attributeValue.getSS() != null) {
out.writeChar('S');
writeStringList(attributeValue.getSS(), out);
} else if (attributeValue.getBOOL() != null) {
out.writeChar('?');
out.writeByte((attributeValue.getBOOL() ? TRUE_FLAG : FALSE_FLAG));
} else if (Boolean.TRUE.equals(attributeValue.getNULL())) {
out.writeChar('\0');
} else if (attributeValue.getL() != null) {
final List<AttributeValue> l = attributeValue.getL();
out.writeChar('L');
out.writeInt(l.size());
for (final AttributeValue attr : l) {
if (attr == null) {
throw new NullPointerException(
"Encountered null list entry value while marshalling attribute value "
+ attributeValue);
}
marshall(attr, out);
}
} else if (attributeValue.getM() != null) {
final Map<String, AttributeValue> m = attributeValue.getM();
final List<String> mKeys = new ArrayList<String>(m.keySet());
Collections.sort(mKeys);
out.writeChar('M');
out.writeInt(m.size());
for (final String mKey : mKeys) {
marshall(new AttributeValue().withS(mKey), out);
final AttributeValue mValue = m.get(mKey);
if (mValue == null) {
throw new NullPointerException(
"Encountered null map value for key "
+ mKey
+ " while marshalling attribute value "
+ attributeValue);
}
marshall(mValue, out);
}
} else {
throw new IllegalArgumentException(
"A seemingly empty AttributeValue is indicative of invalid input or potential errors");
}
}
/** @see #marshall(AttributeValue) */
public static AttributeValue unmarshall(final ByteBuffer plainText) {
try (final DataInputStream in =
new DataInputStream(new ByteBufferInputStream(plainText.asReadOnlyBuffer()))) {
return unmarshall(in);
} catch (IOException ex) {
// Due to the objects in use, an IOException is not possible.
throw new RuntimeException("Unexpected exception", ex);
}
}
private static AttributeValue unmarshall(final DataInputStream in) throws IOException {
char type = in.readChar();
AttributeValue result = new AttributeValue();
switch (type) {
case '\0':
result.setNULL(Boolean.TRUE);
break;
case 'b':
result.setB(readBytes(in));
break;
case 'B':
result.setBS(readBytesList(in));
break;
case 'n':
result.setN(readString(in));
break;
case 'N':
result.setNS(readStringList(in));
break;
case 's':
result.setS(readString(in));
break;
case 'S':
result.setSS(readStringList(in));
break;
case '?':
final byte boolValue = in.readByte();
if (boolValue == TRUE_FLAG) {
result.setBOOL(Boolean.TRUE);
} else if (boolValue == FALSE_FLAG) {
result.setBOOL(Boolean.FALSE);
} else {
throw new IllegalArgumentException("Improperly formatted data");
}
break;
case 'L':
final int lCount = in.readInt();
final List<AttributeValue> l = new ArrayList<AttributeValue>(lCount);
for (int lIdx = 0; lIdx < lCount; lIdx++) {
l.add(unmarshall(in));
}
result.setL(l);
break;
case 'M':
final int mCount = in.readInt();
final Map<String, AttributeValue> m = new HashMap<String, AttributeValue>();
for (int mIdx = 0; mIdx < mCount; mIdx++) {
final AttributeValue key = unmarshall(in);
if (key.getS() == null) {
throw new IllegalArgumentException("Improperly formatted data");
}
AttributeValue value = unmarshall(in);
m.put(key.getS(), value);
}
result.setM(m);
break;
default:
throw new IllegalArgumentException("Unsupported data encoding");
}
return result;
}
private static String trimZeros(final String n) {
BigDecimal number = new BigDecimal(n);
if (number.compareTo(BigDecimal.ZERO) == 0) {
return "0";
}
return number.stripTrailingZeros().toPlainString();
}
private static void writeStringList(List<String> values, final DataOutputStream out)
throws IOException {
final List<String> sorted = new ArrayList<String>(values);
Collections.sort(sorted);
out.writeInt(sorted.size());
for (final String v : sorted) {
writeString(v, out);
}
}
private static List<String> readStringList(final DataInputStream in)
throws IOException, IllegalArgumentException {
final int nCount = in.readInt();
List<String> ns = new ArrayList<String>(nCount);
for (int nIdx = 0; nIdx < nCount; nIdx++) {
ns.add(readString(in));
}
return ns;
}
private static void writeString(String value, final DataOutputStream out) throws IOException {
final byte[] bytes = value.getBytes(UTF8);
out.writeInt(bytes.length);
out.write(bytes);
}
private static String readString(final DataInputStream in)
throws IOException, IllegalArgumentException {
byte[] bytes;
int length;
length = in.readInt();
bytes = new byte[length];
if (in.read(bytes) != length) {
throw new IllegalArgumentException("Improperly formatted data");
}
String tmp = new String(bytes, UTF8);
return tmp;
}
private static void writeBytesList(List<ByteBuffer> values, final DataOutputStream out)
throws IOException {
final List<ByteBuffer> sorted = new ArrayList<ByteBuffer>(values);
Collections.sort(sorted);
out.writeInt(sorted.size());
for (final ByteBuffer v : sorted) {
writeBytes(v, out);
}
}
private static List<ByteBuffer> readBytesList(final DataInputStream in) throws IOException {
final int bCount = in.readInt();
List<ByteBuffer> bs = new ArrayList<ByteBuffer>(bCount);
for (int bIdx = 0; bIdx < bCount; bIdx++) {
bs.add(readBytes(in));
}
return bs;
}
private static void writeBytes(ByteBuffer value, final DataOutputStream out) throws IOException {
value = value.asReadOnlyBuffer();
value.rewind();
out.writeInt(value.remaining());
while (value.hasRemaining()) {
out.writeByte(value.get());
}
}
private static ByteBuffer readBytes(final DataInputStream in) throws IOException {
final int length = in.readInt();
final byte[] buf = new byte[length];
in.readFully(buf);
return ByteBuffer.wrap(buf);
}
}
| 5,078 |
0 | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/main/sdkv1/com/amazonaws/services/dynamodbv2/datamodeling | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/main/sdkv1/com/amazonaws/services/dynamodbv2/datamodeling/internal/ByteBufferInputStream.java | /*
* Copyright 2014 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.services.dynamodbv2.datamodeling.internal;
import java.io.InputStream;
import java.nio.ByteBuffer;
/** @author Greg Rubin */
public class ByteBufferInputStream extends InputStream {
private final ByteBuffer buffer;
public ByteBufferInputStream(ByteBuffer buffer) {
this.buffer = buffer;
}
@Override
public int read() {
if (buffer.hasRemaining()) {
int tmp = buffer.get();
if (tmp < 0) {
tmp += 256;
}
return tmp;
} else {
return -1;
}
}
@Override
public int read(byte[] b, int off, int len) {
if (available() < len) {
len = available();
}
buffer.get(b, off, len);
return len;
}
@Override
public int available() {
return buffer.remaining();
}
}
| 5,079 |
0 | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/dbencryptionsdk | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/dbencryptionsdk/structuredencryption/ToNative.java | // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
// Do not modify this file. This file is machine generated, and any changes to it will be overwritten.
package software.amazon.cryptography.dbencryptionsdk.structuredencryption;
import dafny.DafnyMap;
import dafny.DafnySequence;
import java.lang.Character;
import java.lang.IllegalArgumentException;
import java.lang.RuntimeException;
import java.lang.String;
import java.util.List;
import java.util.Map;
import software.amazon.cryptography.dbencryptionsdk.structuredencryption.internaldafny.types.Error;
import software.amazon.cryptography.dbencryptionsdk.structuredencryption.internaldafny.types.Error_CollectionOfErrors;
import software.amazon.cryptography.dbencryptionsdk.structuredencryption.internaldafny.types.Error_Opaque;
import software.amazon.cryptography.dbencryptionsdk.structuredencryption.internaldafny.types.Error_StructuredEncryptionException;
import software.amazon.cryptography.dbencryptionsdk.structuredencryption.internaldafny.types.IStructuredEncryptionClient;
import software.amazon.cryptography.dbencryptionsdk.structuredencryption.model.AuthenticateAction;
import software.amazon.cryptography.dbencryptionsdk.structuredencryption.model.AuthenticateSchema;
import software.amazon.cryptography.dbencryptionsdk.structuredencryption.model.AuthenticateSchemaContent;
import software.amazon.cryptography.dbencryptionsdk.structuredencryption.model.CollectionOfErrors;
import software.amazon.cryptography.dbencryptionsdk.structuredencryption.model.CryptoAction;
import software.amazon.cryptography.dbencryptionsdk.structuredencryption.model.CryptoSchema;
import software.amazon.cryptography.dbencryptionsdk.structuredencryption.model.CryptoSchemaContent;
import software.amazon.cryptography.dbencryptionsdk.structuredencryption.model.DecryptStructureInput;
import software.amazon.cryptography.dbencryptionsdk.structuredencryption.model.DecryptStructureOutput;
import software.amazon.cryptography.dbencryptionsdk.structuredencryption.model.EncryptStructureInput;
import software.amazon.cryptography.dbencryptionsdk.structuredencryption.model.EncryptStructureOutput;
import software.amazon.cryptography.dbencryptionsdk.structuredencryption.model.OpaqueError;
import software.amazon.cryptography.dbencryptionsdk.structuredencryption.model.ParsedHeader;
import software.amazon.cryptography.dbencryptionsdk.structuredencryption.model.StructuredData;
import software.amazon.cryptography.dbencryptionsdk.structuredencryption.model.StructuredDataContent;
import software.amazon.cryptography.dbencryptionsdk.structuredencryption.model.StructuredDataTerminal;
import software.amazon.cryptography.dbencryptionsdk.structuredencryption.model.StructuredEncryptionConfig;
import software.amazon.cryptography.dbencryptionsdk.structuredencryption.model.StructuredEncryptionException;
public class ToNative {
public static OpaqueError Error(Error_Opaque dafnyValue) {
OpaqueError.Builder nativeBuilder = OpaqueError.builder();
nativeBuilder.obj(dafnyValue.dtor_obj());
return nativeBuilder.build();
}
public static CollectionOfErrors Error(Error_CollectionOfErrors dafnyValue) {
CollectionOfErrors.Builder nativeBuilder = CollectionOfErrors.builder();
nativeBuilder.list(
software.amazon.smithy.dafny.conversion.ToNative.Aggregate.GenericToList(
dafnyValue.dtor_list(),
ToNative::Error));
nativeBuilder.message(software.amazon.smithy.dafny.conversion.ToNative.Simple.String(dafnyValue.dtor_message()));
return nativeBuilder.build();
}
public static StructuredEncryptionException Error(
Error_StructuredEncryptionException dafnyValue) {
StructuredEncryptionException.Builder nativeBuilder = StructuredEncryptionException.builder();
nativeBuilder.message(software.amazon.smithy.dafny.conversion.ToNative.Simple.String(dafnyValue.dtor_message()));
return nativeBuilder.build();
}
public static RuntimeException Error(Error dafnyValue) {
if (dafnyValue.is_StructuredEncryptionException()) {
return ToNative.Error((Error_StructuredEncryptionException) dafnyValue);
}
if (dafnyValue.is_Opaque()) {
return ToNative.Error((Error_Opaque) dafnyValue);
}
if (dafnyValue.is_CollectionOfErrors()) {
return ToNative.Error((Error_CollectionOfErrors) dafnyValue);
}
if (dafnyValue.is_AwsCryptographyPrimitives()) {
return software.amazon.cryptography.primitives.ToNative.Error(dafnyValue.dtor_AwsCryptographyPrimitives());
}
if (dafnyValue.is_AwsCryptographyMaterialProviders()) {
return software.amazon.cryptography.materialproviders.ToNative.Error(dafnyValue.dtor_AwsCryptographyMaterialProviders());
}
OpaqueError.Builder nativeBuilder = OpaqueError.builder();
nativeBuilder.obj(dafnyValue);
return nativeBuilder.build();
}
public static AuthenticateSchema AuthenticateSchema(
software.amazon.cryptography.dbencryptionsdk.structuredencryption.internaldafny.types.AuthenticateSchema dafnyValue) {
AuthenticateSchema.Builder nativeBuilder = AuthenticateSchema.builder();
nativeBuilder.content(ToNative.AuthenticateSchemaContent(dafnyValue.dtor_content()));
if (dafnyValue.dtor_attributes().is_Some()) {
nativeBuilder.attributes(ToNative.AuthenticateSchemaAttributes(dafnyValue.dtor_attributes().dtor_value()));
}
return nativeBuilder.build();
}
public static CryptoSchema CryptoSchema(
software.amazon.cryptography.dbencryptionsdk.structuredencryption.internaldafny.types.CryptoSchema dafnyValue) {
CryptoSchema.Builder nativeBuilder = CryptoSchema.builder();
nativeBuilder.content(ToNative.CryptoSchemaContent(dafnyValue.dtor_content()));
if (dafnyValue.dtor_attributes().is_Some()) {
nativeBuilder.attributes(ToNative.CryptoSchemaAttributes(dafnyValue.dtor_attributes().dtor_value()));
}
return nativeBuilder.build();
}
public static DecryptStructureInput DecryptStructureInput(
software.amazon.cryptography.dbencryptionsdk.structuredencryption.internaldafny.types.DecryptStructureInput dafnyValue) {
DecryptStructureInput.Builder nativeBuilder = DecryptStructureInput.builder();
nativeBuilder.tableName(software.amazon.smithy.dafny.conversion.ToNative.Simple.String(dafnyValue.dtor_tableName()));
nativeBuilder.encryptedStructure(ToNative.StructuredData(dafnyValue.dtor_encryptedStructure()));
nativeBuilder.authenticateSchema(ToNative.AuthenticateSchema(dafnyValue.dtor_authenticateSchema()));
nativeBuilder.cmm(software.amazon.cryptography.materialproviders.ToNative.CryptographicMaterialsManager(dafnyValue.dtor_cmm()));
if (dafnyValue.dtor_encryptionContext().is_Some()) {
nativeBuilder.encryptionContext(software.amazon.cryptography.materialproviders.ToNative.EncryptionContext(dafnyValue.dtor_encryptionContext().dtor_value()));
}
return nativeBuilder.build();
}
public static DecryptStructureOutput DecryptStructureOutput(
software.amazon.cryptography.dbencryptionsdk.structuredencryption.internaldafny.types.DecryptStructureOutput dafnyValue) {
DecryptStructureOutput.Builder nativeBuilder = DecryptStructureOutput.builder();
nativeBuilder.plaintextStructure(ToNative.StructuredData(dafnyValue.dtor_plaintextStructure()));
nativeBuilder.parsedHeader(ToNative.ParsedHeader(dafnyValue.dtor_parsedHeader()));
return nativeBuilder.build();
}
public static EncryptStructureInput EncryptStructureInput(
software.amazon.cryptography.dbencryptionsdk.structuredencryption.internaldafny.types.EncryptStructureInput dafnyValue) {
EncryptStructureInput.Builder nativeBuilder = EncryptStructureInput.builder();
nativeBuilder.tableName(software.amazon.smithy.dafny.conversion.ToNative.Simple.String(dafnyValue.dtor_tableName()));
nativeBuilder.plaintextStructure(ToNative.StructuredData(dafnyValue.dtor_plaintextStructure()));
nativeBuilder.cryptoSchema(ToNative.CryptoSchema(dafnyValue.dtor_cryptoSchema()));
nativeBuilder.cmm(software.amazon.cryptography.materialproviders.ToNative.CryptographicMaterialsManager(dafnyValue.dtor_cmm()));
if (dafnyValue.dtor_algorithmSuiteId().is_Some()) {
nativeBuilder.algorithmSuiteId(software.amazon.cryptography.materialproviders.ToNative.DBEAlgorithmSuiteId(dafnyValue.dtor_algorithmSuiteId().dtor_value()));
}
if (dafnyValue.dtor_encryptionContext().is_Some()) {
nativeBuilder.encryptionContext(software.amazon.cryptography.materialproviders.ToNative.EncryptionContext(dafnyValue.dtor_encryptionContext().dtor_value()));
}
return nativeBuilder.build();
}
public static EncryptStructureOutput EncryptStructureOutput(
software.amazon.cryptography.dbencryptionsdk.structuredencryption.internaldafny.types.EncryptStructureOutput dafnyValue) {
EncryptStructureOutput.Builder nativeBuilder = EncryptStructureOutput.builder();
nativeBuilder.encryptedStructure(ToNative.StructuredData(dafnyValue.dtor_encryptedStructure()));
nativeBuilder.parsedHeader(ToNative.ParsedHeader(dafnyValue.dtor_parsedHeader()));
return nativeBuilder.build();
}
public static ParsedHeader ParsedHeader(
software.amazon.cryptography.dbencryptionsdk.structuredencryption.internaldafny.types.ParsedHeader dafnyValue) {
ParsedHeader.Builder nativeBuilder = ParsedHeader.builder();
nativeBuilder.cryptoSchema(ToNative.CryptoSchema(dafnyValue.dtor_cryptoSchema()));
nativeBuilder.algorithmSuiteId(software.amazon.cryptography.materialproviders.ToNative.DBEAlgorithmSuiteId(dafnyValue.dtor_algorithmSuiteId()));
nativeBuilder.encryptedDataKeys(software.amazon.cryptography.materialproviders.ToNative.EncryptedDataKeyList(dafnyValue.dtor_encryptedDataKeys()));
nativeBuilder.storedEncryptionContext(software.amazon.cryptography.materialproviders.ToNative.EncryptionContext(dafnyValue.dtor_storedEncryptionContext()));
return nativeBuilder.build();
}
public static StructuredData StructuredData(
software.amazon.cryptography.dbencryptionsdk.structuredencryption.internaldafny.types.StructuredData dafnyValue) {
StructuredData.Builder nativeBuilder = StructuredData.builder();
nativeBuilder.content(ToNative.StructuredDataContent(dafnyValue.dtor_content()));
if (dafnyValue.dtor_attributes().is_Some()) {
nativeBuilder.attributes(ToNative.StructuredDataAttributes(dafnyValue.dtor_attributes().dtor_value()));
}
return nativeBuilder.build();
}
public static StructuredDataTerminal StructuredDataTerminal(
software.amazon.cryptography.dbencryptionsdk.structuredencryption.internaldafny.types.StructuredDataTerminal dafnyValue) {
StructuredDataTerminal.Builder nativeBuilder = StructuredDataTerminal.builder();
nativeBuilder.value(software.amazon.smithy.dafny.conversion.ToNative.Simple.ByteBuffer(dafnyValue.dtor_value()));
nativeBuilder.typeId(software.amazon.smithy.dafny.conversion.ToNative.Simple.ByteBuffer(dafnyValue.dtor_typeId()));
return nativeBuilder.build();
}
public static StructuredEncryptionConfig StructuredEncryptionConfig(
software.amazon.cryptography.dbencryptionsdk.structuredencryption.internaldafny.types.StructuredEncryptionConfig dafnyValue) {
StructuredEncryptionConfig.Builder nativeBuilder = StructuredEncryptionConfig.builder();
return nativeBuilder.build();
}
public static AuthenticateAction AuthenticateAction(
software.amazon.cryptography.dbencryptionsdk.structuredencryption.internaldafny.types.AuthenticateAction dafnyValue) {
if (dafnyValue.is_SIGN()) {
return AuthenticateAction.SIGN;
}
if (dafnyValue.is_DO__NOT__SIGN()) {
return AuthenticateAction.DO_NOT_SIGN;
}
throw new IllegalArgumentException("No entry of software.amazon.cryptography.dbencryptionsdk.structuredencryption.model.AuthenticateAction matches the input : " + dafnyValue);
}
public static CryptoAction CryptoAction(
software.amazon.cryptography.dbencryptionsdk.structuredencryption.internaldafny.types.CryptoAction dafnyValue) {
if (dafnyValue.is_ENCRYPT__AND__SIGN()) {
return CryptoAction.ENCRYPT_AND_SIGN;
}
if (dafnyValue.is_SIGN__ONLY()) {
return CryptoAction.SIGN_ONLY;
}
if (dafnyValue.is_DO__NOTHING()) {
return CryptoAction.DO_NOTHING;
}
throw new IllegalArgumentException("No entry of software.amazon.cryptography.dbencryptionsdk.structuredencryption.model.CryptoAction matches the input : " + dafnyValue);
}
public static AuthenticateSchemaContent AuthenticateSchemaContent(
software.amazon.cryptography.dbencryptionsdk.structuredencryption.internaldafny.types.AuthenticateSchemaContent dafnyValue) {
AuthenticateSchemaContent.Builder nativeBuilder = AuthenticateSchemaContent.builder();
if (dafnyValue.is_Action()) {
nativeBuilder.Action(ToNative.AuthenticateAction(dafnyValue.dtor_Action()));
}
if (dafnyValue.is_SchemaMap()) {
nativeBuilder.SchemaMap(ToNative.AuthenticateSchemaMap(dafnyValue.dtor_SchemaMap()));
}
if (dafnyValue.is_SchemaList()) {
nativeBuilder.SchemaList(ToNative.AuthenticateSchemaList(dafnyValue.dtor_SchemaList()));
}
return nativeBuilder.build();
}
public static CryptoSchemaContent CryptoSchemaContent(
software.amazon.cryptography.dbencryptionsdk.structuredencryption.internaldafny.types.CryptoSchemaContent dafnyValue) {
CryptoSchemaContent.Builder nativeBuilder = CryptoSchemaContent.builder();
if (dafnyValue.is_Action()) {
nativeBuilder.Action(ToNative.CryptoAction(dafnyValue.dtor_Action()));
}
if (dafnyValue.is_SchemaMap()) {
nativeBuilder.SchemaMap(ToNative.CryptoSchemaMap(dafnyValue.dtor_SchemaMap()));
}
if (dafnyValue.is_SchemaList()) {
nativeBuilder.SchemaList(ToNative.CryptoSchemaList(dafnyValue.dtor_SchemaList()));
}
return nativeBuilder.build();
}
public static StructuredDataContent StructuredDataContent(
software.amazon.cryptography.dbencryptionsdk.structuredencryption.internaldafny.types.StructuredDataContent dafnyValue) {
StructuredDataContent.Builder nativeBuilder = StructuredDataContent.builder();
if (dafnyValue.is_Terminal()) {
nativeBuilder.Terminal(ToNative.StructuredDataTerminal(dafnyValue.dtor_Terminal()));
}
if (dafnyValue.is_DataList()) {
nativeBuilder.DataList(ToNative.StructuredDataList(dafnyValue.dtor_DataList()));
}
if (dafnyValue.is_DataMap()) {
nativeBuilder.DataMap(ToNative.StructuredDataMap(dafnyValue.dtor_DataMap()));
}
return nativeBuilder.build();
}
public static List<AuthenticateSchema> AuthenticateSchemaList(
DafnySequence<? extends software.amazon.cryptography.dbencryptionsdk.structuredencryption.internaldafny.types.AuthenticateSchema> dafnyValue) {
return software.amazon.smithy.dafny.conversion.ToNative.Aggregate.GenericToList(
dafnyValue,
software.amazon.cryptography.dbencryptionsdk.structuredencryption.ToNative::AuthenticateSchema);
}
public static List<CryptoSchema> CryptoSchemaList(
DafnySequence<? extends software.amazon.cryptography.dbencryptionsdk.structuredencryption.internaldafny.types.CryptoSchema> dafnyValue) {
return software.amazon.smithy.dafny.conversion.ToNative.Aggregate.GenericToList(
dafnyValue,
software.amazon.cryptography.dbencryptionsdk.structuredencryption.ToNative::CryptoSchema);
}
public static List<StructuredData> StructuredDataList(
DafnySequence<? extends software.amazon.cryptography.dbencryptionsdk.structuredencryption.internaldafny.types.StructuredData> dafnyValue) {
return software.amazon.smithy.dafny.conversion.ToNative.Aggregate.GenericToList(
dafnyValue,
software.amazon.cryptography.dbencryptionsdk.structuredencryption.ToNative::StructuredData);
}
public static Map<String, AuthenticateAction> AuthenticateSchemaAttributes(
DafnyMap<? extends DafnySequence<? extends Character>, ? extends software.amazon.cryptography.dbencryptionsdk.structuredencryption.internaldafny.types.AuthenticateAction> dafnyValue) {
return software.amazon.smithy.dafny.conversion.ToNative.Aggregate.GenericToMap(
dafnyValue,
software.amazon.smithy.dafny.conversion.ToNative.Simple::String,
software.amazon.cryptography.dbencryptionsdk.structuredencryption.ToNative::AuthenticateAction);
}
public static Map<String, AuthenticateSchema> AuthenticateSchemaMap(
DafnyMap<? extends DafnySequence<? extends Character>, ? extends software.amazon.cryptography.dbencryptionsdk.structuredencryption.internaldafny.types.AuthenticateSchema> dafnyValue) {
return software.amazon.smithy.dafny.conversion.ToNative.Aggregate.GenericToMap(
dafnyValue,
software.amazon.smithy.dafny.conversion.ToNative.Simple::String,
software.amazon.cryptography.dbencryptionsdk.structuredencryption.ToNative::AuthenticateSchema);
}
public static Map<String, AuthenticateAction> CryptoSchemaAttributes(
DafnyMap<? extends DafnySequence<? extends Character>, ? extends software.amazon.cryptography.dbencryptionsdk.structuredencryption.internaldafny.types.AuthenticateAction> dafnyValue) {
return software.amazon.smithy.dafny.conversion.ToNative.Aggregate.GenericToMap(
dafnyValue,
software.amazon.smithy.dafny.conversion.ToNative.Simple::String,
software.amazon.cryptography.dbencryptionsdk.structuredencryption.ToNative::AuthenticateAction);
}
public static Map<String, CryptoSchema> CryptoSchemaMap(
DafnyMap<? extends DafnySequence<? extends Character>, ? extends software.amazon.cryptography.dbencryptionsdk.structuredencryption.internaldafny.types.CryptoSchema> dafnyValue) {
return software.amazon.smithy.dafny.conversion.ToNative.Aggregate.GenericToMap(
dafnyValue,
software.amazon.smithy.dafny.conversion.ToNative.Simple::String,
software.amazon.cryptography.dbencryptionsdk.structuredencryption.ToNative::CryptoSchema);
}
public static Map<String, StructuredDataTerminal> StructuredDataAttributes(
DafnyMap<? extends DafnySequence<? extends Character>, ? extends software.amazon.cryptography.dbencryptionsdk.structuredencryption.internaldafny.types.StructuredDataTerminal> dafnyValue) {
return software.amazon.smithy.dafny.conversion.ToNative.Aggregate.GenericToMap(
dafnyValue,
software.amazon.smithy.dafny.conversion.ToNative.Simple::String,
software.amazon.cryptography.dbencryptionsdk.structuredencryption.ToNative::StructuredDataTerminal);
}
public static Map<String, StructuredData> StructuredDataMap(
DafnyMap<? extends DafnySequence<? extends Character>, ? extends software.amazon.cryptography.dbencryptionsdk.structuredencryption.internaldafny.types.StructuredData> dafnyValue) {
return software.amazon.smithy.dafny.conversion.ToNative.Aggregate.GenericToMap(
dafnyValue,
software.amazon.smithy.dafny.conversion.ToNative.Simple::String,
software.amazon.cryptography.dbencryptionsdk.structuredencryption.ToNative::StructuredData);
}
public static StructuredEncryption StructuredEncryption(IStructuredEncryptionClient dafnyValue) {
return new StructuredEncryption(dafnyValue);
}
}
| 5,080 |
0 | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/dbencryptionsdk | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/dbencryptionsdk/structuredencryption/StructuredEncryption.java | // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
// Do not modify this file. This file is machine generated, and any changes to it will be overwritten.
package software.amazon.cryptography.dbencryptionsdk.structuredencryption;
import Wrappers_Compile.Result;
import java.lang.IllegalArgumentException;
import java.util.Objects;
import software.amazon.cryptography.dbencryptionsdk.structuredencryption.internaldafny.StructuredEncryptionClient;
import software.amazon.cryptography.dbencryptionsdk.structuredencryption.internaldafny.__default;
import software.amazon.cryptography.dbencryptionsdk.structuredencryption.internaldafny.types.Error;
import software.amazon.cryptography.dbencryptionsdk.structuredencryption.internaldafny.types.IStructuredEncryptionClient;
import software.amazon.cryptography.dbencryptionsdk.structuredencryption.model.DecryptStructureInput;
import software.amazon.cryptography.dbencryptionsdk.structuredencryption.model.DecryptStructureOutput;
import software.amazon.cryptography.dbencryptionsdk.structuredencryption.model.EncryptStructureInput;
import software.amazon.cryptography.dbencryptionsdk.structuredencryption.model.EncryptStructureOutput;
import software.amazon.cryptography.dbencryptionsdk.structuredencryption.model.StructuredEncryptionConfig;
public class StructuredEncryption {
private final IStructuredEncryptionClient _impl;
protected StructuredEncryption(BuilderImpl builder) {
StructuredEncryptionConfig input = builder.StructuredEncryptionConfig();
software.amazon.cryptography.dbencryptionsdk.structuredencryption.internaldafny.types.StructuredEncryptionConfig dafnyValue = ToDafny.StructuredEncryptionConfig(input);
Result<StructuredEncryptionClient, Error> result = __default.StructuredEncryption(dafnyValue);
if (result.is_Failure()) {
throw ToNative.Error(result.dtor_error());
}
this._impl = result.dtor_value();
}
StructuredEncryption(IStructuredEncryptionClient impl) {
this._impl = impl;
}
public static Builder builder() {
return new BuilderImpl();
}
public DecryptStructureOutput DecryptStructure(DecryptStructureInput input) {
software.amazon.cryptography.dbencryptionsdk.structuredencryption.internaldafny.types.DecryptStructureInput dafnyValue = ToDafny.DecryptStructureInput(input);
Result<software.amazon.cryptography.dbencryptionsdk.structuredencryption.internaldafny.types.DecryptStructureOutput, Error> result = this._impl.DecryptStructure(dafnyValue);
if (result.is_Failure()) {
throw ToNative.Error(result.dtor_error());
}
return ToNative.DecryptStructureOutput(result.dtor_value());
}
public EncryptStructureOutput EncryptStructure(EncryptStructureInput input) {
software.amazon.cryptography.dbencryptionsdk.structuredencryption.internaldafny.types.EncryptStructureInput dafnyValue = ToDafny.EncryptStructureInput(input);
Result<software.amazon.cryptography.dbencryptionsdk.structuredencryption.internaldafny.types.EncryptStructureOutput, Error> result = this._impl.EncryptStructure(dafnyValue);
if (result.is_Failure()) {
throw ToNative.Error(result.dtor_error());
}
return ToNative.EncryptStructureOutput(result.dtor_value());
}
protected IStructuredEncryptionClient impl() {
return this._impl;
}
public interface Builder {
Builder StructuredEncryptionConfig(StructuredEncryptionConfig StructuredEncryptionConfig);
StructuredEncryptionConfig StructuredEncryptionConfig();
StructuredEncryption build();
}
static class BuilderImpl implements Builder {
protected StructuredEncryptionConfig StructuredEncryptionConfig;
protected BuilderImpl() {
}
public Builder StructuredEncryptionConfig(
StructuredEncryptionConfig StructuredEncryptionConfig) {
this.StructuredEncryptionConfig = StructuredEncryptionConfig;
return this;
}
public StructuredEncryptionConfig StructuredEncryptionConfig() {
return this.StructuredEncryptionConfig;
}
public StructuredEncryption build() {
if (Objects.isNull(this.StructuredEncryptionConfig())) {
throw new IllegalArgumentException("Missing value for required field `StructuredEncryptionConfig`");
}
return new StructuredEncryption(this);
}
}
}
| 5,081 |
0 | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/dbencryptionsdk | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/dbencryptionsdk/structuredencryption/ToDafny.java | // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
// Do not modify this file. This file is machine generated, and any changes to it will be overwritten.
package software.amazon.cryptography.dbencryptionsdk.structuredencryption;
import Wrappers_Compile.Option;
import dafny.DafnyMap;
import dafny.DafnySequence;
import java.lang.Byte;
import java.lang.Character;
import java.lang.IllegalArgumentException;
import java.lang.RuntimeException;
import java.lang.String;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import software.amazon.cryptography.dbencryptionsdk.structuredencryption.internaldafny.types.AuthenticateAction;
import software.amazon.cryptography.dbencryptionsdk.structuredencryption.internaldafny.types.AuthenticateSchema;
import software.amazon.cryptography.dbencryptionsdk.structuredencryption.internaldafny.types.AuthenticateSchemaContent;
import software.amazon.cryptography.dbencryptionsdk.structuredencryption.internaldafny.types.CryptoAction;
import software.amazon.cryptography.dbencryptionsdk.structuredencryption.internaldafny.types.CryptoSchema;
import software.amazon.cryptography.dbencryptionsdk.structuredencryption.internaldafny.types.CryptoSchemaContent;
import software.amazon.cryptography.dbencryptionsdk.structuredencryption.internaldafny.types.DecryptStructureInput;
import software.amazon.cryptography.dbencryptionsdk.structuredencryption.internaldafny.types.DecryptStructureOutput;
import software.amazon.cryptography.dbencryptionsdk.structuredencryption.internaldafny.types.EncryptStructureInput;
import software.amazon.cryptography.dbencryptionsdk.structuredencryption.internaldafny.types.EncryptStructureOutput;
import software.amazon.cryptography.dbencryptionsdk.structuredencryption.internaldafny.types.Error;
import software.amazon.cryptography.dbencryptionsdk.structuredencryption.internaldafny.types.Error_StructuredEncryptionException;
import software.amazon.cryptography.dbencryptionsdk.structuredencryption.internaldafny.types.IStructuredEncryptionClient;
import software.amazon.cryptography.dbencryptionsdk.structuredencryption.internaldafny.types.ParsedHeader;
import software.amazon.cryptography.dbencryptionsdk.structuredencryption.internaldafny.types.StructuredData;
import software.amazon.cryptography.dbencryptionsdk.structuredencryption.internaldafny.types.StructuredDataContent;
import software.amazon.cryptography.dbencryptionsdk.structuredencryption.internaldafny.types.StructuredDataTerminal;
import software.amazon.cryptography.dbencryptionsdk.structuredencryption.internaldafny.types.StructuredEncryptionConfig;
import software.amazon.cryptography.dbencryptionsdk.structuredencryption.model.CollectionOfErrors;
import software.amazon.cryptography.dbencryptionsdk.structuredencryption.model.OpaqueError;
import software.amazon.cryptography.dbencryptionsdk.structuredencryption.model.StructuredEncryptionException;
import software.amazon.cryptography.materialproviders.internaldafny.types.DBEAlgorithmSuiteId;
import software.amazon.cryptography.materialproviders.internaldafny.types.EncryptedDataKey;
import software.amazon.cryptography.materialproviders.internaldafny.types.ICryptographicMaterialsManager;
public class ToDafny {
public static Error Error(RuntimeException nativeValue) {
if (nativeValue instanceof StructuredEncryptionException) {
return ToDafny.Error((StructuredEncryptionException) nativeValue);
}
if (nativeValue instanceof OpaqueError) {
return ToDafny.Error((OpaqueError) nativeValue);
}
if (nativeValue instanceof CollectionOfErrors) {
return ToDafny.Error((CollectionOfErrors) nativeValue);
}
return Error.create_Opaque(nativeValue);
}
public static Error Error(OpaqueError nativeValue) {
return Error.create_Opaque(nativeValue.obj());
}
public static Error Error(CollectionOfErrors nativeValue) {
DafnySequence<? extends Error> list = software.amazon.smithy.dafny.conversion.ToDafny.Aggregate.GenericToSequence(
nativeValue.list(),
ToDafny::Error,
Error._typeDescriptor());
DafnySequence<? extends Character> message = software.amazon.smithy.dafny.conversion.ToDafny.Simple.CharacterSequence(nativeValue.getMessage());
return Error.create_CollectionOfErrors(list, message);
}
public static AuthenticateSchema AuthenticateSchema(
software.amazon.cryptography.dbencryptionsdk.structuredencryption.model.AuthenticateSchema nativeValue) {
AuthenticateSchemaContent content;
content = ToDafny.AuthenticateSchemaContent(nativeValue.content());
Option<DafnyMap<? extends DafnySequence<? extends Character>, ? extends AuthenticateAction>> attributes;
attributes = (Objects.nonNull(nativeValue.attributes()) && nativeValue.attributes().size() > 0) ?
Option.create_Some(ToDafny.AuthenticateSchemaAttributes(nativeValue.attributes()))
: Option.create_None();
return new AuthenticateSchema(content, attributes);
}
public static CryptoSchema CryptoSchema(
software.amazon.cryptography.dbencryptionsdk.structuredencryption.model.CryptoSchema nativeValue) {
CryptoSchemaContent content;
content = ToDafny.CryptoSchemaContent(nativeValue.content());
Option<DafnyMap<? extends DafnySequence<? extends Character>, ? extends AuthenticateAction>> attributes;
attributes = (Objects.nonNull(nativeValue.attributes()) && nativeValue.attributes().size() > 0) ?
Option.create_Some(ToDafny.CryptoSchemaAttributes(nativeValue.attributes()))
: Option.create_None();
return new CryptoSchema(content, attributes);
}
public static DecryptStructureInput DecryptStructureInput(
software.amazon.cryptography.dbencryptionsdk.structuredencryption.model.DecryptStructureInput nativeValue) {
DafnySequence<? extends Character> tableName;
tableName = software.amazon.smithy.dafny.conversion.ToDafny.Simple.CharacterSequence(nativeValue.tableName());
StructuredData encryptedStructure;
encryptedStructure = ToDafny.StructuredData(nativeValue.encryptedStructure());
AuthenticateSchema authenticateSchema;
authenticateSchema = ToDafny.AuthenticateSchema(nativeValue.authenticateSchema());
ICryptographicMaterialsManager cmm;
cmm = software.amazon.cryptography.materialproviders.ToDafny.CryptographicMaterialsManager(nativeValue.cmm());
Option<DafnyMap<? extends DafnySequence<? extends Byte>, ? extends DafnySequence<? extends Byte>>> encryptionContext;
encryptionContext = (Objects.nonNull(nativeValue.encryptionContext()) && nativeValue.encryptionContext().size() > 0) ?
Option.create_Some(software.amazon.cryptography.materialproviders.ToDafny.EncryptionContext(nativeValue.encryptionContext()))
: Option.create_None();
return new DecryptStructureInput(tableName, encryptedStructure, authenticateSchema, cmm, encryptionContext);
}
public static DecryptStructureOutput DecryptStructureOutput(
software.amazon.cryptography.dbencryptionsdk.structuredencryption.model.DecryptStructureOutput nativeValue) {
StructuredData plaintextStructure;
plaintextStructure = ToDafny.StructuredData(nativeValue.plaintextStructure());
ParsedHeader parsedHeader;
parsedHeader = ToDafny.ParsedHeader(nativeValue.parsedHeader());
return new DecryptStructureOutput(plaintextStructure, parsedHeader);
}
public static EncryptStructureInput EncryptStructureInput(
software.amazon.cryptography.dbencryptionsdk.structuredencryption.model.EncryptStructureInput nativeValue) {
DafnySequence<? extends Character> tableName;
tableName = software.amazon.smithy.dafny.conversion.ToDafny.Simple.CharacterSequence(nativeValue.tableName());
StructuredData plaintextStructure;
plaintextStructure = ToDafny.StructuredData(nativeValue.plaintextStructure());
CryptoSchema cryptoSchema;
cryptoSchema = ToDafny.CryptoSchema(nativeValue.cryptoSchema());
ICryptographicMaterialsManager cmm;
cmm = software.amazon.cryptography.materialproviders.ToDafny.CryptographicMaterialsManager(nativeValue.cmm());
Option<DBEAlgorithmSuiteId> algorithmSuiteId;
algorithmSuiteId = Objects.nonNull(nativeValue.algorithmSuiteId()) ?
Option.create_Some(software.amazon.cryptography.materialproviders.ToDafny.DBEAlgorithmSuiteId(nativeValue.algorithmSuiteId()))
: Option.create_None();
Option<DafnyMap<? extends DafnySequence<? extends Byte>, ? extends DafnySequence<? extends Byte>>> encryptionContext;
encryptionContext = (Objects.nonNull(nativeValue.encryptionContext()) && nativeValue.encryptionContext().size() > 0) ?
Option.create_Some(software.amazon.cryptography.materialproviders.ToDafny.EncryptionContext(nativeValue.encryptionContext()))
: Option.create_None();
return new EncryptStructureInput(tableName, plaintextStructure, cryptoSchema, cmm, algorithmSuiteId, encryptionContext);
}
public static EncryptStructureOutput EncryptStructureOutput(
software.amazon.cryptography.dbencryptionsdk.structuredencryption.model.EncryptStructureOutput nativeValue) {
StructuredData encryptedStructure;
encryptedStructure = ToDafny.StructuredData(nativeValue.encryptedStructure());
ParsedHeader parsedHeader;
parsedHeader = ToDafny.ParsedHeader(nativeValue.parsedHeader());
return new EncryptStructureOutput(encryptedStructure, parsedHeader);
}
public static ParsedHeader ParsedHeader(
software.amazon.cryptography.dbencryptionsdk.structuredencryption.model.ParsedHeader nativeValue) {
CryptoSchema cryptoSchema;
cryptoSchema = ToDafny.CryptoSchema(nativeValue.cryptoSchema());
DBEAlgorithmSuiteId algorithmSuiteId;
algorithmSuiteId = software.amazon.cryptography.materialproviders.ToDafny.DBEAlgorithmSuiteId(nativeValue.algorithmSuiteId());
DafnySequence<? extends EncryptedDataKey> encryptedDataKeys;
encryptedDataKeys = software.amazon.cryptography.materialproviders.ToDafny.EncryptedDataKeyList(nativeValue.encryptedDataKeys());
DafnyMap<? extends DafnySequence<? extends Byte>, ? extends DafnySequence<? extends Byte>> storedEncryptionContext;
storedEncryptionContext = software.amazon.cryptography.materialproviders.ToDafny.EncryptionContext(nativeValue.storedEncryptionContext());
return new ParsedHeader(cryptoSchema, algorithmSuiteId, encryptedDataKeys, storedEncryptionContext);
}
public static StructuredData StructuredData(
software.amazon.cryptography.dbencryptionsdk.structuredencryption.model.StructuredData nativeValue) {
StructuredDataContent content;
content = ToDafny.StructuredDataContent(nativeValue.content());
Option<DafnyMap<? extends DafnySequence<? extends Character>, ? extends StructuredDataTerminal>> attributes;
attributes = (Objects.nonNull(nativeValue.attributes()) && nativeValue.attributes().size() > 0) ?
Option.create_Some(ToDafny.StructuredDataAttributes(nativeValue.attributes()))
: Option.create_None();
return new StructuredData(content, attributes);
}
public static StructuredDataTerminal StructuredDataTerminal(
software.amazon.cryptography.dbencryptionsdk.structuredencryption.model.StructuredDataTerminal nativeValue) {
DafnySequence<? extends Byte> value;
value = software.amazon.smithy.dafny.conversion.ToDafny.Simple.ByteSequence(nativeValue.value());
DafnySequence<? extends Byte> typeId;
typeId = software.amazon.smithy.dafny.conversion.ToDafny.Simple.ByteSequence(nativeValue.typeId());
return new StructuredDataTerminal(value, typeId);
}
public static StructuredEncryptionConfig StructuredEncryptionConfig(
software.amazon.cryptography.dbencryptionsdk.structuredencryption.model.StructuredEncryptionConfig nativeValue) {
return new StructuredEncryptionConfig();
}
public static Error Error(StructuredEncryptionException nativeValue) {
DafnySequence<? extends Character> message;
message = software.amazon.smithy.dafny.conversion.ToDafny.Simple.CharacterSequence(nativeValue.message());
return new Error_StructuredEncryptionException(message);
}
public static AuthenticateAction AuthenticateAction(
software.amazon.cryptography.dbencryptionsdk.structuredencryption.model.AuthenticateAction nativeValue) {
switch (nativeValue) {
case SIGN: {
return AuthenticateAction.create_SIGN();
}
case DO_NOT_SIGN: {
return AuthenticateAction.create_DO__NOT__SIGN();
}
default: {
throw new RuntimeException("Cannot convert " + nativeValue + " to software.amazon.cryptography.dbencryptionsdk.structuredencryption.internaldafny.types.AuthenticateAction.");
}
}
}
public static CryptoAction CryptoAction(
software.amazon.cryptography.dbencryptionsdk.structuredencryption.model.CryptoAction nativeValue) {
switch (nativeValue) {
case ENCRYPT_AND_SIGN: {
return CryptoAction.create_ENCRYPT__AND__SIGN();
}
case SIGN_ONLY: {
return CryptoAction.create_SIGN__ONLY();
}
case DO_NOTHING: {
return CryptoAction.create_DO__NOTHING();
}
default: {
throw new RuntimeException("Cannot convert " + nativeValue + " to software.amazon.cryptography.dbencryptionsdk.structuredencryption.internaldafny.types.CryptoAction.");
}
}
}
public static AuthenticateSchemaContent AuthenticateSchemaContent(
software.amazon.cryptography.dbencryptionsdk.structuredencryption.model.AuthenticateSchemaContent nativeValue) {
if (Objects.nonNull(nativeValue.Action())) {
return AuthenticateSchemaContent.create_Action(ToDafny.AuthenticateAction(nativeValue.Action()));
}
if (Objects.nonNull(nativeValue.SchemaMap())) {
return AuthenticateSchemaContent.create_SchemaMap(ToDafny.AuthenticateSchemaMap(nativeValue.SchemaMap()));
}
if (Objects.nonNull(nativeValue.SchemaList())) {
return AuthenticateSchemaContent.create_SchemaList(ToDafny.AuthenticateSchemaList(nativeValue.SchemaList()));
}
throw new IllegalArgumentException("Cannot convert " + nativeValue + " to software.amazon.cryptography.dbencryptionsdk.structuredencryption.internaldafny.types.AuthenticateSchemaContent.");
}
public static CryptoSchemaContent CryptoSchemaContent(
software.amazon.cryptography.dbencryptionsdk.structuredencryption.model.CryptoSchemaContent nativeValue) {
if (Objects.nonNull(nativeValue.Action())) {
return CryptoSchemaContent.create_Action(ToDafny.CryptoAction(nativeValue.Action()));
}
if (Objects.nonNull(nativeValue.SchemaMap())) {
return CryptoSchemaContent.create_SchemaMap(ToDafny.CryptoSchemaMap(nativeValue.SchemaMap()));
}
if (Objects.nonNull(nativeValue.SchemaList())) {
return CryptoSchemaContent.create_SchemaList(ToDafny.CryptoSchemaList(nativeValue.SchemaList()));
}
throw new IllegalArgumentException("Cannot convert " + nativeValue + " to software.amazon.cryptography.dbencryptionsdk.structuredencryption.internaldafny.types.CryptoSchemaContent.");
}
public static StructuredDataContent StructuredDataContent(
software.amazon.cryptography.dbencryptionsdk.structuredencryption.model.StructuredDataContent nativeValue) {
if (Objects.nonNull(nativeValue.Terminal())) {
return StructuredDataContent.create_Terminal(ToDafny.StructuredDataTerminal(nativeValue.Terminal()));
}
if (Objects.nonNull(nativeValue.DataList())) {
return StructuredDataContent.create_DataList(ToDafny.StructuredDataList(nativeValue.DataList()));
}
if (Objects.nonNull(nativeValue.DataMap())) {
return StructuredDataContent.create_DataMap(ToDafny.StructuredDataMap(nativeValue.DataMap()));
}
throw new IllegalArgumentException("Cannot convert " + nativeValue + " to software.amazon.cryptography.dbencryptionsdk.structuredencryption.internaldafny.types.StructuredDataContent.");
}
public static DafnySequence<? extends AuthenticateSchema> AuthenticateSchemaList(
List<software.amazon.cryptography.dbencryptionsdk.structuredencryption.model.AuthenticateSchema> nativeValue) {
return software.amazon.smithy.dafny.conversion.ToDafny.Aggregate.GenericToSequence(
nativeValue,
software.amazon.cryptography.dbencryptionsdk.structuredencryption.ToDafny::AuthenticateSchema,
AuthenticateSchema._typeDescriptor());
}
public static DafnySequence<? extends CryptoSchema> CryptoSchemaList(
List<software.amazon.cryptography.dbencryptionsdk.structuredencryption.model.CryptoSchema> nativeValue) {
return software.amazon.smithy.dafny.conversion.ToDafny.Aggregate.GenericToSequence(
nativeValue,
software.amazon.cryptography.dbencryptionsdk.structuredencryption.ToDafny::CryptoSchema,
CryptoSchema._typeDescriptor());
}
public static DafnySequence<? extends StructuredData> StructuredDataList(
List<software.amazon.cryptography.dbencryptionsdk.structuredencryption.model.StructuredData> nativeValue) {
return software.amazon.smithy.dafny.conversion.ToDafny.Aggregate.GenericToSequence(
nativeValue,
software.amazon.cryptography.dbencryptionsdk.structuredencryption.ToDafny::StructuredData,
StructuredData._typeDescriptor());
}
public static DafnyMap<? extends DafnySequence<? extends Character>, ? extends AuthenticateAction> AuthenticateSchemaAttributes(
Map<String, software.amazon.cryptography.dbencryptionsdk.structuredencryption.model.AuthenticateAction> nativeValue) {
return software.amazon.smithy.dafny.conversion.ToDafny.Aggregate.GenericToMap(
nativeValue,
software.amazon.smithy.dafny.conversion.ToDafny.Simple::CharacterSequence,
software.amazon.cryptography.dbencryptionsdk.structuredencryption.ToDafny::AuthenticateAction);
}
public static DafnyMap<? extends DafnySequence<? extends Character>, ? extends AuthenticateSchema> AuthenticateSchemaMap(
Map<String, software.amazon.cryptography.dbencryptionsdk.structuredencryption.model.AuthenticateSchema> nativeValue) {
return software.amazon.smithy.dafny.conversion.ToDafny.Aggregate.GenericToMap(
nativeValue,
software.amazon.smithy.dafny.conversion.ToDafny.Simple::CharacterSequence,
software.amazon.cryptography.dbencryptionsdk.structuredencryption.ToDafny::AuthenticateSchema);
}
public static DafnyMap<? extends DafnySequence<? extends Character>, ? extends AuthenticateAction> CryptoSchemaAttributes(
Map<String, software.amazon.cryptography.dbencryptionsdk.structuredencryption.model.AuthenticateAction> nativeValue) {
return software.amazon.smithy.dafny.conversion.ToDafny.Aggregate.GenericToMap(
nativeValue,
software.amazon.smithy.dafny.conversion.ToDafny.Simple::CharacterSequence,
software.amazon.cryptography.dbencryptionsdk.structuredencryption.ToDafny::AuthenticateAction);
}
public static DafnyMap<? extends DafnySequence<? extends Character>, ? extends CryptoSchema> CryptoSchemaMap(
Map<String, software.amazon.cryptography.dbencryptionsdk.structuredencryption.model.CryptoSchema> nativeValue) {
return software.amazon.smithy.dafny.conversion.ToDafny.Aggregate.GenericToMap(
nativeValue,
software.amazon.smithy.dafny.conversion.ToDafny.Simple::CharacterSequence,
software.amazon.cryptography.dbencryptionsdk.structuredencryption.ToDafny::CryptoSchema);
}
public static DafnyMap<? extends DafnySequence<? extends Character>, ? extends StructuredDataTerminal> StructuredDataAttributes(
Map<String, software.amazon.cryptography.dbencryptionsdk.structuredencryption.model.StructuredDataTerminal> nativeValue) {
return software.amazon.smithy.dafny.conversion.ToDafny.Aggregate.GenericToMap(
nativeValue,
software.amazon.smithy.dafny.conversion.ToDafny.Simple::CharacterSequence,
software.amazon.cryptography.dbencryptionsdk.structuredencryption.ToDafny::StructuredDataTerminal);
}
public static DafnyMap<? extends DafnySequence<? extends Character>, ? extends StructuredData> StructuredDataMap(
Map<String, software.amazon.cryptography.dbencryptionsdk.structuredencryption.model.StructuredData> nativeValue) {
return software.amazon.smithy.dafny.conversion.ToDafny.Aggregate.GenericToMap(
nativeValue,
software.amazon.smithy.dafny.conversion.ToDafny.Simple::CharacterSequence,
software.amazon.cryptography.dbencryptionsdk.structuredencryption.ToDafny::StructuredData);
}
public static IStructuredEncryptionClient StructuredEncryption(StructuredEncryption nativeValue) {
return nativeValue.impl();
}
}
| 5,082 |
0 | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/dbencryptionsdk/structuredencryption | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/dbencryptionsdk/structuredencryption/model/EncryptStructureInput.java | // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
// Do not modify this file. This file is machine generated, and any changes to it will be overwritten.
package software.amazon.cryptography.dbencryptionsdk.structuredencryption.model;
import java.util.Map;
import java.util.Objects;
import software.amazon.cryptography.materialproviders.CryptographicMaterialsManager;
import software.amazon.cryptography.materialproviders.ICryptographicMaterialsManager;
import software.amazon.cryptography.materialproviders.model.DBEAlgorithmSuiteId;
public class EncryptStructureInput {
private final String tableName;
private final StructuredData plaintextStructure;
private final CryptoSchema cryptoSchema;
private final ICryptographicMaterialsManager cmm;
private final DBEAlgorithmSuiteId algorithmSuiteId;
private final Map<String, String> encryptionContext;
protected EncryptStructureInput(BuilderImpl builder) {
this.tableName = builder.tableName();
this.plaintextStructure = builder.plaintextStructure();
this.cryptoSchema = builder.cryptoSchema();
this.cmm = builder.cmm();
this.algorithmSuiteId = builder.algorithmSuiteId();
this.encryptionContext = builder.encryptionContext();
}
public String tableName() {
return this.tableName;
}
public StructuredData plaintextStructure() {
return this.plaintextStructure;
}
public CryptoSchema cryptoSchema() {
return this.cryptoSchema;
}
public ICryptographicMaterialsManager cmm() {
return this.cmm;
}
public DBEAlgorithmSuiteId algorithmSuiteId() {
return this.algorithmSuiteId;
}
public Map<String, String> encryptionContext() {
return this.encryptionContext;
}
public Builder toBuilder() {
return new BuilderImpl(this);
}
public static Builder builder() {
return new BuilderImpl();
}
public interface Builder {
Builder tableName(String tableName);
String tableName();
Builder plaintextStructure(StructuredData plaintextStructure);
StructuredData plaintextStructure();
Builder cryptoSchema(CryptoSchema cryptoSchema);
CryptoSchema cryptoSchema();
Builder cmm(ICryptographicMaterialsManager cmm);
ICryptographicMaterialsManager cmm();
Builder algorithmSuiteId(DBEAlgorithmSuiteId algorithmSuiteId);
DBEAlgorithmSuiteId algorithmSuiteId();
Builder encryptionContext(Map<String, String> encryptionContext);
Map<String, String> encryptionContext();
EncryptStructureInput build();
}
static class BuilderImpl implements Builder {
protected String tableName;
protected StructuredData plaintextStructure;
protected CryptoSchema cryptoSchema;
protected ICryptographicMaterialsManager cmm;
protected DBEAlgorithmSuiteId algorithmSuiteId;
protected Map<String, String> encryptionContext;
protected BuilderImpl() {
}
protected BuilderImpl(EncryptStructureInput model) {
this.tableName = model.tableName();
this.plaintextStructure = model.plaintextStructure();
this.cryptoSchema = model.cryptoSchema();
this.cmm = model.cmm();
this.algorithmSuiteId = model.algorithmSuiteId();
this.encryptionContext = model.encryptionContext();
}
public Builder tableName(String tableName) {
this.tableName = tableName;
return this;
}
public String tableName() {
return this.tableName;
}
public Builder plaintextStructure(StructuredData plaintextStructure) {
this.plaintextStructure = plaintextStructure;
return this;
}
public StructuredData plaintextStructure() {
return this.plaintextStructure;
}
public Builder cryptoSchema(CryptoSchema cryptoSchema) {
this.cryptoSchema = cryptoSchema;
return this;
}
public CryptoSchema cryptoSchema() {
return this.cryptoSchema;
}
public Builder cmm(ICryptographicMaterialsManager cmm) {
this.cmm = CryptographicMaterialsManager.wrap(cmm);
return this;
}
public ICryptographicMaterialsManager cmm() {
return this.cmm;
}
public Builder algorithmSuiteId(DBEAlgorithmSuiteId algorithmSuiteId) {
this.algorithmSuiteId = algorithmSuiteId;
return this;
}
public DBEAlgorithmSuiteId algorithmSuiteId() {
return this.algorithmSuiteId;
}
public Builder encryptionContext(Map<String, String> encryptionContext) {
this.encryptionContext = encryptionContext;
return this;
}
public Map<String, String> encryptionContext() {
return this.encryptionContext;
}
public EncryptStructureInput build() {
if (Objects.isNull(this.tableName())) {
throw new IllegalArgumentException("Missing value for required field `tableName`");
}
if (Objects.isNull(this.plaintextStructure())) {
throw new IllegalArgumentException("Missing value for required field `plaintextStructure`");
}
if (Objects.isNull(this.cryptoSchema())) {
throw new IllegalArgumentException("Missing value for required field `cryptoSchema`");
}
if (Objects.isNull(this.cmm())) {
throw new IllegalArgumentException("Missing value for required field `cmm`");
}
return new EncryptStructureInput(this);
}
}
}
| 5,083 |
0 | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/dbencryptionsdk/structuredencryption | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/dbencryptionsdk/structuredencryption/model/DecryptStructureOutput.java | // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
// Do not modify this file. This file is machine generated, and any changes to it will be overwritten.
package software.amazon.cryptography.dbencryptionsdk.structuredencryption.model;
import java.util.Objects;
public class DecryptStructureOutput {
private final StructuredData plaintextStructure;
private final ParsedHeader parsedHeader;
protected DecryptStructureOutput(BuilderImpl builder) {
this.plaintextStructure = builder.plaintextStructure();
this.parsedHeader = builder.parsedHeader();
}
public StructuredData plaintextStructure() {
return this.plaintextStructure;
}
public ParsedHeader parsedHeader() {
return this.parsedHeader;
}
public Builder toBuilder() {
return new BuilderImpl(this);
}
public static Builder builder() {
return new BuilderImpl();
}
public interface Builder {
Builder plaintextStructure(StructuredData plaintextStructure);
StructuredData plaintextStructure();
Builder parsedHeader(ParsedHeader parsedHeader);
ParsedHeader parsedHeader();
DecryptStructureOutput build();
}
static class BuilderImpl implements Builder {
protected StructuredData plaintextStructure;
protected ParsedHeader parsedHeader;
protected BuilderImpl() {
}
protected BuilderImpl(DecryptStructureOutput model) {
this.plaintextStructure = model.plaintextStructure();
this.parsedHeader = model.parsedHeader();
}
public Builder plaintextStructure(StructuredData plaintextStructure) {
this.plaintextStructure = plaintextStructure;
return this;
}
public StructuredData plaintextStructure() {
return this.plaintextStructure;
}
public Builder parsedHeader(ParsedHeader parsedHeader) {
this.parsedHeader = parsedHeader;
return this;
}
public ParsedHeader parsedHeader() {
return this.parsedHeader;
}
public DecryptStructureOutput build() {
if (Objects.isNull(this.plaintextStructure())) {
throw new IllegalArgumentException("Missing value for required field `plaintextStructure`");
}
if (Objects.isNull(this.parsedHeader())) {
throw new IllegalArgumentException("Missing value for required field `parsedHeader`");
}
return new DecryptStructureOutput(this);
}
}
}
| 5,084 |
0 | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/dbencryptionsdk/structuredencryption | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/dbencryptionsdk/structuredencryption/model/AuthenticateSchema.java | // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
// Do not modify this file. This file is machine generated, and any changes to it will be overwritten.
package software.amazon.cryptography.dbencryptionsdk.structuredencryption.model;
import java.util.Map;
import java.util.Objects;
public class AuthenticateSchema {
private final AuthenticateSchemaContent content;
private final Map<String, AuthenticateAction> attributes;
protected AuthenticateSchema(BuilderImpl builder) {
this.content = builder.content();
this.attributes = builder.attributes();
}
public AuthenticateSchemaContent content() {
return this.content;
}
public Map<String, AuthenticateAction> attributes() {
return this.attributes;
}
public Builder toBuilder() {
return new BuilderImpl(this);
}
public static Builder builder() {
return new BuilderImpl();
}
public interface Builder {
Builder content(AuthenticateSchemaContent content);
AuthenticateSchemaContent content();
Builder attributes(Map<String, AuthenticateAction> attributes);
Map<String, AuthenticateAction> attributes();
AuthenticateSchema build();
}
static class BuilderImpl implements Builder {
protected AuthenticateSchemaContent content;
protected Map<String, AuthenticateAction> attributes;
protected BuilderImpl() {
}
protected BuilderImpl(AuthenticateSchema model) {
this.content = model.content();
this.attributes = model.attributes();
}
public Builder content(AuthenticateSchemaContent content) {
this.content = content;
return this;
}
public AuthenticateSchemaContent content() {
return this.content;
}
public Builder attributes(Map<String, AuthenticateAction> attributes) {
this.attributes = attributes;
return this;
}
public Map<String, AuthenticateAction> attributes() {
return this.attributes;
}
public AuthenticateSchema build() {
if (Objects.isNull(this.content())) {
throw new IllegalArgumentException("Missing value for required field `content`");
}
return new AuthenticateSchema(this);
}
}
}
| 5,085 |
0 | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/dbencryptionsdk/structuredencryption | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/dbencryptionsdk/structuredencryption/model/StructuredEncryptionException.java | // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
// Do not modify this file. This file is machine generated, and any changes to it will be overwritten.
package software.amazon.cryptography.dbencryptionsdk.structuredencryption.model;
import java.util.Objects;
public class StructuredEncryptionException extends RuntimeException {
protected StructuredEncryptionException(BuilderImpl builder) {
super(messageFromBuilder(builder), builder.cause());
}
private static String messageFromBuilder(Builder builder) {
if (builder.message() != null) {
return builder.message();
}
if (builder.cause() != null) {
return builder.cause().getMessage();
}
return null;
}
/**
* See {@link Throwable#getMessage()}.
*/
public String message() {
return this.getMessage();
}
/**
* See {@link Throwable#getCause()}.
*/
public Throwable cause() {
return this.getCause();
}
public Builder toBuilder() {
return new BuilderImpl(this);
}
public static Builder builder() {
return new BuilderImpl();
}
public interface Builder {
/**
* @param message The detailed message. The detail message is saved for later retrieval by the {@link #getMessage()} method.
*/
Builder message(String message);
/**
* @return The detailed message. The detail message is saved for later retrieval by the {@link #getMessage()} method.
*/
String message();
/**
* @param cause The cause (which is saved for later retrieval by the {@link #getCause()} method). (A {@code null} value is permitted, and indicates that the cause is nonexistent or unknown.)
*/
Builder cause(Throwable cause);
/**
* @return The cause (which is saved for later retrieval by the {@link #getCause()} method). (A {@code null} value is permitted, and indicates that the cause is nonexistent or unknown.)
*/
Throwable cause();
StructuredEncryptionException build();
}
static class BuilderImpl implements Builder {
protected String message;
protected Throwable cause;
protected BuilderImpl() {
}
protected BuilderImpl(StructuredEncryptionException model) {
this.message = model.message();
this.cause = model.cause();
}
public Builder message(String message) {
this.message = message;
return this;
}
public String message() {
return this.message;
}
public Builder cause(Throwable cause) {
this.cause = cause;
return this;
}
public Throwable cause() {
return this.cause;
}
public StructuredEncryptionException build() {
if (Objects.isNull(this.message())) {
throw new IllegalArgumentException("Missing value for required field `message`");
}
return new StructuredEncryptionException(this);
}
}
}
| 5,086 |
0 | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/dbencryptionsdk/structuredencryption | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/dbencryptionsdk/structuredencryption/model/DecryptStructureInput.java | // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
// Do not modify this file. This file is machine generated, and any changes to it will be overwritten.
package software.amazon.cryptography.dbencryptionsdk.structuredencryption.model;
import java.util.Map;
import java.util.Objects;
import software.amazon.cryptography.materialproviders.CryptographicMaterialsManager;
import software.amazon.cryptography.materialproviders.ICryptographicMaterialsManager;
public class DecryptStructureInput {
private final String tableName;
private final StructuredData encryptedStructure;
private final AuthenticateSchema authenticateSchema;
private final ICryptographicMaterialsManager cmm;
private final Map<String, String> encryptionContext;
protected DecryptStructureInput(BuilderImpl builder) {
this.tableName = builder.tableName();
this.encryptedStructure = builder.encryptedStructure();
this.authenticateSchema = builder.authenticateSchema();
this.cmm = builder.cmm();
this.encryptionContext = builder.encryptionContext();
}
public String tableName() {
return this.tableName;
}
public StructuredData encryptedStructure() {
return this.encryptedStructure;
}
public AuthenticateSchema authenticateSchema() {
return this.authenticateSchema;
}
public ICryptographicMaterialsManager cmm() {
return this.cmm;
}
public Map<String, String> encryptionContext() {
return this.encryptionContext;
}
public Builder toBuilder() {
return new BuilderImpl(this);
}
public static Builder builder() {
return new BuilderImpl();
}
public interface Builder {
Builder tableName(String tableName);
String tableName();
Builder encryptedStructure(StructuredData encryptedStructure);
StructuredData encryptedStructure();
Builder authenticateSchema(AuthenticateSchema authenticateSchema);
AuthenticateSchema authenticateSchema();
Builder cmm(ICryptographicMaterialsManager cmm);
ICryptographicMaterialsManager cmm();
Builder encryptionContext(Map<String, String> encryptionContext);
Map<String, String> encryptionContext();
DecryptStructureInput build();
}
static class BuilderImpl implements Builder {
protected String tableName;
protected StructuredData encryptedStructure;
protected AuthenticateSchema authenticateSchema;
protected ICryptographicMaterialsManager cmm;
protected Map<String, String> encryptionContext;
protected BuilderImpl() {
}
protected BuilderImpl(DecryptStructureInput model) {
this.tableName = model.tableName();
this.encryptedStructure = model.encryptedStructure();
this.authenticateSchema = model.authenticateSchema();
this.cmm = model.cmm();
this.encryptionContext = model.encryptionContext();
}
public Builder tableName(String tableName) {
this.tableName = tableName;
return this;
}
public String tableName() {
return this.tableName;
}
public Builder encryptedStructure(StructuredData encryptedStructure) {
this.encryptedStructure = encryptedStructure;
return this;
}
public StructuredData encryptedStructure() {
return this.encryptedStructure;
}
public Builder authenticateSchema(AuthenticateSchema authenticateSchema) {
this.authenticateSchema = authenticateSchema;
return this;
}
public AuthenticateSchema authenticateSchema() {
return this.authenticateSchema;
}
public Builder cmm(ICryptographicMaterialsManager cmm) {
this.cmm = CryptographicMaterialsManager.wrap(cmm);
return this;
}
public ICryptographicMaterialsManager cmm() {
return this.cmm;
}
public Builder encryptionContext(Map<String, String> encryptionContext) {
this.encryptionContext = encryptionContext;
return this;
}
public Map<String, String> encryptionContext() {
return this.encryptionContext;
}
public DecryptStructureInput build() {
if (Objects.isNull(this.tableName())) {
throw new IllegalArgumentException("Missing value for required field `tableName`");
}
if (Objects.isNull(this.encryptedStructure())) {
throw new IllegalArgumentException("Missing value for required field `encryptedStructure`");
}
if (Objects.isNull(this.authenticateSchema())) {
throw new IllegalArgumentException("Missing value for required field `authenticateSchema`");
}
if (Objects.isNull(this.cmm())) {
throw new IllegalArgumentException("Missing value for required field `cmm`");
}
return new DecryptStructureInput(this);
}
}
}
| 5,087 |
0 | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/dbencryptionsdk/structuredencryption | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/dbencryptionsdk/structuredencryption/model/EncryptStructureOutput.java | // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
// Do not modify this file. This file is machine generated, and any changes to it will be overwritten.
package software.amazon.cryptography.dbencryptionsdk.structuredencryption.model;
import java.util.Objects;
public class EncryptStructureOutput {
private final StructuredData encryptedStructure;
private final ParsedHeader parsedHeader;
protected EncryptStructureOutput(BuilderImpl builder) {
this.encryptedStructure = builder.encryptedStructure();
this.parsedHeader = builder.parsedHeader();
}
public StructuredData encryptedStructure() {
return this.encryptedStructure;
}
public ParsedHeader parsedHeader() {
return this.parsedHeader;
}
public Builder toBuilder() {
return new BuilderImpl(this);
}
public static Builder builder() {
return new BuilderImpl();
}
public interface Builder {
Builder encryptedStructure(StructuredData encryptedStructure);
StructuredData encryptedStructure();
Builder parsedHeader(ParsedHeader parsedHeader);
ParsedHeader parsedHeader();
EncryptStructureOutput build();
}
static class BuilderImpl implements Builder {
protected StructuredData encryptedStructure;
protected ParsedHeader parsedHeader;
protected BuilderImpl() {
}
protected BuilderImpl(EncryptStructureOutput model) {
this.encryptedStructure = model.encryptedStructure();
this.parsedHeader = model.parsedHeader();
}
public Builder encryptedStructure(StructuredData encryptedStructure) {
this.encryptedStructure = encryptedStructure;
return this;
}
public StructuredData encryptedStructure() {
return this.encryptedStructure;
}
public Builder parsedHeader(ParsedHeader parsedHeader) {
this.parsedHeader = parsedHeader;
return this;
}
public ParsedHeader parsedHeader() {
return this.parsedHeader;
}
public EncryptStructureOutput build() {
if (Objects.isNull(this.encryptedStructure())) {
throw new IllegalArgumentException("Missing value for required field `encryptedStructure`");
}
if (Objects.isNull(this.parsedHeader())) {
throw new IllegalArgumentException("Missing value for required field `parsedHeader`");
}
return new EncryptStructureOutput(this);
}
}
}
| 5,088 |
0 | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/dbencryptionsdk/structuredencryption | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/dbencryptionsdk/structuredencryption/model/CryptoAction.java | // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
// Do not modify this file. This file is machine generated, and any changes to it will be overwritten.
package software.amazon.cryptography.dbencryptionsdk.structuredencryption.model;
public enum CryptoAction {
ENCRYPT_AND_SIGN("ENCRYPT_AND_SIGN"),
SIGN_ONLY("SIGN_ONLY"),
DO_NOTHING("DO_NOTHING");
private final String value;
private CryptoAction(String value) {
this.value = value;
}
public String toString() {
return String.valueOf(value);
}
}
| 5,089 |
0 | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/dbencryptionsdk/structuredencryption | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/dbencryptionsdk/structuredencryption/model/CryptoSchemaContent.java | // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
// Do not modify this file. This file is machine generated, and any changes to it will be overwritten.
package software.amazon.cryptography.dbencryptionsdk.structuredencryption.model;
import java.util.List;
import java.util.Map;
import java.util.Objects;
public class CryptoSchemaContent {
private final CryptoAction Action;
private final Map<String, CryptoSchema> SchemaMap;
private final List<CryptoSchema> SchemaList;
protected CryptoSchemaContent(BuilderImpl builder) {
this.Action = builder.Action();
this.SchemaMap = builder.SchemaMap();
this.SchemaList = builder.SchemaList();
}
public CryptoAction Action() {
return this.Action;
}
public Map<String, CryptoSchema> SchemaMap() {
return this.SchemaMap;
}
public List<CryptoSchema> SchemaList() {
return this.SchemaList;
}
public Builder toBuilder() {
return new BuilderImpl(this);
}
public static Builder builder() {
return new BuilderImpl();
}
public interface Builder {
Builder Action(CryptoAction Action);
CryptoAction Action();
Builder SchemaMap(Map<String, CryptoSchema> SchemaMap);
Map<String, CryptoSchema> SchemaMap();
Builder SchemaList(List<CryptoSchema> SchemaList);
List<CryptoSchema> SchemaList();
CryptoSchemaContent build();
}
static class BuilderImpl implements Builder {
protected CryptoAction Action;
protected Map<String, CryptoSchema> SchemaMap;
protected List<CryptoSchema> SchemaList;
protected BuilderImpl() {
}
protected BuilderImpl(CryptoSchemaContent model) {
this.Action = model.Action();
this.SchemaMap = model.SchemaMap();
this.SchemaList = model.SchemaList();
}
public Builder Action(CryptoAction Action) {
this.Action = Action;
return this;
}
public CryptoAction Action() {
return this.Action;
}
public Builder SchemaMap(Map<String, CryptoSchema> SchemaMap) {
this.SchemaMap = SchemaMap;
return this;
}
public Map<String, CryptoSchema> SchemaMap() {
return this.SchemaMap;
}
public Builder SchemaList(List<CryptoSchema> SchemaList) {
this.SchemaList = SchemaList;
return this;
}
public List<CryptoSchema> SchemaList() {
return this.SchemaList;
}
public CryptoSchemaContent build() {
if (!onlyOneNonNull()) {
throw new IllegalArgumentException("`CryptoSchemaContent` is a Union. A Union MUST have one and only one value set.");
}
return new CryptoSchemaContent(this);
}
private boolean onlyOneNonNull() {
Object[] allValues = {this.Action, this.SchemaMap, this.SchemaList};
boolean haveOneNonNull = false;
for (Object o : allValues) {
if (Objects.nonNull(o)) {
if (haveOneNonNull) {
return false;
}
haveOneNonNull = true;
}
}
return haveOneNonNull;
}
}
}
| 5,090 |
0 | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/dbencryptionsdk/structuredencryption | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/dbencryptionsdk/structuredencryption/model/AuthenticateSchemaContent.java | // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
// Do not modify this file. This file is machine generated, and any changes to it will be overwritten.
package software.amazon.cryptography.dbencryptionsdk.structuredencryption.model;
import java.util.List;
import java.util.Map;
import java.util.Objects;
public class AuthenticateSchemaContent {
private final AuthenticateAction Action;
private final Map<String, AuthenticateSchema> SchemaMap;
private final List<AuthenticateSchema> SchemaList;
protected AuthenticateSchemaContent(BuilderImpl builder) {
this.Action = builder.Action();
this.SchemaMap = builder.SchemaMap();
this.SchemaList = builder.SchemaList();
}
public AuthenticateAction Action() {
return this.Action;
}
public Map<String, AuthenticateSchema> SchemaMap() {
return this.SchemaMap;
}
public List<AuthenticateSchema> SchemaList() {
return this.SchemaList;
}
public Builder toBuilder() {
return new BuilderImpl(this);
}
public static Builder builder() {
return new BuilderImpl();
}
public interface Builder {
Builder Action(AuthenticateAction Action);
AuthenticateAction Action();
Builder SchemaMap(Map<String, AuthenticateSchema> SchemaMap);
Map<String, AuthenticateSchema> SchemaMap();
Builder SchemaList(List<AuthenticateSchema> SchemaList);
List<AuthenticateSchema> SchemaList();
AuthenticateSchemaContent build();
}
static class BuilderImpl implements Builder {
protected AuthenticateAction Action;
protected Map<String, AuthenticateSchema> SchemaMap;
protected List<AuthenticateSchema> SchemaList;
protected BuilderImpl() {
}
protected BuilderImpl(AuthenticateSchemaContent model) {
this.Action = model.Action();
this.SchemaMap = model.SchemaMap();
this.SchemaList = model.SchemaList();
}
public Builder Action(AuthenticateAction Action) {
this.Action = Action;
return this;
}
public AuthenticateAction Action() {
return this.Action;
}
public Builder SchemaMap(Map<String, AuthenticateSchema> SchemaMap) {
this.SchemaMap = SchemaMap;
return this;
}
public Map<String, AuthenticateSchema> SchemaMap() {
return this.SchemaMap;
}
public Builder SchemaList(List<AuthenticateSchema> SchemaList) {
this.SchemaList = SchemaList;
return this;
}
public List<AuthenticateSchema> SchemaList() {
return this.SchemaList;
}
public AuthenticateSchemaContent build() {
if (!onlyOneNonNull()) {
throw new IllegalArgumentException("`AuthenticateSchemaContent` is a Union. A Union MUST have one and only one value set.");
}
return new AuthenticateSchemaContent(this);
}
private boolean onlyOneNonNull() {
Object[] allValues = {this.Action, this.SchemaMap, this.SchemaList};
boolean haveOneNonNull = false;
for (Object o : allValues) {
if (Objects.nonNull(o)) {
if (haveOneNonNull) {
return false;
}
haveOneNonNull = true;
}
}
return haveOneNonNull;
}
}
}
| 5,091 |
0 | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/dbencryptionsdk/structuredencryption | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/dbencryptionsdk/structuredencryption/model/StructuredDataContent.java | // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
// Do not modify this file. This file is machine generated, and any changes to it will be overwritten.
package software.amazon.cryptography.dbencryptionsdk.structuredencryption.model;
import java.util.List;
import java.util.Map;
import java.util.Objects;
public class StructuredDataContent {
private final StructuredDataTerminal Terminal;
private final List<StructuredData> DataList;
private final Map<String, StructuredData> DataMap;
protected StructuredDataContent(BuilderImpl builder) {
this.Terminal = builder.Terminal();
this.DataList = builder.DataList();
this.DataMap = builder.DataMap();
}
public StructuredDataTerminal Terminal() {
return this.Terminal;
}
public List<StructuredData> DataList() {
return this.DataList;
}
public Map<String, StructuredData> DataMap() {
return this.DataMap;
}
public Builder toBuilder() {
return new BuilderImpl(this);
}
public static Builder builder() {
return new BuilderImpl();
}
public interface Builder {
Builder Terminal(StructuredDataTerminal Terminal);
StructuredDataTerminal Terminal();
Builder DataList(List<StructuredData> DataList);
List<StructuredData> DataList();
Builder DataMap(Map<String, StructuredData> DataMap);
Map<String, StructuredData> DataMap();
StructuredDataContent build();
}
static class BuilderImpl implements Builder {
protected StructuredDataTerminal Terminal;
protected List<StructuredData> DataList;
protected Map<String, StructuredData> DataMap;
protected BuilderImpl() {
}
protected BuilderImpl(StructuredDataContent model) {
this.Terminal = model.Terminal();
this.DataList = model.DataList();
this.DataMap = model.DataMap();
}
public Builder Terminal(StructuredDataTerminal Terminal) {
this.Terminal = Terminal;
return this;
}
public StructuredDataTerminal Terminal() {
return this.Terminal;
}
public Builder DataList(List<StructuredData> DataList) {
this.DataList = DataList;
return this;
}
public List<StructuredData> DataList() {
return this.DataList;
}
public Builder DataMap(Map<String, StructuredData> DataMap) {
this.DataMap = DataMap;
return this;
}
public Map<String, StructuredData> DataMap() {
return this.DataMap;
}
public StructuredDataContent build() {
if (!onlyOneNonNull()) {
throw new IllegalArgumentException("`StructuredDataContent` is a Union. A Union MUST have one and only one value set.");
}
return new StructuredDataContent(this);
}
private boolean onlyOneNonNull() {
Object[] allValues = {this.Terminal, this.DataList, this.DataMap};
boolean haveOneNonNull = false;
for (Object o : allValues) {
if (Objects.nonNull(o)) {
if (haveOneNonNull) {
return false;
}
haveOneNonNull = true;
}
}
return haveOneNonNull;
}
}
}
| 5,092 |
0 | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/dbencryptionsdk/structuredencryption | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/dbencryptionsdk/structuredencryption/model/OpaqueError.java | // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
// Do not modify this file. This file is machine generated, and any changes to it will be overwritten.
package software.amazon.cryptography.dbencryptionsdk.structuredencryption.model;
public class OpaqueError extends RuntimeException {
/**
* The unexpected object encountered. It MIGHT BE an Exception, but that is not guaranteed.
*/
private final Object obj;
protected OpaqueError(BuilderImpl builder) {
super(messageFromBuilder(builder), builder.cause());
this.obj = builder.obj();
}
private static String messageFromBuilder(Builder builder) {
if (builder.message() != null) {
return builder.message();
}
if (builder.cause() != null) {
return builder.cause().getMessage();
}
return null;
}
/**
* See {@link Throwable#getMessage()}.
*/
public String message() {
return this.getMessage();
}
/**
* See {@link Throwable#getCause()}.
*/
public Throwable cause() {
return this.getCause();
}
/**
* @return The unexpected object encountered. It MIGHT BE an Exception, but that is not guaranteed.
*/
public Object obj() {
return this.obj;
}
public Builder toBuilder() {
return new BuilderImpl(this);
}
public static Builder builder() {
return new BuilderImpl();
}
public interface Builder {
/**
* @param message The detailed message. The detail message is saved for later retrieval by the {@link #getMessage()} method.
*/
Builder message(String message);
/**
* @return The detailed message. The detail message is saved for later retrieval by the {@link #getMessage()} method.
*/
String message();
/**
* @param cause The cause (which is saved for later retrieval by the {@link #getCause()} method). (A {@code null} value is permitted, and indicates that the cause is nonexistent or unknown.)
*/
Builder cause(Throwable cause);
/**
* @return The cause (which is saved for later retrieval by the {@link #getCause()} method). (A {@code null} value is permitted, and indicates that the cause is nonexistent or unknown.)
*/
Throwable cause();
/**
* @param obj The unexpected object encountered. It MIGHT BE an Exception, but that is not guaranteed.
*/
Builder obj(Object obj);
/**
* @return The unexpected object encountered. It MIGHT BE an Exception, but that is not guaranteed.
*/
Object obj();
OpaqueError build();
}
static class BuilderImpl implements Builder {
protected String message;
protected Throwable cause;
protected Object obj;
protected BuilderImpl() {
}
protected BuilderImpl(OpaqueError model) {
this.cause = model.getCause();
this.message = model.getMessage();
this.obj = model.obj();
}
public Builder message(String message) {
this.message = message;
return this;
}
public String message() {
return this.message;
}
public Builder cause(Throwable cause) {
this.cause = cause;
return this;
}
public Throwable cause() {
return this.cause;
}
public Builder obj(Object obj) {
this.obj = obj;
return this;
}
public Object obj() {
return this.obj;
}
public OpaqueError build() {
if (this.obj != null && this.cause == null && this.obj instanceof Throwable) {
this.cause = (Throwable) this.obj;
} else if (this.obj == null && this.cause != null) {
this.obj = this.cause;
}
return new OpaqueError(this);
}
}
}
| 5,093 |
0 | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/dbencryptionsdk/structuredencryption | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/dbencryptionsdk/structuredencryption/model/StructuredEncryptionConfig.java | // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
// Do not modify this file. This file is machine generated, and any changes to it will be overwritten.
package software.amazon.cryptography.dbencryptionsdk.structuredencryption.model;
public class StructuredEncryptionConfig {
protected StructuredEncryptionConfig(BuilderImpl builder) {
}
public Builder toBuilder() {
return new BuilderImpl(this);
}
public static Builder builder() {
return new BuilderImpl();
}
public interface Builder {
StructuredEncryptionConfig build();
}
static class BuilderImpl implements Builder {
protected BuilderImpl() {
}
protected BuilderImpl(StructuredEncryptionConfig model) {
}
public StructuredEncryptionConfig build() {
return new StructuredEncryptionConfig(this);
}
}
}
| 5,094 |
0 | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/dbencryptionsdk/structuredencryption | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/dbencryptionsdk/structuredencryption/model/StructuredDataTerminal.java | // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
// Do not modify this file. This file is machine generated, and any changes to it will be overwritten.
package software.amazon.cryptography.dbencryptionsdk.structuredencryption.model;
import java.nio.ByteBuffer;
import java.util.Objects;
public class StructuredDataTerminal {
private final ByteBuffer value;
private final ByteBuffer typeId;
protected StructuredDataTerminal(BuilderImpl builder) {
this.value = builder.value();
this.typeId = builder.typeId();
}
public ByteBuffer value() {
return this.value;
}
public ByteBuffer typeId() {
return this.typeId;
}
public Builder toBuilder() {
return new BuilderImpl(this);
}
public static Builder builder() {
return new BuilderImpl();
}
public interface Builder {
Builder value(ByteBuffer value);
ByteBuffer value();
Builder typeId(ByteBuffer typeId);
ByteBuffer typeId();
StructuredDataTerminal build();
}
static class BuilderImpl implements Builder {
protected ByteBuffer value;
protected ByteBuffer typeId;
protected BuilderImpl() {
}
protected BuilderImpl(StructuredDataTerminal model) {
this.value = model.value();
this.typeId = model.typeId();
}
public Builder value(ByteBuffer value) {
this.value = value;
return this;
}
public ByteBuffer value() {
return this.value;
}
public Builder typeId(ByteBuffer typeId) {
this.typeId = typeId;
return this;
}
public ByteBuffer typeId() {
return this.typeId;
}
public StructuredDataTerminal build() {
if (Objects.isNull(this.value())) {
throw new IllegalArgumentException("Missing value for required field `value`");
}
if (Objects.isNull(this.typeId())) {
throw new IllegalArgumentException("Missing value for required field `typeId`");
}
if (Objects.nonNull(this.typeId()) && this.typeId().remaining() < 2) {
throw new IllegalArgumentException("The size of `typeId` must be greater than or equal to 2");
}
if (Objects.nonNull(this.typeId()) && this.typeId().remaining() > 2) {
throw new IllegalArgumentException("The size of `typeId` must be less than or equal to 2");
}
return new StructuredDataTerminal(this);
}
}
}
| 5,095 |
0 | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/dbencryptionsdk/structuredencryption | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/dbencryptionsdk/structuredencryption/model/StructuredData.java | // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
// Do not modify this file. This file is machine generated, and any changes to it will be overwritten.
package software.amazon.cryptography.dbencryptionsdk.structuredencryption.model;
import java.util.Map;
import java.util.Objects;
public class StructuredData {
private final StructuredDataContent content;
private final Map<String, StructuredDataTerminal> attributes;
protected StructuredData(BuilderImpl builder) {
this.content = builder.content();
this.attributes = builder.attributes();
}
public StructuredDataContent content() {
return this.content;
}
public Map<String, StructuredDataTerminal> attributes() {
return this.attributes;
}
public Builder toBuilder() {
return new BuilderImpl(this);
}
public static Builder builder() {
return new BuilderImpl();
}
public interface Builder {
Builder content(StructuredDataContent content);
StructuredDataContent content();
Builder attributes(Map<String, StructuredDataTerminal> attributes);
Map<String, StructuredDataTerminal> attributes();
StructuredData build();
}
static class BuilderImpl implements Builder {
protected StructuredDataContent content;
protected Map<String, StructuredDataTerminal> attributes;
protected BuilderImpl() {
}
protected BuilderImpl(StructuredData model) {
this.content = model.content();
this.attributes = model.attributes();
}
public Builder content(StructuredDataContent content) {
this.content = content;
return this;
}
public StructuredDataContent content() {
return this.content;
}
public Builder attributes(Map<String, StructuredDataTerminal> attributes) {
this.attributes = attributes;
return this;
}
public Map<String, StructuredDataTerminal> attributes() {
return this.attributes;
}
public StructuredData build() {
if (Objects.isNull(this.content())) {
throw new IllegalArgumentException("Missing value for required field `content`");
}
return new StructuredData(this);
}
}
}
| 5,096 |
0 | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/dbencryptionsdk/structuredencryption | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/dbencryptionsdk/structuredencryption/model/AuthenticateAction.java | // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
// Do not modify this file. This file is machine generated, and any changes to it will be overwritten.
package software.amazon.cryptography.dbencryptionsdk.structuredencryption.model;
public enum AuthenticateAction {
SIGN("SIGN"),
DO_NOT_SIGN("DO_NOT_SIGN");
private final String value;
private AuthenticateAction(String value) {
this.value = value;
}
public String toString() {
return String.valueOf(value);
}
}
| 5,097 |
0 | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/dbencryptionsdk/structuredencryption | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/dbencryptionsdk/structuredencryption/model/ParsedHeader.java | // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
// Do not modify this file. This file is machine generated, and any changes to it will be overwritten.
package software.amazon.cryptography.dbencryptionsdk.structuredencryption.model;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import software.amazon.cryptography.materialproviders.model.DBEAlgorithmSuiteId;
import software.amazon.cryptography.materialproviders.model.EncryptedDataKey;
public class ParsedHeader {
private final CryptoSchema cryptoSchema;
private final DBEAlgorithmSuiteId algorithmSuiteId;
private final List<EncryptedDataKey> encryptedDataKeys;
private final Map<String, String> storedEncryptionContext;
protected ParsedHeader(BuilderImpl builder) {
this.cryptoSchema = builder.cryptoSchema();
this.algorithmSuiteId = builder.algorithmSuiteId();
this.encryptedDataKeys = builder.encryptedDataKeys();
this.storedEncryptionContext = builder.storedEncryptionContext();
}
public CryptoSchema cryptoSchema() {
return this.cryptoSchema;
}
public DBEAlgorithmSuiteId algorithmSuiteId() {
return this.algorithmSuiteId;
}
public List<EncryptedDataKey> encryptedDataKeys() {
return this.encryptedDataKeys;
}
public Map<String, String> storedEncryptionContext() {
return this.storedEncryptionContext;
}
public Builder toBuilder() {
return new BuilderImpl(this);
}
public static Builder builder() {
return new BuilderImpl();
}
public interface Builder {
Builder cryptoSchema(CryptoSchema cryptoSchema);
CryptoSchema cryptoSchema();
Builder algorithmSuiteId(DBEAlgorithmSuiteId algorithmSuiteId);
DBEAlgorithmSuiteId algorithmSuiteId();
Builder encryptedDataKeys(List<EncryptedDataKey> encryptedDataKeys);
List<EncryptedDataKey> encryptedDataKeys();
Builder storedEncryptionContext(Map<String, String> storedEncryptionContext);
Map<String, String> storedEncryptionContext();
ParsedHeader build();
}
static class BuilderImpl implements Builder {
protected CryptoSchema cryptoSchema;
protected DBEAlgorithmSuiteId algorithmSuiteId;
protected List<EncryptedDataKey> encryptedDataKeys;
protected Map<String, String> storedEncryptionContext;
protected BuilderImpl() {
}
protected BuilderImpl(ParsedHeader model) {
this.cryptoSchema = model.cryptoSchema();
this.algorithmSuiteId = model.algorithmSuiteId();
this.encryptedDataKeys = model.encryptedDataKeys();
this.storedEncryptionContext = model.storedEncryptionContext();
}
public Builder cryptoSchema(CryptoSchema cryptoSchema) {
this.cryptoSchema = cryptoSchema;
return this;
}
public CryptoSchema cryptoSchema() {
return this.cryptoSchema;
}
public Builder algorithmSuiteId(DBEAlgorithmSuiteId algorithmSuiteId) {
this.algorithmSuiteId = algorithmSuiteId;
return this;
}
public DBEAlgorithmSuiteId algorithmSuiteId() {
return this.algorithmSuiteId;
}
public Builder encryptedDataKeys(List<EncryptedDataKey> encryptedDataKeys) {
this.encryptedDataKeys = encryptedDataKeys;
return this;
}
public List<EncryptedDataKey> encryptedDataKeys() {
return this.encryptedDataKeys;
}
public Builder storedEncryptionContext(Map<String, String> storedEncryptionContext) {
this.storedEncryptionContext = storedEncryptionContext;
return this;
}
public Map<String, String> storedEncryptionContext() {
return this.storedEncryptionContext;
}
public ParsedHeader build() {
if (Objects.isNull(this.cryptoSchema())) {
throw new IllegalArgumentException("Missing value for required field `cryptoSchema`");
}
if (Objects.isNull(this.algorithmSuiteId())) {
throw new IllegalArgumentException("Missing value for required field `algorithmSuiteId`");
}
if (Objects.isNull(this.encryptedDataKeys())) {
throw new IllegalArgumentException("Missing value for required field `encryptedDataKeys`");
}
if (Objects.isNull(this.storedEncryptionContext())) {
throw new IllegalArgumentException("Missing value for required field `storedEncryptionContext`");
}
return new ParsedHeader(this);
}
}
}
| 5,098 |
0 | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/dbencryptionsdk/structuredencryption | Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/dbencryptionsdk/structuredencryption/model/CryptoSchema.java | // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
// Do not modify this file. This file is machine generated, and any changes to it will be overwritten.
package software.amazon.cryptography.dbencryptionsdk.structuredencryption.model;
import java.util.Map;
import java.util.Objects;
public class CryptoSchema {
private final CryptoSchemaContent content;
private final Map<String, AuthenticateAction> attributes;
protected CryptoSchema(BuilderImpl builder) {
this.content = builder.content();
this.attributes = builder.attributes();
}
public CryptoSchemaContent content() {
return this.content;
}
public Map<String, AuthenticateAction> attributes() {
return this.attributes;
}
public Builder toBuilder() {
return new BuilderImpl(this);
}
public static Builder builder() {
return new BuilderImpl();
}
public interface Builder {
Builder content(CryptoSchemaContent content);
CryptoSchemaContent content();
Builder attributes(Map<String, AuthenticateAction> attributes);
Map<String, AuthenticateAction> attributes();
CryptoSchema build();
}
static class BuilderImpl implements Builder {
protected CryptoSchemaContent content;
protected Map<String, AuthenticateAction> attributes;
protected BuilderImpl() {
}
protected BuilderImpl(CryptoSchema model) {
this.content = model.content();
this.attributes = model.attributes();
}
public Builder content(CryptoSchemaContent content) {
this.content = content;
return this;
}
public CryptoSchemaContent content() {
return this.content;
}
public Builder attributes(Map<String, AuthenticateAction> attributes) {
this.attributes = attributes;
return this;
}
public Map<String, AuthenticateAction> attributes() {
return this.attributes;
}
public CryptoSchema build() {
if (Objects.isNull(this.content())) {
throw new IllegalArgumentException("Missing value for required field `content`");
}
return new CryptoSchema(this);
}
}
}
| 5,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.