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/main/smithy-generated/software/amazon/cryptography/dbencryptionsdk/dynamodb
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/dbencryptionsdk/dynamodb/model/SingleKeyStore.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.dynamodb.model; import java.util.Objects; /** * The configuration for using a single Beacon Key. */ public class SingleKeyStore { /** * The Beacon Key ID. */ private final String keyId; /** * How long (in seconds) the beacon key material is cached locally before it is re-retrieved from DynamoDB and re-authed with AWS KMS. */ private final Integer cacheTTL; protected SingleKeyStore(BuilderImpl builder) { this.keyId = builder.keyId(); this.cacheTTL = builder.cacheTTL(); } /** * @return The Beacon Key ID. */ public String keyId() { return this.keyId; } /** * @return How long (in seconds) the beacon key material is cached locally before it is re-retrieved from DynamoDB and re-authed with AWS KMS. */ public Integer cacheTTL() { return this.cacheTTL; } public Builder toBuilder() { return new BuilderImpl(this); } public static Builder builder() { return new BuilderImpl(); } public interface Builder { /** * @param keyId The Beacon Key ID. */ Builder keyId(String keyId); /** * @return The Beacon Key ID. */ String keyId(); /** * @param cacheTTL How long (in seconds) the beacon key material is cached locally before it is re-retrieved from DynamoDB and re-authed with AWS KMS. */ Builder cacheTTL(Integer cacheTTL); /** * @return How long (in seconds) the beacon key material is cached locally before it is re-retrieved from DynamoDB and re-authed with AWS KMS. */ Integer cacheTTL(); SingleKeyStore build(); } static class BuilderImpl implements Builder { protected String keyId; protected Integer cacheTTL; protected BuilderImpl() { } protected BuilderImpl(SingleKeyStore model) { this.keyId = model.keyId(); this.cacheTTL = model.cacheTTL(); } public Builder keyId(String keyId) { this.keyId = keyId; return this; } public String keyId() { return this.keyId; } public Builder cacheTTL(Integer cacheTTL) { this.cacheTTL = cacheTTL; return this; } public Integer cacheTTL() { return this.cacheTTL; } public SingleKeyStore build() { if (Objects.isNull(this.keyId())) { throw new IllegalArgumentException("Missing value for required field `keyId`"); } if (Objects.isNull(this.cacheTTL())) { throw new IllegalArgumentException("Missing value for required field `cacheTTL`"); } return new SingleKeyStore(this); } } }
5,200
0
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/dbencryptionsdk/dynamodb
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/dbencryptionsdk/dynamodb/model/MultiKeyStore.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.dynamodb.model; import java.util.Objects; import software.amazon.cryptography.materialproviders.model.CacheType; /** * The configuration for using multiple Beacon Keys. */ public class MultiKeyStore { /** * The name of the field that stores the Beacon Key. This may be a Virtual Field. */ private final String keyFieldName; /** * How long (in seconds) the beacon key material is cached locally before it is re-retrieved from DynamoDB and re-authed with AWS KMS. */ private final Integer cacheTTL; /** * Which type of local cache to use. */ private final CacheType cache; protected MultiKeyStore(BuilderImpl builder) { this.keyFieldName = builder.keyFieldName(); this.cacheTTL = builder.cacheTTL(); this.cache = builder.cache(); } /** * @return The name of the field that stores the Beacon Key. This may be a Virtual Field. */ public String keyFieldName() { return this.keyFieldName; } /** * @return How long (in seconds) the beacon key material is cached locally before it is re-retrieved from DynamoDB and re-authed with AWS KMS. */ public Integer cacheTTL() { return this.cacheTTL; } /** * @return Which type of local cache to use. */ public CacheType cache() { return this.cache; } public Builder toBuilder() { return new BuilderImpl(this); } public static Builder builder() { return new BuilderImpl(); } public interface Builder { /** * @param keyFieldName The name of the field that stores the Beacon Key. This may be a Virtual Field. */ Builder keyFieldName(String keyFieldName); /** * @return The name of the field that stores the Beacon Key. This may be a Virtual Field. */ String keyFieldName(); /** * @param cacheTTL How long (in seconds) the beacon key material is cached locally before it is re-retrieved from DynamoDB and re-authed with AWS KMS. */ Builder cacheTTL(Integer cacheTTL); /** * @return How long (in seconds) the beacon key material is cached locally before it is re-retrieved from DynamoDB and re-authed with AWS KMS. */ Integer cacheTTL(); /** * @param cache Which type of local cache to use. */ Builder cache(CacheType cache); /** * @return Which type of local cache to use. */ CacheType cache(); MultiKeyStore build(); } static class BuilderImpl implements Builder { protected String keyFieldName; protected Integer cacheTTL; protected CacheType cache; protected BuilderImpl() { } protected BuilderImpl(MultiKeyStore model) { this.keyFieldName = model.keyFieldName(); this.cacheTTL = model.cacheTTL(); this.cache = model.cache(); } public Builder keyFieldName(String keyFieldName) { this.keyFieldName = keyFieldName; return this; } public String keyFieldName() { return this.keyFieldName; } public Builder cacheTTL(Integer cacheTTL) { this.cacheTTL = cacheTTL; return this; } public Integer cacheTTL() { return this.cacheTTL; } public Builder cache(CacheType cache) { this.cache = cache; return this; } public CacheType cache() { return this.cache; } public MultiKeyStore build() { if (Objects.isNull(this.keyFieldName())) { throw new IllegalArgumentException("Missing value for required field `keyFieldName`"); } if (Objects.isNull(this.cacheTTL())) { throw new IllegalArgumentException("Missing value for required field `cacheTTL`"); } return new MultiKeyStore(this); } } }
5,201
0
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/dbencryptionsdk/dynamodb
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/dbencryptionsdk/dynamodb/model/StandardBeacon.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.dynamodb.model; import java.util.Objects; /** * The configuration for a Standard Beacon. */ public class StandardBeacon { /** * The name for this Standard Beacon. */ private final String name; /** * The length of the calculated beacon. */ private final int length; /** * The DynamoDB document path to the value this beacon will calculate over. If not specified, the beacon will calculate values for the attribute with the name specified in 'name'. */ private final String loc; /** * Optional augmented behavior. */ private final BeaconStyle style; protected StandardBeacon(BuilderImpl builder) { this.name = builder.name(); this.length = builder.length(); this.loc = builder.loc(); this.style = builder.style(); } /** * @return The name for this Standard Beacon. */ public String name() { return this.name; } /** * @return The length of the calculated beacon. */ public int length() { return this.length; } /** * @return The DynamoDB document path to the value this beacon will calculate over. If not specified, the beacon will calculate values for the attribute with the name specified in 'name'. */ public String loc() { return this.loc; } /** * @return Optional augmented behavior. */ public BeaconStyle style() { return this.style; } public Builder toBuilder() { return new BuilderImpl(this); } public static Builder builder() { return new BuilderImpl(); } public interface Builder { /** * @param name The name for this Standard Beacon. */ Builder name(String name); /** * @return The name for this Standard Beacon. */ String name(); /** * @param length The length of the calculated beacon. */ Builder length(int length); /** * @return The length of the calculated beacon. */ int length(); /** * @param loc The DynamoDB document path to the value this beacon will calculate over. If not specified, the beacon will calculate values for the attribute with the name specified in 'name'. */ Builder loc(String loc); /** * @return The DynamoDB document path to the value this beacon will calculate over. If not specified, the beacon will calculate values for the attribute with the name specified in 'name'. */ String loc(); /** * @param style Optional augmented behavior. */ Builder style(BeaconStyle style); /** * @return Optional augmented behavior. */ BeaconStyle style(); StandardBeacon build(); } static class BuilderImpl implements Builder { protected String name; protected int length; private boolean _lengthSet = false; protected String loc; protected BeaconStyle style; protected BuilderImpl() { } protected BuilderImpl(StandardBeacon model) { this.name = model.name(); this.length = model.length(); this._lengthSet = true; this.loc = model.loc(); this.style = model.style(); } public Builder name(String name) { this.name = name; return this; } public String name() { return this.name; } public Builder length(int length) { this.length = length; this._lengthSet = true; return this; } public int length() { return this.length; } public Builder loc(String loc) { this.loc = loc; return this; } public String loc() { return this.loc; } public Builder style(BeaconStyle style) { this.style = style; return this; } public BeaconStyle style() { return this.style; } public StandardBeacon build() { if (Objects.isNull(this.name())) { throw new IllegalArgumentException("Missing value for required field `name`"); } if (!this._lengthSet) { throw new IllegalArgumentException("Missing value for required field `length`"); } if (this._lengthSet && this.length() < 1) { throw new IllegalArgumentException("`length` must be greater than or equal to 1"); } if (this._lengthSet && this.length() > 63) { throw new IllegalArgumentException("`length` must be less than or equal to 63."); } if (Objects.nonNull(this.loc()) && this.loc().length() < 1) { throw new IllegalArgumentException("The size of `loc` must be greater than or equal to 1"); } return new StandardBeacon(this); } } }
5,202
0
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/dbencryptionsdk/dynamodb
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/dbencryptionsdk/dynamodb/model/GetSubstring.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.dynamodb.model; import java.util.Objects; /** * The Virtual Part Transformation that gets a substring from a string. */ public class GetSubstring { /** * The index to start the substring from, inclusive. Negative numbers count from the end. -1 is the last character of a string. */ private final Integer low; /** * The index to stop the substring at, exclusive. Negative numbers count from the end. -1 is the last character of a string. */ private final Integer high; protected GetSubstring(BuilderImpl builder) { this.low = builder.low(); this.high = builder.high(); } /** * @return The index to start the substring from, inclusive. Negative numbers count from the end. -1 is the last character of a string. */ public Integer low() { return this.low; } /** * @return The index to stop the substring at, exclusive. Negative numbers count from the end. -1 is the last character of a string. */ public Integer high() { return this.high; } public Builder toBuilder() { return new BuilderImpl(this); } public static Builder builder() { return new BuilderImpl(); } public interface Builder { /** * @param low The index to start the substring from, inclusive. Negative numbers count from the end. -1 is the last character of a string. */ Builder low(Integer low); /** * @return The index to start the substring from, inclusive. Negative numbers count from the end. -1 is the last character of a string. */ Integer low(); /** * @param high The index to stop the substring at, exclusive. Negative numbers count from the end. -1 is the last character of a string. */ Builder high(Integer high); /** * @return The index to stop the substring at, exclusive. Negative numbers count from the end. -1 is the last character of a string. */ Integer high(); GetSubstring build(); } static class BuilderImpl implements Builder { protected Integer low; protected Integer high; protected BuilderImpl() { } protected BuilderImpl(GetSubstring model) { this.low = model.low(); this.high = model.high(); } public Builder low(Integer low) { this.low = low; return this; } public Integer low() { return this.low; } public Builder high(Integer high) { this.high = high; return this; } public Integer high() { return this.high; } public GetSubstring build() { if (Objects.isNull(this.low())) { throw new IllegalArgumentException("Missing value for required field `low`"); } if (Objects.isNull(this.high())) { throw new IllegalArgumentException("Missing value for required field `high`"); } return new GetSubstring(this); } } }
5,203
0
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/dbencryptionsdk/dynamodb
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/dbencryptionsdk/dynamodb/model/VirtualPart.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.dynamodb.model; import java.util.List; import java.util.Objects; /** * A Virtual Part is the configuration of a transformation on an existing field in an item. */ public class VirtualPart { /** * The DynamoDB document path to the value for this part. */ private final String loc; /** * A list of transformations performed on the value for this part. */ private final List<VirtualTransform> trans; protected VirtualPart(BuilderImpl builder) { this.loc = builder.loc(); this.trans = builder.trans(); } /** * @return The DynamoDB document path to the value for this part. */ public String loc() { return this.loc; } /** * @return A list of transformations performed on the value for this part. */ public List<VirtualTransform> trans() { return this.trans; } public Builder toBuilder() { return new BuilderImpl(this); } public static Builder builder() { return new BuilderImpl(); } public interface Builder { /** * @param loc The DynamoDB document path to the value for this part. */ Builder loc(String loc); /** * @return The DynamoDB document path to the value for this part. */ String loc(); /** * @param trans A list of transformations performed on the value for this part. */ Builder trans(List<VirtualTransform> trans); /** * @return A list of transformations performed on the value for this part. */ List<VirtualTransform> trans(); VirtualPart build(); } static class BuilderImpl implements Builder { protected String loc; protected List<VirtualTransform> trans; protected BuilderImpl() { } protected BuilderImpl(VirtualPart model) { this.loc = model.loc(); this.trans = model.trans(); } public Builder loc(String loc) { this.loc = loc; return this; } public String loc() { return this.loc; } public Builder trans(List<VirtualTransform> trans) { this.trans = trans; return this; } public List<VirtualTransform> trans() { return this.trans; } public VirtualPart build() { if (Objects.isNull(this.loc())) { throw new IllegalArgumentException("Missing value for required field `loc`"); } if (Objects.nonNull(this.loc()) && this.loc().length() < 1) { throw new IllegalArgumentException("The size of `loc` must be greater than or equal to 1"); } if (Objects.nonNull(this.trans()) && this.trans().size() < 1) { throw new IllegalArgumentException("The size of `trans` must be greater than or equal to 1"); } return new VirtualPart(this); } } }
5,204
0
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/dbencryptionsdk/dynamodb
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/dbencryptionsdk/dynamodb/model/GetBranchKeyIdFromDdbKeyOutput.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.dynamodb.model; import java.util.Objects; /** * Outputs for getting the Branch Key that should be used for wrapping and unwrapping data keys. */ public class GetBranchKeyIdFromDdbKeyOutput { /** * The ID of the Branch Key that should be used to wrap and unwrap data keys for this item. */ private final String branchKeyId; protected GetBranchKeyIdFromDdbKeyOutput(BuilderImpl builder) { this.branchKeyId = builder.branchKeyId(); } /** * @return The ID of the Branch Key that should be used to wrap and unwrap data keys for this item. */ public String branchKeyId() { return this.branchKeyId; } public Builder toBuilder() { return new BuilderImpl(this); } public static Builder builder() { return new BuilderImpl(); } public interface Builder { /** * @param branchKeyId The ID of the Branch Key that should be used to wrap and unwrap data keys for this item. */ Builder branchKeyId(String branchKeyId); /** * @return The ID of the Branch Key that should be used to wrap and unwrap data keys for this item. */ String branchKeyId(); GetBranchKeyIdFromDdbKeyOutput build(); } static class BuilderImpl implements Builder { protected String branchKeyId; protected BuilderImpl() { } protected BuilderImpl(GetBranchKeyIdFromDdbKeyOutput model) { this.branchKeyId = model.branchKeyId(); } public Builder branchKeyId(String branchKeyId) { this.branchKeyId = branchKeyId; return this; } public String branchKeyId() { return this.branchKeyId; } public GetBranchKeyIdFromDdbKeyOutput build() { if (Objects.isNull(this.branchKeyId())) { throw new IllegalArgumentException("Missing value for required field `branchKeyId`"); } return new GetBranchKeyIdFromDdbKeyOutput(this); } } }
5,205
0
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/dbencryptionsdk/dynamodb
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/dbencryptionsdk/dynamodb/model/CollectionOfErrors.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.dynamodb.model; import java.util.List; public class CollectionOfErrors extends RuntimeException { /** * The list of Exceptions encountered. */ private final List<RuntimeException> list; protected CollectionOfErrors(BuilderImpl builder) { super(messageFromBuilder(builder), builder.cause()); this.list = builder.list(); } 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 list of Exceptions encountered. */ public List<RuntimeException> list() { return this.list; } 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 list The list of Exceptions encountered. */ Builder list(List<RuntimeException> list); /** * @return The list of Exceptions encountered. */ List<RuntimeException> list(); CollectionOfErrors build(); } static class BuilderImpl implements Builder { protected String message; protected Throwable cause; protected List<RuntimeException> list; protected BuilderImpl() { } protected BuilderImpl(CollectionOfErrors model) { this.cause = model.getCause(); this.message = model.getMessage(); this.list = model.list(); } 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 list(List<RuntimeException> list) { this.list = list; return this; } public List<RuntimeException> list() { return this.list; } public CollectionOfErrors build() { return new CollectionOfErrors(this); } } }
5,206
0
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/dbencryptionsdk/dynamodb
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/dbencryptionsdk/dynamodb/model/CompoundBeacon.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.dynamodb.model; import java.util.List; import java.util.Objects; /** * The configuration for a Compound Beacon. */ public class CompoundBeacon { /** * The name of the Compound Beacon. */ private final String name; /** * The characters used to split parts of a compound beacon. The split character should be a character that does not appear in any Signed Part or Prefix used by the Compound Beacon. */ private final String split; /** * The list of Encrypted Parts that may be included in the compound beacon. */ private final List<EncryptedPart> encrypted; /** * The list of Signed Parts that may be included in the compound beacon. */ private final List<SignedPart> signed; /** * The ordered list of constructors that may be used to create the Compound Beacon. Each constructor is checked, in order, to see if it can construct the beacon. The first constructor that can construct the beacon is used. If no constructor can construct the beacon, the Compound Beacon is not written to the item. */ private final List<Constructor> constructors; protected CompoundBeacon(BuilderImpl builder) { this.name = builder.name(); this.split = builder.split(); this.encrypted = builder.encrypted(); this.signed = builder.signed(); this.constructors = builder.constructors(); } /** * @return The name of the Compound Beacon. */ public String name() { return this.name; } /** * @return The characters used to split parts of a compound beacon. The split character should be a character that does not appear in any Signed Part or Prefix used by the Compound Beacon. */ public String split() { return this.split; } /** * @return The list of Encrypted Parts that may be included in the compound beacon. */ public List<EncryptedPart> encrypted() { return this.encrypted; } /** * @return The list of Signed Parts that may be included in the compound beacon. */ public List<SignedPart> signed() { return this.signed; } /** * @return The ordered list of constructors that may be used to create the Compound Beacon. Each constructor is checked, in order, to see if it can construct the beacon. The first constructor that can construct the beacon is used. If no constructor can construct the beacon, the Compound Beacon is not written to the item. */ public List<Constructor> constructors() { return this.constructors; } public Builder toBuilder() { return new BuilderImpl(this); } public static Builder builder() { return new BuilderImpl(); } public interface Builder { /** * @param name The name of the Compound Beacon. */ Builder name(String name); /** * @return The name of the Compound Beacon. */ String name(); /** * @param split The characters used to split parts of a compound beacon. The split character should be a character that does not appear in any Signed Part or Prefix used by the Compound Beacon. */ Builder split(String split); /** * @return The characters used to split parts of a compound beacon. The split character should be a character that does not appear in any Signed Part or Prefix used by the Compound Beacon. */ String split(); /** * @param encrypted The list of Encrypted Parts that may be included in the compound beacon. */ Builder encrypted(List<EncryptedPart> encrypted); /** * @return The list of Encrypted Parts that may be included in the compound beacon. */ List<EncryptedPart> encrypted(); /** * @param signed The list of Signed Parts that may be included in the compound beacon. */ Builder signed(List<SignedPart> signed); /** * @return The list of Signed Parts that may be included in the compound beacon. */ List<SignedPart> signed(); /** * @param constructors The ordered list of constructors that may be used to create the Compound Beacon. Each constructor is checked, in order, to see if it can construct the beacon. The first constructor that can construct the beacon is used. If no constructor can construct the beacon, the Compound Beacon is not written to the item. */ Builder constructors(List<Constructor> constructors); /** * @return The ordered list of constructors that may be used to create the Compound Beacon. Each constructor is checked, in order, to see if it can construct the beacon. The first constructor that can construct the beacon is used. If no constructor can construct the beacon, the Compound Beacon is not written to the item. */ List<Constructor> constructors(); CompoundBeacon build(); } static class BuilderImpl implements Builder { protected String name; protected String split; protected List<EncryptedPart> encrypted; protected List<SignedPart> signed; protected List<Constructor> constructors; protected BuilderImpl() { } protected BuilderImpl(CompoundBeacon model) { this.name = model.name(); this.split = model.split(); this.encrypted = model.encrypted(); this.signed = model.signed(); this.constructors = model.constructors(); } public Builder name(String name) { this.name = name; return this; } public String name() { return this.name; } public Builder split(String split) { this.split = split; return this; } public String split() { return this.split; } public Builder encrypted(List<EncryptedPart> encrypted) { this.encrypted = encrypted; return this; } public List<EncryptedPart> encrypted() { return this.encrypted; } public Builder signed(List<SignedPart> signed) { this.signed = signed; return this; } public List<SignedPart> signed() { return this.signed; } public Builder constructors(List<Constructor> constructors) { this.constructors = constructors; return this; } public List<Constructor> constructors() { return this.constructors; } public CompoundBeacon build() { if (Objects.isNull(this.name())) { throw new IllegalArgumentException("Missing value for required field `name`"); } if (Objects.isNull(this.split())) { throw new IllegalArgumentException("Missing value for required field `split`"); } if (Objects.nonNull(this.split()) && this.split().length() < 1) { throw new IllegalArgumentException("The size of `split` must be greater than or equal to 1"); } if (Objects.nonNull(this.split()) && this.split().length() > 1) { throw new IllegalArgumentException("The size of `split` must be less than or equal to 1"); } if (Objects.nonNull(this.encrypted()) && this.encrypted().size() < 1) { throw new IllegalArgumentException("The size of `encrypted` must be greater than or equal to 1"); } if (Objects.nonNull(this.signed()) && this.signed().size() < 1) { throw new IllegalArgumentException("The size of `signed` must be greater than or equal to 1"); } if (Objects.nonNull(this.constructors()) && this.constructors().size() < 1) { throw new IllegalArgumentException("The size of `constructors` must be greater than or equal to 1"); } return new CompoundBeacon(this); } } }
5,207
0
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/dbencryptionsdk/dynamodb
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/dbencryptionsdk/dynamodb/itemencryptor/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.dynamodb.itemencryptor; import java.lang.RuntimeException; import software.amazon.cryptography.dbencryptionsdk.dynamodb.itemencryptor.internaldafny.types.Error; import software.amazon.cryptography.dbencryptionsdk.dynamodb.itemencryptor.internaldafny.types.Error_CollectionOfErrors; import software.amazon.cryptography.dbencryptionsdk.dynamodb.itemencryptor.internaldafny.types.Error_DynamoDbItemEncryptorException; import software.amazon.cryptography.dbencryptionsdk.dynamodb.itemencryptor.internaldafny.types.Error_Opaque; import software.amazon.cryptography.dbencryptionsdk.dynamodb.itemencryptor.internaldafny.types.IDynamoDbItemEncryptorClient; import software.amazon.cryptography.dbencryptionsdk.dynamodb.itemencryptor.model.CollectionOfErrors; import software.amazon.cryptography.dbencryptionsdk.dynamodb.itemencryptor.model.DecryptItemInput; import software.amazon.cryptography.dbencryptionsdk.dynamodb.itemencryptor.model.DecryptItemOutput; import software.amazon.cryptography.dbencryptionsdk.dynamodb.itemencryptor.model.DynamoDbItemEncryptorConfig; import software.amazon.cryptography.dbencryptionsdk.dynamodb.itemencryptor.model.DynamoDbItemEncryptorException; import software.amazon.cryptography.dbencryptionsdk.dynamodb.itemencryptor.model.EncryptItemInput; import software.amazon.cryptography.dbencryptionsdk.dynamodb.itemencryptor.model.EncryptItemOutput; import software.amazon.cryptography.dbencryptionsdk.dynamodb.itemencryptor.model.OpaqueError; import software.amazon.cryptography.dbencryptionsdk.dynamodb.itemencryptor.model.ParsedHeader; 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 DynamoDbItemEncryptorException Error( Error_DynamoDbItemEncryptorException dafnyValue) { DynamoDbItemEncryptorException.Builder nativeBuilder = DynamoDbItemEncryptorException.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_DynamoDbItemEncryptorException()) { return ToNative.Error((Error_DynamoDbItemEncryptorException) 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_ComAmazonawsDynamodb()) { return software.amazon.cryptography.services.dynamodb.internaldafny.ToNative.Error(dafnyValue.dtor_ComAmazonawsDynamodb()); } if (dafnyValue.is_AwsCryptographyMaterialProviders()) { return software.amazon.cryptography.materialproviders.ToNative.Error(dafnyValue.dtor_AwsCryptographyMaterialProviders()); } if (dafnyValue.is_AwsCryptographyDbEncryptionSdkStructuredEncryption()) { return software.amazon.cryptography.dbencryptionsdk.structuredencryption.ToNative.Error(dafnyValue.dtor_AwsCryptographyDbEncryptionSdkStructuredEncryption()); } if (dafnyValue.is_AwsCryptographyDbEncryptionSdkDynamoDb()) { return software.amazon.cryptography.dbencryptionsdk.dynamodb.ToNative.Error(dafnyValue.dtor_AwsCryptographyDbEncryptionSdkDynamoDb()); } OpaqueError.Builder nativeBuilder = OpaqueError.builder(); nativeBuilder.obj(dafnyValue); return nativeBuilder.build(); } public static DecryptItemInput DecryptItemInput( software.amazon.cryptography.dbencryptionsdk.dynamodb.itemencryptor.internaldafny.types.DecryptItemInput dafnyValue) { DecryptItemInput.Builder nativeBuilder = DecryptItemInput.builder(); nativeBuilder.encryptedItem(software.amazon.cryptography.services.dynamodb.internaldafny.ToNative.AttributeMap(dafnyValue.dtor_encryptedItem())); return nativeBuilder.build(); } public static DecryptItemOutput DecryptItemOutput( software.amazon.cryptography.dbencryptionsdk.dynamodb.itemencryptor.internaldafny.types.DecryptItemOutput dafnyValue) { DecryptItemOutput.Builder nativeBuilder = DecryptItemOutput.builder(); nativeBuilder.plaintextItem(software.amazon.cryptography.services.dynamodb.internaldafny.ToNative.AttributeMap(dafnyValue.dtor_plaintextItem())); if (dafnyValue.dtor_parsedHeader().is_Some()) { nativeBuilder.parsedHeader(ToNative.ParsedHeader(dafnyValue.dtor_parsedHeader().dtor_value())); } return nativeBuilder.build(); } public static DynamoDbItemEncryptorConfig DynamoDbItemEncryptorConfig( software.amazon.cryptography.dbencryptionsdk.dynamodb.itemencryptor.internaldafny.types.DynamoDbItemEncryptorConfig dafnyValue) { DynamoDbItemEncryptorConfig.Builder nativeBuilder = DynamoDbItemEncryptorConfig.builder(); nativeBuilder.logicalTableName(software.amazon.smithy.dafny.conversion.ToNative.Simple.String(dafnyValue.dtor_logicalTableName())); nativeBuilder.partitionKeyName(software.amazon.smithy.dafny.conversion.ToNative.Simple.String(dafnyValue.dtor_partitionKeyName())); if (dafnyValue.dtor_sortKeyName().is_Some()) { nativeBuilder.sortKeyName(software.amazon.smithy.dafny.conversion.ToNative.Simple.String(dafnyValue.dtor_sortKeyName().dtor_value())); } nativeBuilder.attributeActionsOnEncrypt(software.amazon.cryptography.dbencryptionsdk.dynamodb.ToNative.AttributeActions(dafnyValue.dtor_attributeActionsOnEncrypt())); if (dafnyValue.dtor_allowedUnsignedAttributes().is_Some()) { nativeBuilder.allowedUnsignedAttributes(software.amazon.cryptography.services.dynamodb.internaldafny.ToNative.AttributeNameList(dafnyValue.dtor_allowedUnsignedAttributes().dtor_value())); } if (dafnyValue.dtor_allowedUnsignedAttributePrefix().is_Some()) { nativeBuilder.allowedUnsignedAttributePrefix(software.amazon.smithy.dafny.conversion.ToNative.Simple.String(dafnyValue.dtor_allowedUnsignedAttributePrefix().dtor_value())); } if (dafnyValue.dtor_algorithmSuiteId().is_Some()) { nativeBuilder.algorithmSuiteId(software.amazon.cryptography.materialproviders.ToNative.DBEAlgorithmSuiteId(dafnyValue.dtor_algorithmSuiteId().dtor_value())); } if (dafnyValue.dtor_keyring().is_Some()) { nativeBuilder.keyring(software.amazon.cryptography.materialproviders.ToNative.Keyring(dafnyValue.dtor_keyring().dtor_value())); } if (dafnyValue.dtor_cmm().is_Some()) { nativeBuilder.cmm(software.amazon.cryptography.materialproviders.ToNative.CryptographicMaterialsManager(dafnyValue.dtor_cmm().dtor_value())); } if (dafnyValue.dtor_legacyOverride().is_Some()) { nativeBuilder.legacyOverride(software.amazon.cryptography.dbencryptionsdk.dynamodb.ToNative.LegacyOverride(dafnyValue.dtor_legacyOverride().dtor_value())); } if (dafnyValue.dtor_plaintextOverride().is_Some()) { nativeBuilder.plaintextOverride(software.amazon.cryptography.dbencryptionsdk.dynamodb.ToNative.PlaintextOverride(dafnyValue.dtor_plaintextOverride().dtor_value())); } return nativeBuilder.build(); } public static EncryptItemInput EncryptItemInput( software.amazon.cryptography.dbencryptionsdk.dynamodb.itemencryptor.internaldafny.types.EncryptItemInput dafnyValue) { EncryptItemInput.Builder nativeBuilder = EncryptItemInput.builder(); nativeBuilder.plaintextItem(software.amazon.cryptography.services.dynamodb.internaldafny.ToNative.AttributeMap(dafnyValue.dtor_plaintextItem())); return nativeBuilder.build(); } public static EncryptItemOutput EncryptItemOutput( software.amazon.cryptography.dbencryptionsdk.dynamodb.itemencryptor.internaldafny.types.EncryptItemOutput dafnyValue) { EncryptItemOutput.Builder nativeBuilder = EncryptItemOutput.builder(); nativeBuilder.encryptedItem(software.amazon.cryptography.services.dynamodb.internaldafny.ToNative.AttributeMap(dafnyValue.dtor_encryptedItem())); if (dafnyValue.dtor_parsedHeader().is_Some()) { nativeBuilder.parsedHeader(ToNative.ParsedHeader(dafnyValue.dtor_parsedHeader().dtor_value())); } return nativeBuilder.build(); } public static ParsedHeader ParsedHeader( software.amazon.cryptography.dbencryptionsdk.dynamodb.itemencryptor.internaldafny.types.ParsedHeader dafnyValue) { ParsedHeader.Builder nativeBuilder = ParsedHeader.builder(); nativeBuilder.attributeActionsOnEncrypt(software.amazon.cryptography.dbencryptionsdk.dynamodb.ToNative.AttributeActions(dafnyValue.dtor_attributeActionsOnEncrypt())); 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 DynamoDbItemEncryptor DynamoDbItemEncryptor( IDynamoDbItemEncryptorClient dafnyValue) { return new DynamoDbItemEncryptor(dafnyValue); } }
5,208
0
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/dbencryptionsdk/dynamodb
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/dbencryptionsdk/dynamodb/itemencryptor/DynamoDbItemEncryptor.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.dynamodb.itemencryptor; import Wrappers_Compile.Result; import java.lang.IllegalArgumentException; import java.util.Objects; import software.amazon.cryptography.dbencryptionsdk.dynamodb.itemencryptor.internaldafny.DynamoDbItemEncryptorClient; import software.amazon.cryptography.dbencryptionsdk.dynamodb.itemencryptor.internaldafny.__default; import software.amazon.cryptography.dbencryptionsdk.dynamodb.itemencryptor.internaldafny.types.Error; import software.amazon.cryptography.dbencryptionsdk.dynamodb.itemencryptor.internaldafny.types.IDynamoDbItemEncryptorClient; import software.amazon.cryptography.dbencryptionsdk.dynamodb.itemencryptor.model.DecryptItemInput; import software.amazon.cryptography.dbencryptionsdk.dynamodb.itemencryptor.model.DecryptItemOutput; import software.amazon.cryptography.dbencryptionsdk.dynamodb.itemencryptor.model.DynamoDbItemEncryptorConfig; import software.amazon.cryptography.dbencryptionsdk.dynamodb.itemencryptor.model.EncryptItemInput; import software.amazon.cryptography.dbencryptionsdk.dynamodb.itemencryptor.model.EncryptItemOutput; public class DynamoDbItemEncryptor { private final IDynamoDbItemEncryptorClient _impl; protected DynamoDbItemEncryptor(BuilderImpl builder) { DynamoDbItemEncryptorConfig input = builder.DynamoDbItemEncryptorConfig(); software.amazon.cryptography.dbencryptionsdk.dynamodb.itemencryptor.internaldafny.types.DynamoDbItemEncryptorConfig dafnyValue = ToDafny.DynamoDbItemEncryptorConfig(input); Result<DynamoDbItemEncryptorClient, Error> result = __default.DynamoDbItemEncryptor(dafnyValue); if (result.is_Failure()) { throw ToNative.Error(result.dtor_error()); } this._impl = result.dtor_value(); } DynamoDbItemEncryptor(IDynamoDbItemEncryptorClient impl) { this._impl = impl; } public static Builder builder() { return new BuilderImpl(); } /** * Decrypt a DynamoDB Item. * * @param input Inputs for decrypting a DynamoDB Item. * @return Outputs for decrypting a DynamoDB Item. */ public DecryptItemOutput DecryptItem(DecryptItemInput input) { software.amazon.cryptography.dbencryptionsdk.dynamodb.itemencryptor.internaldafny.types.DecryptItemInput dafnyValue = ToDafny.DecryptItemInput(input); Result<software.amazon.cryptography.dbencryptionsdk.dynamodb.itemencryptor.internaldafny.types.DecryptItemOutput, Error> result = this._impl.DecryptItem(dafnyValue); if (result.is_Failure()) { throw ToNative.Error(result.dtor_error()); } return ToNative.DecryptItemOutput(result.dtor_value()); } /** * Encrypt a DynamoDB Item. * * @param input Inputs for encrypting a DynamoDB Item. * @return Outputs for encrypting a DynamoDB Item. */ public EncryptItemOutput EncryptItem(EncryptItemInput input) { software.amazon.cryptography.dbencryptionsdk.dynamodb.itemencryptor.internaldafny.types.EncryptItemInput dafnyValue = ToDafny.EncryptItemInput(input); Result<software.amazon.cryptography.dbencryptionsdk.dynamodb.itemencryptor.internaldafny.types.EncryptItemOutput, Error> result = this._impl.EncryptItem(dafnyValue); if (result.is_Failure()) { throw ToNative.Error(result.dtor_error()); } return ToNative.EncryptItemOutput(result.dtor_value()); } protected IDynamoDbItemEncryptorClient impl() { return this._impl; } public interface Builder { /** * @param DynamoDbItemEncryptorConfig The configuration for the client-side encryption of DynamoDB items. */ Builder DynamoDbItemEncryptorConfig(DynamoDbItemEncryptorConfig DynamoDbItemEncryptorConfig); /** * @return The configuration for the client-side encryption of DynamoDB items. */ DynamoDbItemEncryptorConfig DynamoDbItemEncryptorConfig(); DynamoDbItemEncryptor build(); } static class BuilderImpl implements Builder { protected DynamoDbItemEncryptorConfig DynamoDbItemEncryptorConfig; protected BuilderImpl() { } public Builder DynamoDbItemEncryptorConfig( DynamoDbItemEncryptorConfig DynamoDbItemEncryptorConfig) { this.DynamoDbItemEncryptorConfig = DynamoDbItemEncryptorConfig; return this; } public DynamoDbItemEncryptorConfig DynamoDbItemEncryptorConfig() { return this.DynamoDbItemEncryptorConfig; } public DynamoDbItemEncryptor build() { if (Objects.isNull(this.DynamoDbItemEncryptorConfig())) { throw new IllegalArgumentException("Missing value for required field `DynamoDbItemEncryptorConfig`"); } return new DynamoDbItemEncryptor(this); } } }
5,209
0
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/dbencryptionsdk/dynamodb
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/dbencryptionsdk/dynamodb/itemencryptor/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.dynamodb.itemencryptor; import Wrappers_Compile.Option; import dafny.DafnyMap; import dafny.DafnySequence; import java.lang.Byte; import java.lang.Character; import java.lang.RuntimeException; import java.util.Objects; import software.amazon.cryptography.dbencryptionsdk.dynamodb.internaldafny.types.LegacyOverride; import software.amazon.cryptography.dbencryptionsdk.dynamodb.internaldafny.types.PlaintextOverride; import software.amazon.cryptography.dbencryptionsdk.dynamodb.itemencryptor.internaldafny.types.DecryptItemInput; import software.amazon.cryptography.dbencryptionsdk.dynamodb.itemencryptor.internaldafny.types.DecryptItemOutput; import software.amazon.cryptography.dbencryptionsdk.dynamodb.itemencryptor.internaldafny.types.DynamoDbItemEncryptorConfig; import software.amazon.cryptography.dbencryptionsdk.dynamodb.itemencryptor.internaldafny.types.EncryptItemInput; import software.amazon.cryptography.dbencryptionsdk.dynamodb.itemencryptor.internaldafny.types.EncryptItemOutput; import software.amazon.cryptography.dbencryptionsdk.dynamodb.itemencryptor.internaldafny.types.Error; import software.amazon.cryptography.dbencryptionsdk.dynamodb.itemencryptor.internaldafny.types.Error_DynamoDbItemEncryptorException; import software.amazon.cryptography.dbencryptionsdk.dynamodb.itemencryptor.internaldafny.types.IDynamoDbItemEncryptorClient; import software.amazon.cryptography.dbencryptionsdk.dynamodb.itemencryptor.internaldafny.types.ParsedHeader; import software.amazon.cryptography.dbencryptionsdk.dynamodb.itemencryptor.model.CollectionOfErrors; import software.amazon.cryptography.dbencryptionsdk.dynamodb.itemencryptor.model.DynamoDbItemEncryptorException; import software.amazon.cryptography.dbencryptionsdk.dynamodb.itemencryptor.model.OpaqueError; import software.amazon.cryptography.dbencryptionsdk.structuredencryption.internaldafny.types.CryptoAction; import software.amazon.cryptography.materialproviders.internaldafny.types.DBEAlgorithmSuiteId; import software.amazon.cryptography.materialproviders.internaldafny.types.EncryptedDataKey; import software.amazon.cryptography.materialproviders.internaldafny.types.ICryptographicMaterialsManager; import software.amazon.cryptography.materialproviders.internaldafny.types.IKeyring; import software.amazon.cryptography.services.dynamodb.internaldafny.types.AttributeValue; public class ToDafny { public static Error Error(RuntimeException nativeValue) { if (nativeValue instanceof DynamoDbItemEncryptorException) { return ToDafny.Error((DynamoDbItemEncryptorException) 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 DecryptItemInput DecryptItemInput( software.amazon.cryptography.dbencryptionsdk.dynamodb.itemencryptor.model.DecryptItemInput nativeValue) { DafnyMap<? extends DafnySequence<? extends Character>, ? extends AttributeValue> encryptedItem; encryptedItem = software.amazon.cryptography.services.dynamodb.internaldafny.ToDafny.AttributeMap(nativeValue.encryptedItem()); return new DecryptItemInput(encryptedItem); } public static DecryptItemOutput DecryptItemOutput( software.amazon.cryptography.dbencryptionsdk.dynamodb.itemencryptor.model.DecryptItemOutput nativeValue) { DafnyMap<? extends DafnySequence<? extends Character>, ? extends AttributeValue> plaintextItem; plaintextItem = software.amazon.cryptography.services.dynamodb.internaldafny.ToDafny.AttributeMap(nativeValue.plaintextItem()); Option<ParsedHeader> parsedHeader; parsedHeader = Objects.nonNull(nativeValue.parsedHeader()) ? Option.create_Some(ToDafny.ParsedHeader(nativeValue.parsedHeader())) : Option.create_None(); return new DecryptItemOutput(plaintextItem, parsedHeader); } public static DynamoDbItemEncryptorConfig DynamoDbItemEncryptorConfig( software.amazon.cryptography.dbencryptionsdk.dynamodb.itemencryptor.model.DynamoDbItemEncryptorConfig nativeValue) { DafnySequence<? extends Character> logicalTableName; logicalTableName = software.amazon.smithy.dafny.conversion.ToDafny.Simple.CharacterSequence(nativeValue.logicalTableName()); DafnySequence<? extends Character> partitionKeyName; partitionKeyName = software.amazon.smithy.dafny.conversion.ToDafny.Simple.CharacterSequence(nativeValue.partitionKeyName()); Option<DafnySequence<? extends Character>> sortKeyName; sortKeyName = Objects.nonNull(nativeValue.sortKeyName()) ? Option.create_Some(software.amazon.smithy.dafny.conversion.ToDafny.Simple.CharacterSequence(nativeValue.sortKeyName())) : Option.create_None(); DafnyMap<? extends DafnySequence<? extends Character>, ? extends CryptoAction> attributeActionsOnEncrypt; attributeActionsOnEncrypt = software.amazon.cryptography.dbencryptionsdk.dynamodb.ToDafny.AttributeActions(nativeValue.attributeActionsOnEncrypt()); Option<DafnySequence<? extends DafnySequence<? extends Character>>> allowedUnsignedAttributes; allowedUnsignedAttributes = (Objects.nonNull(nativeValue.allowedUnsignedAttributes()) && nativeValue.allowedUnsignedAttributes().size() > 0) ? Option.create_Some(software.amazon.cryptography.services.dynamodb.internaldafny.ToDafny.AttributeNameList(nativeValue.allowedUnsignedAttributes())) : Option.create_None(); Option<DafnySequence<? extends Character>> allowedUnsignedAttributePrefix; allowedUnsignedAttributePrefix = Objects.nonNull(nativeValue.allowedUnsignedAttributePrefix()) ? Option.create_Some(software.amazon.smithy.dafny.conversion.ToDafny.Simple.CharacterSequence(nativeValue.allowedUnsignedAttributePrefix())) : Option.create_None(); Option<DBEAlgorithmSuiteId> algorithmSuiteId; algorithmSuiteId = Objects.nonNull(nativeValue.algorithmSuiteId()) ? Option.create_Some(software.amazon.cryptography.materialproviders.ToDafny.DBEAlgorithmSuiteId(nativeValue.algorithmSuiteId())) : Option.create_None(); Option<IKeyring> keyring; keyring = Objects.nonNull(nativeValue.keyring()) ? Option.create_Some(software.amazon.cryptography.materialproviders.ToDafny.Keyring(nativeValue.keyring())) : Option.create_None(); Option<ICryptographicMaterialsManager> cmm; cmm = Objects.nonNull(nativeValue.cmm()) ? Option.create_Some(software.amazon.cryptography.materialproviders.ToDafny.CryptographicMaterialsManager(nativeValue.cmm())) : Option.create_None(); Option<LegacyOverride> legacyOverride; legacyOverride = Objects.nonNull(nativeValue.legacyOverride()) ? Option.create_Some(software.amazon.cryptography.dbencryptionsdk.dynamodb.ToDafny.LegacyOverride(nativeValue.legacyOverride())) : Option.create_None(); Option<PlaintextOverride> plaintextOverride; plaintextOverride = Objects.nonNull(nativeValue.plaintextOverride()) ? Option.create_Some(software.amazon.cryptography.dbencryptionsdk.dynamodb.ToDafny.PlaintextOverride(nativeValue.plaintextOverride())) : Option.create_None(); return new DynamoDbItemEncryptorConfig(logicalTableName, partitionKeyName, sortKeyName, attributeActionsOnEncrypt, allowedUnsignedAttributes, allowedUnsignedAttributePrefix, algorithmSuiteId, keyring, cmm, legacyOverride, plaintextOverride); } public static EncryptItemInput EncryptItemInput( software.amazon.cryptography.dbencryptionsdk.dynamodb.itemencryptor.model.EncryptItemInput nativeValue) { DafnyMap<? extends DafnySequence<? extends Character>, ? extends AttributeValue> plaintextItem; plaintextItem = software.amazon.cryptography.services.dynamodb.internaldafny.ToDafny.AttributeMap(nativeValue.plaintextItem()); return new EncryptItemInput(plaintextItem); } public static EncryptItemOutput EncryptItemOutput( software.amazon.cryptography.dbencryptionsdk.dynamodb.itemencryptor.model.EncryptItemOutput nativeValue) { DafnyMap<? extends DafnySequence<? extends Character>, ? extends AttributeValue> encryptedItem; encryptedItem = software.amazon.cryptography.services.dynamodb.internaldafny.ToDafny.AttributeMap(nativeValue.encryptedItem()); Option<ParsedHeader> parsedHeader; parsedHeader = Objects.nonNull(nativeValue.parsedHeader()) ? Option.create_Some(ToDafny.ParsedHeader(nativeValue.parsedHeader())) : Option.create_None(); return new EncryptItemOutput(encryptedItem, parsedHeader); } public static ParsedHeader ParsedHeader( software.amazon.cryptography.dbencryptionsdk.dynamodb.itemencryptor.model.ParsedHeader nativeValue) { DafnyMap<? extends DafnySequence<? extends Character>, ? extends CryptoAction> attributeActionsOnEncrypt; attributeActionsOnEncrypt = software.amazon.cryptography.dbencryptionsdk.dynamodb.ToDafny.AttributeActions(nativeValue.attributeActionsOnEncrypt()); 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(attributeActionsOnEncrypt, algorithmSuiteId, encryptedDataKeys, storedEncryptionContext); } public static Error Error(DynamoDbItemEncryptorException nativeValue) { DafnySequence<? extends Character> message; message = software.amazon.smithy.dafny.conversion.ToDafny.Simple.CharacterSequence(nativeValue.message()); return new Error_DynamoDbItemEncryptorException(message); } public static IDynamoDbItemEncryptorClient DynamoDbItemEncryptor( DynamoDbItemEncryptor nativeValue) { return nativeValue.impl(); } }
5,210
0
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/dbencryptionsdk/dynamodb/itemencryptor
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/dbencryptionsdk/dynamodb/itemencryptor/model/DecryptItemInput.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.dynamodb.itemencryptor.model; import java.util.Map; import java.util.Objects; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; /** * Inputs for decrypting a DynamoDB Item. */ public class DecryptItemInput { /** * The encrypted DynamoDB item to decrypt. */ private final Map<String, AttributeValue> encryptedItem; protected DecryptItemInput(BuilderImpl builder) { this.encryptedItem = builder.encryptedItem(); } /** * @return The encrypted DynamoDB item to decrypt. */ public Map<String, AttributeValue> encryptedItem() { return this.encryptedItem; } public Builder toBuilder() { return new BuilderImpl(this); } public static Builder builder() { return new BuilderImpl(); } public interface Builder { /** * @param encryptedItem The encrypted DynamoDB item to decrypt. */ Builder encryptedItem(Map<String, AttributeValue> encryptedItem); /** * @return The encrypted DynamoDB item to decrypt. */ Map<String, AttributeValue> encryptedItem(); DecryptItemInput build(); } static class BuilderImpl implements Builder { protected Map<String, AttributeValue> encryptedItem; protected BuilderImpl() { } protected BuilderImpl(DecryptItemInput model) { this.encryptedItem = model.encryptedItem(); } public Builder encryptedItem(Map<String, AttributeValue> encryptedItem) { this.encryptedItem = encryptedItem; return this; } public Map<String, AttributeValue> encryptedItem() { return this.encryptedItem; } public DecryptItemInput build() { if (Objects.isNull(this.encryptedItem())) { throw new IllegalArgumentException("Missing value for required field `encryptedItem`"); } return new DecryptItemInput(this); } } }
5,211
0
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/dbencryptionsdk/dynamodb/itemencryptor
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/dbencryptionsdk/dynamodb/itemencryptor/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.dynamodb.itemencryptor.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,212
0
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/dbencryptionsdk/dynamodb/itemencryptor
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/dbencryptionsdk/dynamodb/itemencryptor/model/EncryptItemInput.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.dynamodb.itemencryptor.model; import java.util.Map; import java.util.Objects; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; /** * Inputs for encrypting a DynamoDB Item. */ public class EncryptItemInput { /** * The DynamoDB item to encrypt. */ private final Map<String, AttributeValue> plaintextItem; protected EncryptItemInput(BuilderImpl builder) { this.plaintextItem = builder.plaintextItem(); } /** * @return The DynamoDB item to encrypt. */ public Map<String, AttributeValue> plaintextItem() { return this.plaintextItem; } public Builder toBuilder() { return new BuilderImpl(this); } public static Builder builder() { return new BuilderImpl(); } public interface Builder { /** * @param plaintextItem The DynamoDB item to encrypt. */ Builder plaintextItem(Map<String, AttributeValue> plaintextItem); /** * @return The DynamoDB item to encrypt. */ Map<String, AttributeValue> plaintextItem(); EncryptItemInput build(); } static class BuilderImpl implements Builder { protected Map<String, AttributeValue> plaintextItem; protected BuilderImpl() { } protected BuilderImpl(EncryptItemInput model) { this.plaintextItem = model.plaintextItem(); } public Builder plaintextItem(Map<String, AttributeValue> plaintextItem) { this.plaintextItem = plaintextItem; return this; } public Map<String, AttributeValue> plaintextItem() { return this.plaintextItem; } public EncryptItemInput build() { if (Objects.isNull(this.plaintextItem())) { throw new IllegalArgumentException("Missing value for required field `plaintextItem`"); } return new EncryptItemInput(this); } } }
5,213
0
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/dbencryptionsdk/dynamodb/itemencryptor
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/dbencryptionsdk/dynamodb/itemencryptor/model/DynamoDbItemEncryptorException.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.dynamodb.itemencryptor.model; import java.util.Objects; public class DynamoDbItemEncryptorException extends RuntimeException { protected DynamoDbItemEncryptorException(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(); DynamoDbItemEncryptorException build(); } static class BuilderImpl implements Builder { protected String message; protected Throwable cause; protected BuilderImpl() { } protected BuilderImpl(DynamoDbItemEncryptorException 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 DynamoDbItemEncryptorException build() { if (Objects.isNull(this.message())) { throw new IllegalArgumentException("Missing value for required field `message`"); } return new DynamoDbItemEncryptorException(this); } } }
5,214
0
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/dbencryptionsdk/dynamodb/itemencryptor
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/dbencryptionsdk/dynamodb/itemencryptor/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.dynamodb.itemencryptor.model; import java.util.List; import java.util.Map; import java.util.Objects; import software.amazon.cryptography.dbencryptionsdk.structuredencryption.model.CryptoAction; import software.amazon.cryptography.materialproviders.model.DBEAlgorithmSuiteId; import software.amazon.cryptography.materialproviders.model.EncryptedDataKey; /** * A parsed version of the header that was written with or read on an encrypted DynamoDB item. */ public class ParsedHeader { /** * The non-DO_NOTHING Crypto Actions that were configured when this item was originally encrypted. */ private final Map<String, CryptoAction> attributeActionsOnEncrypt; /** * The ID of the algorithm suite that was used to encrypt this item. */ private final DBEAlgorithmSuiteId algorithmSuiteId; /** * The encrypted data keys that are stored in the header of this item. */ private final List<EncryptedDataKey> encryptedDataKeys; /** * The portion of the encryption context that was stored in the header of this item. */ private final Map<String, String> storedEncryptionContext; protected ParsedHeader(BuilderImpl builder) { this.attributeActionsOnEncrypt = builder.attributeActionsOnEncrypt(); this.algorithmSuiteId = builder.algorithmSuiteId(); this.encryptedDataKeys = builder.encryptedDataKeys(); this.storedEncryptionContext = builder.storedEncryptionContext(); } /** * @return The non-DO_NOTHING Crypto Actions that were configured when this item was originally encrypted. */ public Map<String, CryptoAction> attributeActionsOnEncrypt() { return this.attributeActionsOnEncrypt; } /** * @return The ID of the algorithm suite that was used to encrypt this item. */ public DBEAlgorithmSuiteId algorithmSuiteId() { return this.algorithmSuiteId; } /** * @return The encrypted data keys that are stored in the header of this item. */ public List<EncryptedDataKey> encryptedDataKeys() { return this.encryptedDataKeys; } /** * @return The portion of the encryption context that was stored in the header of this item. */ 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 { /** * @param attributeActionsOnEncrypt The non-DO_NOTHING Crypto Actions that were configured when this item was originally encrypted. */ Builder attributeActionsOnEncrypt(Map<String, CryptoAction> attributeActionsOnEncrypt); /** * @return The non-DO_NOTHING Crypto Actions that were configured when this item was originally encrypted. */ Map<String, CryptoAction> attributeActionsOnEncrypt(); /** * @param algorithmSuiteId The ID of the algorithm suite that was used to encrypt this item. */ Builder algorithmSuiteId(DBEAlgorithmSuiteId algorithmSuiteId); /** * @return The ID of the algorithm suite that was used to encrypt this item. */ DBEAlgorithmSuiteId algorithmSuiteId(); /** * @param encryptedDataKeys The encrypted data keys that are stored in the header of this item. */ Builder encryptedDataKeys(List<EncryptedDataKey> encryptedDataKeys); /** * @return The encrypted data keys that are stored in the header of this item. */ List<EncryptedDataKey> encryptedDataKeys(); /** * @param storedEncryptionContext The portion of the encryption context that was stored in the header of this item. */ Builder storedEncryptionContext(Map<String, String> storedEncryptionContext); /** * @return The portion of the encryption context that was stored in the header of this item. */ Map<String, String> storedEncryptionContext(); ParsedHeader build(); } static class BuilderImpl implements Builder { protected Map<String, CryptoAction> attributeActionsOnEncrypt; protected DBEAlgorithmSuiteId algorithmSuiteId; protected List<EncryptedDataKey> encryptedDataKeys; protected Map<String, String> storedEncryptionContext; protected BuilderImpl() { } protected BuilderImpl(ParsedHeader model) { this.attributeActionsOnEncrypt = model.attributeActionsOnEncrypt(); this.algorithmSuiteId = model.algorithmSuiteId(); this.encryptedDataKeys = model.encryptedDataKeys(); this.storedEncryptionContext = model.storedEncryptionContext(); } public Builder attributeActionsOnEncrypt(Map<String, CryptoAction> attributeActionsOnEncrypt) { this.attributeActionsOnEncrypt = attributeActionsOnEncrypt; return this; } public Map<String, CryptoAction> attributeActionsOnEncrypt() { return this.attributeActionsOnEncrypt; } 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.attributeActionsOnEncrypt())) { throw new IllegalArgumentException("Missing value for required field `attributeActionsOnEncrypt`"); } 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,215
0
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/dbencryptionsdk/dynamodb/itemencryptor
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/dbencryptionsdk/dynamodb/itemencryptor/model/DynamoDbItemEncryptorConfig.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.dynamodb.itemencryptor.model; import java.util.List; import java.util.Map; import java.util.Objects; import software.amazon.cryptography.dbencryptionsdk.dynamodb.model.LegacyOverride; import software.amazon.cryptography.dbencryptionsdk.dynamodb.model.PlaintextOverride; import software.amazon.cryptography.dbencryptionsdk.structuredencryption.model.CryptoAction; import software.amazon.cryptography.materialproviders.CryptographicMaterialsManager; import software.amazon.cryptography.materialproviders.ICryptographicMaterialsManager; import software.amazon.cryptography.materialproviders.IKeyring; import software.amazon.cryptography.materialproviders.Keyring; import software.amazon.cryptography.materialproviders.model.DBEAlgorithmSuiteId; /** * The configuration for the client-side encryption of DynamoDB items. */ public class DynamoDbItemEncryptorConfig { /** * The logical table name for this table. This is the name that is cryptographically bound with your data. This can be the same as the actual DynamoDB table name. It's purpose is to be distinct from the DynamoDB table name so that the data may still be authenticated if being read from different (but logically similar) tables, such as a backup table. */ private final String logicalTableName; /** * The name of the partition key on the table this item will be written to or was read from. */ private final String partitionKeyName; /** * If this table contains a sort key, the name of the sort key on the table this item will be written to or was read from. */ private final String sortKeyName; /** * A map that describes what attributes should be encrypted and/or signed on encrypt. This map must contain all attributes that might be encountered during encryption. */ private final Map<String, CryptoAction> attributeActionsOnEncrypt; /** * A list of attribute names such that, if encountered during decryption, those attributes are treated as unsigned. */ private final List<String> allowedUnsignedAttributes; /** * A prefix such that, if during decryption any attribute has a name with this prefix, it is treated as unsigned. */ private final String allowedUnsignedAttributePrefix; /** * An ID for the algorithm suite to use during encryption and decryption. */ private final DBEAlgorithmSuiteId algorithmSuiteId; /** * The Keyring that should be used to wrap and unwrap data keys. If specified a Default Cryptographic Materials Manager with this Keyring is used to obtain materials for encryption and decryption. Either a Keyring or a Cryptographic Materials Manager must be specified. */ private final IKeyring keyring; /** * The Cryptographic Materials Manager that is used to obtain materials for encryption and decryption. Either a Keyring or a Cryptographic Materials Manager must be specified. */ private final ICryptographicMaterialsManager cmm; /** * A configuration that override encryption and/or decryption to instead perform legacy encryption and/or decryption. Used as part of migration from version 2.x to version 3.x. */ private final LegacyOverride legacyOverride; /** * A configuration that override encryption and/or decryption to instead passthrough and write and/or read plaintext. Used to update plaintext tables to fully use client-side encryption. */ private final PlaintextOverride plaintextOverride; protected DynamoDbItemEncryptorConfig(BuilderImpl builder) { this.logicalTableName = builder.logicalTableName(); this.partitionKeyName = builder.partitionKeyName(); this.sortKeyName = builder.sortKeyName(); this.attributeActionsOnEncrypt = builder.attributeActionsOnEncrypt(); this.allowedUnsignedAttributes = builder.allowedUnsignedAttributes(); this.allowedUnsignedAttributePrefix = builder.allowedUnsignedAttributePrefix(); this.algorithmSuiteId = builder.algorithmSuiteId(); this.keyring = builder.keyring(); this.cmm = builder.cmm(); this.legacyOverride = builder.legacyOverride(); this.plaintextOverride = builder.plaintextOverride(); } /** * @return The logical table name for this table. This is the name that is cryptographically bound with your data. This can be the same as the actual DynamoDB table name. It's purpose is to be distinct from the DynamoDB table name so that the data may still be authenticated if being read from different (but logically similar) tables, such as a backup table. */ public String logicalTableName() { return this.logicalTableName; } /** * @return The name of the partition key on the table this item will be written to or was read from. */ public String partitionKeyName() { return this.partitionKeyName; } /** * @return If this table contains a sort key, the name of the sort key on the table this item will be written to or was read from. */ public String sortKeyName() { return this.sortKeyName; } /** * @return A map that describes what attributes should be encrypted and/or signed on encrypt. This map must contain all attributes that might be encountered during encryption. */ public Map<String, CryptoAction> attributeActionsOnEncrypt() { return this.attributeActionsOnEncrypt; } /** * @return A list of attribute names such that, if encountered during decryption, those attributes are treated as unsigned. */ public List<String> allowedUnsignedAttributes() { return this.allowedUnsignedAttributes; } /** * @return A prefix such that, if during decryption any attribute has a name with this prefix, it is treated as unsigned. */ public String allowedUnsignedAttributePrefix() { return this.allowedUnsignedAttributePrefix; } /** * @return An ID for the algorithm suite to use during encryption and decryption. */ public DBEAlgorithmSuiteId algorithmSuiteId() { return this.algorithmSuiteId; } /** * @return The Keyring that should be used to wrap and unwrap data keys. If specified a Default Cryptographic Materials Manager with this Keyring is used to obtain materials for encryption and decryption. Either a Keyring or a Cryptographic Materials Manager must be specified. */ public IKeyring keyring() { return this.keyring; } /** * @return The Cryptographic Materials Manager that is used to obtain materials for encryption and decryption. Either a Keyring or a Cryptographic Materials Manager must be specified. */ public ICryptographicMaterialsManager cmm() { return this.cmm; } /** * @return A configuration that override encryption and/or decryption to instead perform legacy encryption and/or decryption. Used as part of migration from version 2.x to version 3.x. */ public LegacyOverride legacyOverride() { return this.legacyOverride; } /** * @return A configuration that override encryption and/or decryption to instead passthrough and write and/or read plaintext. Used to update plaintext tables to fully use client-side encryption. */ public PlaintextOverride plaintextOverride() { return this.plaintextOverride; } public Builder toBuilder() { return new BuilderImpl(this); } public static Builder builder() { return new BuilderImpl(); } public interface Builder { /** * @param logicalTableName The logical table name for this table. This is the name that is cryptographically bound with your data. This can be the same as the actual DynamoDB table name. It's purpose is to be distinct from the DynamoDB table name so that the data may still be authenticated if being read from different (but logically similar) tables, such as a backup table. */ Builder logicalTableName(String logicalTableName); /** * @return The logical table name for this table. This is the name that is cryptographically bound with your data. This can be the same as the actual DynamoDB table name. It's purpose is to be distinct from the DynamoDB table name so that the data may still be authenticated if being read from different (but logically similar) tables, such as a backup table. */ String logicalTableName(); /** * @param partitionKeyName The name of the partition key on the table this item will be written to or was read from. */ Builder partitionKeyName(String partitionKeyName); /** * @return The name of the partition key on the table this item will be written to or was read from. */ String partitionKeyName(); /** * @param sortKeyName If this table contains a sort key, the name of the sort key on the table this item will be written to or was read from. */ Builder sortKeyName(String sortKeyName); /** * @return If this table contains a sort key, the name of the sort key on the table this item will be written to or was read from. */ String sortKeyName(); /** * @param attributeActionsOnEncrypt A map that describes what attributes should be encrypted and/or signed on encrypt. This map must contain all attributes that might be encountered during encryption. */ Builder attributeActionsOnEncrypt(Map<String, CryptoAction> attributeActionsOnEncrypt); /** * @return A map that describes what attributes should be encrypted and/or signed on encrypt. This map must contain all attributes that might be encountered during encryption. */ Map<String, CryptoAction> attributeActionsOnEncrypt(); /** * @param allowedUnsignedAttributes A list of attribute names such that, if encountered during decryption, those attributes are treated as unsigned. */ Builder allowedUnsignedAttributes(List<String> allowedUnsignedAttributes); /** * @return A list of attribute names such that, if encountered during decryption, those attributes are treated as unsigned. */ List<String> allowedUnsignedAttributes(); /** * @param allowedUnsignedAttributePrefix A prefix such that, if during decryption any attribute has a name with this prefix, it is treated as unsigned. */ Builder allowedUnsignedAttributePrefix(String allowedUnsignedAttributePrefix); /** * @return A prefix such that, if during decryption any attribute has a name with this prefix, it is treated as unsigned. */ String allowedUnsignedAttributePrefix(); /** * @param algorithmSuiteId An ID for the algorithm suite to use during encryption and decryption. */ Builder algorithmSuiteId(DBEAlgorithmSuiteId algorithmSuiteId); /** * @return An ID for the algorithm suite to use during encryption and decryption. */ DBEAlgorithmSuiteId algorithmSuiteId(); /** * @param keyring The Keyring that should be used to wrap and unwrap data keys. If specified a Default Cryptographic Materials Manager with this Keyring is used to obtain materials for encryption and decryption. Either a Keyring or a Cryptographic Materials Manager must be specified. */ Builder keyring(IKeyring keyring); /** * @return The Keyring that should be used to wrap and unwrap data keys. If specified a Default Cryptographic Materials Manager with this Keyring is used to obtain materials for encryption and decryption. Either a Keyring or a Cryptographic Materials Manager must be specified. */ IKeyring keyring(); /** * @param cmm The Cryptographic Materials Manager that is used to obtain materials for encryption and decryption. Either a Keyring or a Cryptographic Materials Manager must be specified. */ Builder cmm(ICryptographicMaterialsManager cmm); /** * @return The Cryptographic Materials Manager that is used to obtain materials for encryption and decryption. Either a Keyring or a Cryptographic Materials Manager must be specified. */ ICryptographicMaterialsManager cmm(); /** * @param legacyOverride A configuration that override encryption and/or decryption to instead perform legacy encryption and/or decryption. Used as part of migration from version 2.x to version 3.x. */ Builder legacyOverride(LegacyOverride legacyOverride); /** * @return A configuration that override encryption and/or decryption to instead perform legacy encryption and/or decryption. Used as part of migration from version 2.x to version 3.x. */ LegacyOverride legacyOverride(); /** * @param plaintextOverride A configuration that override encryption and/or decryption to instead passthrough and write and/or read plaintext. Used to update plaintext tables to fully use client-side encryption. */ Builder plaintextOverride(PlaintextOverride plaintextOverride); /** * @return A configuration that override encryption and/or decryption to instead passthrough and write and/or read plaintext. Used to update plaintext tables to fully use client-side encryption. */ PlaintextOverride plaintextOverride(); DynamoDbItemEncryptorConfig build(); } static class BuilderImpl implements Builder { protected String logicalTableName; protected String partitionKeyName; protected String sortKeyName; protected Map<String, CryptoAction> attributeActionsOnEncrypt; protected List<String> allowedUnsignedAttributes; protected String allowedUnsignedAttributePrefix; protected DBEAlgorithmSuiteId algorithmSuiteId; protected IKeyring keyring; protected ICryptographicMaterialsManager cmm; protected LegacyOverride legacyOverride; protected PlaintextOverride plaintextOverride; protected BuilderImpl() { } protected BuilderImpl(DynamoDbItemEncryptorConfig model) { this.logicalTableName = model.logicalTableName(); this.partitionKeyName = model.partitionKeyName(); this.sortKeyName = model.sortKeyName(); this.attributeActionsOnEncrypt = model.attributeActionsOnEncrypt(); this.allowedUnsignedAttributes = model.allowedUnsignedAttributes(); this.allowedUnsignedAttributePrefix = model.allowedUnsignedAttributePrefix(); this.algorithmSuiteId = model.algorithmSuiteId(); this.keyring = model.keyring(); this.cmm = model.cmm(); this.legacyOverride = model.legacyOverride(); this.plaintextOverride = model.plaintextOverride(); } public Builder logicalTableName(String logicalTableName) { this.logicalTableName = logicalTableName; return this; } public String logicalTableName() { return this.logicalTableName; } public Builder partitionKeyName(String partitionKeyName) { this.partitionKeyName = partitionKeyName; return this; } public String partitionKeyName() { return this.partitionKeyName; } public Builder sortKeyName(String sortKeyName) { this.sortKeyName = sortKeyName; return this; } public String sortKeyName() { return this.sortKeyName; } public Builder attributeActionsOnEncrypt(Map<String, CryptoAction> attributeActionsOnEncrypt) { this.attributeActionsOnEncrypt = attributeActionsOnEncrypt; return this; } public Map<String, CryptoAction> attributeActionsOnEncrypt() { return this.attributeActionsOnEncrypt; } 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 Builder algorithmSuiteId(DBEAlgorithmSuiteId algorithmSuiteId) { this.algorithmSuiteId = algorithmSuiteId; return this; } public DBEAlgorithmSuiteId algorithmSuiteId() { return this.algorithmSuiteId; } public Builder keyring(IKeyring keyring) { this.keyring = Keyring.wrap(keyring); return this; } public IKeyring keyring() { return this.keyring; } public Builder cmm(ICryptographicMaterialsManager cmm) { this.cmm = CryptographicMaterialsManager.wrap(cmm); return this; } public ICryptographicMaterialsManager 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 DynamoDbItemEncryptorConfig build() { if (Objects.isNull(this.logicalTableName())) { throw new IllegalArgumentException("Missing value for required field `logicalTableName`"); } if (Objects.isNull(this.partitionKeyName())) { throw new IllegalArgumentException("Missing value for required field `partitionKeyName`"); } if (Objects.nonNull(this.partitionKeyName()) && this.partitionKeyName().length() < 1) { throw new IllegalArgumentException("The size of `partitionKeyName` must be greater than or equal to 1"); } if (Objects.nonNull(this.partitionKeyName()) && this.partitionKeyName().length() > 255) { throw new IllegalArgumentException("The size of `partitionKeyName` must be less than or equal to 255"); } if (Objects.nonNull(this.sortKeyName()) && this.sortKeyName().length() < 1) { throw new IllegalArgumentException("The size of `sortKeyName` must be greater than or equal to 1"); } if (Objects.nonNull(this.sortKeyName()) && this.sortKeyName().length() > 255) { throw new IllegalArgumentException("The size of `sortKeyName` must be less than or equal to 255"); } if (Objects.isNull(this.attributeActionsOnEncrypt())) { throw new IllegalArgumentException("Missing value for required field `attributeActionsOnEncrypt`"); } if (Objects.nonNull(this.allowedUnsignedAttributes()) && this.allowedUnsignedAttributes().size() < 1) { throw new IllegalArgumentException("The size of `allowedUnsignedAttributes` must be greater than or equal to 1"); } return new DynamoDbItemEncryptorConfig(this); } } }
5,216
0
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/dbencryptionsdk/dynamodb/itemencryptor
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/dbencryptionsdk/dynamodb/itemencryptor/model/EncryptItemOutput.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.dynamodb.itemencryptor.model; import java.util.Map; import java.util.Objects; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; /** * Outputs for encrypting a DynamoDB Item. */ public class EncryptItemOutput { /** * The encrypted DynamoDB item. */ private final Map<String, AttributeValue> encryptedItem; /** * A parsed version of the header written with the encrypted DynamoDB item. */ private final ParsedHeader parsedHeader; protected EncryptItemOutput(BuilderImpl builder) { this.encryptedItem = builder.encryptedItem(); this.parsedHeader = builder.parsedHeader(); } /** * @return The encrypted DynamoDB item. */ public Map<String, AttributeValue> encryptedItem() { return this.encryptedItem; } /** * @return A parsed version of the header written with the encrypted DynamoDB item. */ public ParsedHeader parsedHeader() { return this.parsedHeader; } public Builder toBuilder() { return new BuilderImpl(this); } public static Builder builder() { return new BuilderImpl(); } public interface Builder { /** * @param encryptedItem The encrypted DynamoDB item. */ Builder encryptedItem(Map<String, AttributeValue> encryptedItem); /** * @return The encrypted DynamoDB item. */ Map<String, AttributeValue> encryptedItem(); /** * @param parsedHeader A parsed version of the header written with the encrypted DynamoDB item. */ Builder parsedHeader(ParsedHeader parsedHeader); /** * @return A parsed version of the header written with the encrypted DynamoDB item. */ ParsedHeader parsedHeader(); EncryptItemOutput build(); } static class BuilderImpl implements Builder { protected Map<String, AttributeValue> encryptedItem; protected ParsedHeader parsedHeader; protected BuilderImpl() { } protected BuilderImpl(EncryptItemOutput model) { this.encryptedItem = model.encryptedItem(); this.parsedHeader = model.parsedHeader(); } public Builder encryptedItem(Map<String, AttributeValue> encryptedItem) { this.encryptedItem = encryptedItem; return this; } public Map<String, AttributeValue> encryptedItem() { return this.encryptedItem; } public Builder parsedHeader(ParsedHeader parsedHeader) { this.parsedHeader = parsedHeader; return this; } public ParsedHeader parsedHeader() { return this.parsedHeader; } public EncryptItemOutput build() { if (Objects.isNull(this.encryptedItem())) { throw new IllegalArgumentException("Missing value for required field `encryptedItem`"); } return new EncryptItemOutput(this); } } }
5,217
0
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/dbencryptionsdk/dynamodb/itemencryptor
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/dbencryptionsdk/dynamodb/itemencryptor/model/DecryptItemOutput.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.dynamodb.itemencryptor.model; import java.util.Map; import java.util.Objects; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; /** * Outputs for decrypting a DynamoDB Item. */ public class DecryptItemOutput { /** * The decrypted DynamoDB item. */ private final Map<String, AttributeValue> plaintextItem; /** * A parsed version of the header on the encrypted DynamoDB item. */ private final ParsedHeader parsedHeader; protected DecryptItemOutput(BuilderImpl builder) { this.plaintextItem = builder.plaintextItem(); this.parsedHeader = builder.parsedHeader(); } /** * @return The decrypted DynamoDB item. */ public Map<String, AttributeValue> plaintextItem() { return this.plaintextItem; } /** * @return A parsed version of the header on the encrypted DynamoDB item. */ public ParsedHeader parsedHeader() { return this.parsedHeader; } public Builder toBuilder() { return new BuilderImpl(this); } public static Builder builder() { return new BuilderImpl(); } public interface Builder { /** * @param plaintextItem The decrypted DynamoDB item. */ Builder plaintextItem(Map<String, AttributeValue> plaintextItem); /** * @return The decrypted DynamoDB item. */ Map<String, AttributeValue> plaintextItem(); /** * @param parsedHeader A parsed version of the header on the encrypted DynamoDB item. */ Builder parsedHeader(ParsedHeader parsedHeader); /** * @return A parsed version of the header on the encrypted DynamoDB item. */ ParsedHeader parsedHeader(); DecryptItemOutput build(); } static class BuilderImpl implements Builder { protected Map<String, AttributeValue> plaintextItem; protected ParsedHeader parsedHeader; protected BuilderImpl() { } protected BuilderImpl(DecryptItemOutput model) { this.plaintextItem = model.plaintextItem(); this.parsedHeader = model.parsedHeader(); } public Builder plaintextItem(Map<String, AttributeValue> plaintextItem) { this.plaintextItem = plaintextItem; return this; } public Map<String, AttributeValue> plaintextItem() { return this.plaintextItem; } public Builder parsedHeader(ParsedHeader parsedHeader) { this.parsedHeader = parsedHeader; return this; } public ParsedHeader parsedHeader() { return this.parsedHeader; } public DecryptItemOutput build() { if (Objects.isNull(this.plaintextItem())) { throw new IllegalArgumentException("Missing value for required field `plaintextItem`"); } return new DecryptItemOutput(this); } } }
5,218
0
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/dbencryptionsdk/dynamodb/itemencryptor
Create_ds/aws-database-encryption-sdk-dynamodb-java/DynamoDbEncryption/runtimes/java/src/main/smithy-generated/software/amazon/cryptography/dbencryptionsdk/dynamodb/itemencryptor/model/CollectionOfErrors.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.dynamodb.itemencryptor.model; import java.util.List; public class CollectionOfErrors extends RuntimeException { /** * The list of Exceptions encountered. */ private final List<RuntimeException> list; protected CollectionOfErrors(BuilderImpl builder) { super(messageFromBuilder(builder), builder.cause()); this.list = builder.list(); } 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 list of Exceptions encountered. */ public List<RuntimeException> list() { return this.list; } 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 list The list of Exceptions encountered. */ Builder list(List<RuntimeException> list); /** * @return The list of Exceptions encountered. */ List<RuntimeException> list(); CollectionOfErrors build(); } static class BuilderImpl implements Builder { protected String message; protected Throwable cause; protected List<RuntimeException> list; protected BuilderImpl() { } protected BuilderImpl(CollectionOfErrors model) { this.cause = model.getCause(); this.message = model.getMessage(); this.list = model.list(); } 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 list(List<RuntimeException> list) { this.list = list; return this; } public List<RuntimeException> list() { return this.list; } public CollectionOfErrors build() { return new CollectionOfErrors(this); } } }
5,219
0
Create_ds/aws-database-encryption-sdk-dynamodb-java/Examples/runtimes/java/DynamoDbEncryption/src/test/java/software/amazon/cryptography
Create_ds/aws-database-encryption-sdk-dynamodb-java/Examples/runtimes/java/DynamoDbEncryption/src/test/java/software/amazon/cryptography/examples/TestCreateKeyStoreTableExample.java
package software.amazon.cryptography.examples; import org.testng.annotations.Test; public class TestCreateKeyStoreTableExample { @Test public void TestCreateKeyStoreTableExample() { CreateKeyStoreTableExample.KeyStoreCreateTable( TestUtils.TEST_KEYSTORE_NAME, TestUtils.TEST_LOGICAL_KEYSTORE_NAME, TestUtils.TEST_KEYSTORE_KMS_KEY_ID); } }
5,220
0
Create_ds/aws-database-encryption-sdk-dynamodb-java/Examples/runtimes/java/DynamoDbEncryption/src/test/java/software/amazon/cryptography
Create_ds/aws-database-encryption-sdk-dynamodb-java/Examples/runtimes/java/DynamoDbEncryption/src/test/java/software/amazon/cryptography/examples/TestUtils.java
package software.amazon.cryptography.examples; public class TestUtils { public static final String TEST_KEYSTORE_NAME = "KeyStoreDdbTable"; public static final String TEST_LOGICAL_KEYSTORE_NAME = "KeyStoreDdbTable"; public static final String TEST_KEYSTORE_KMS_KEY_ID = "arn:aws:kms:us-west-2:370957321024:key/9d989aa2-2f9c-438c-a745-cc57d3ad0126"; public static final String TEST_AWS_ACCOUNT_ID = "658956600833"; public static final String TEST_AWS_REGION = "us-west-2"; // These are public KMS Keys that MUST only be used for testing, and MUST NOT be used for any production data public static final String TEST_KMS_KEY_ID = "arn:aws:kms:us-west-2:658956600833:key/b3537ef1-d8dc-4780-9f5a-55776cbb2f7f"; public static final String TEST_MRK_KEY_ID = "arn:aws:kms:us-west-2:658956600833:key/mrk-80bd8ecdcd4342aebd84b7dc9da498a7"; public static final String TEST_KMS_RSA_KEY_ID = "arn:aws:kms:us-west-2:658956600833:key/8b432da4-dde4-4bc3-a794-c7d68cbab5a6"; public static final String TEST_MRK_REPLICA_KEY_ID_US_EAST_1 = "arn:aws:kms:us-east-1:658956600833:key/mrk-80bd8ecdcd4342aebd84b7dc9da498a7"; public static final String TEST_MRK_REPLICA_KEY_ID_EU_WEST_1 = "arn:aws:kms:eu-west-1:658956600833:key/mrk-80bd8ecdcd4342aebd84b7dc9da498a7"; // Our tests require access to DDB Table with this name public static final String TEST_DDB_TABLE_NAME = "DynamoDbEncryptionInterceptorTestTable"; }
5,221
0
Create_ds/aws-database-encryption-sdk-dynamodb-java/Examples/runtimes/java/DynamoDbEncryption/src/test/java/software/amazon/cryptography
Create_ds/aws-database-encryption-sdk-dynamodb-java/Examples/runtimes/java/DynamoDbEncryption/src/test/java/software/amazon/cryptography/examples/TestBasicPutGetExample.java
package software.amazon.cryptography.examples; import org.testng.annotations.Test; public class TestBasicPutGetExample { @Test public void TestPutGet() { BasicPutGetExample.PutItemGetItem(TestUtils.TEST_KMS_KEY_ID, TestUtils.TEST_DDB_TABLE_NAME); } }
5,222
0
Create_ds/aws-database-encryption-sdk-dynamodb-java/Examples/runtimes/java/DynamoDbEncryption/src/test/java/software/amazon/cryptography
Create_ds/aws-database-encryption-sdk-dynamodb-java/Examples/runtimes/java/DynamoDbEncryption/src/test/java/software/amazon/cryptography/examples/TestCreateKeyStoreKeyExample.java
package software.amazon.cryptography.examples; import org.testng.annotations.Test; import static org.testng.Assert.assertNotNull; public class TestCreateKeyStoreKeyExample { @Test public void TestCreateKeyStoreKeyExample() { String keyId = CreateKeyStoreKeyExample.KeyStoreCreateKey( TestUtils.TEST_KEYSTORE_NAME, TestUtils.TEST_LOGICAL_KEYSTORE_NAME, TestUtils.TEST_KEYSTORE_KMS_KEY_ID); assertNotNull(keyId); } }
5,223
0
Create_ds/aws-database-encryption-sdk-dynamodb-java/Examples/runtimes/java/DynamoDbEncryption/src/test/java/software/amazon/cryptography/examples
Create_ds/aws-database-encryption-sdk-dynamodb-java/Examples/runtimes/java/DynamoDbEncryption/src/test/java/software/amazon/cryptography/examples/keyring/TestMrkDiscoveryMultiKeyringExample.java
package software.amazon.cryptography.examples.keyring; import java.util.Collections; import java.util.List; import org.testng.annotations.Test; import software.amazon.cryptography.examples.TestUtils; public class TestMrkDiscoveryMultiKeyringExample { @Test public void TestMrkDiscoveryMultiKeyringExample() { List<String> accounts = Collections.singletonList(TestUtils.TEST_AWS_ACCOUNT_ID); List<String> regions = Collections.singletonList(TestUtils.TEST_AWS_REGION); MrkDiscoveryMultiKeyringExample.MultiMrkDiscoveryKeyringGetItemPutItem( TestUtils.TEST_DDB_TABLE_NAME, TestUtils.TEST_MRK_KEY_ID, accounts, regions); } }
5,224
0
Create_ds/aws-database-encryption-sdk-dynamodb-java/Examples/runtimes/java/DynamoDbEncryption/src/test/java/software/amazon/cryptography/examples
Create_ds/aws-database-encryption-sdk-dynamodb-java/Examples/runtimes/java/DynamoDbEncryption/src/test/java/software/amazon/cryptography/examples/keyring/TestMrkMultiKeyringExample.java
package software.amazon.cryptography.examples.keyring; import org.testng.annotations.Test; import software.amazon.cryptography.examples.TestUtils; public class TestMrkMultiKeyringExample { @Test public void TestMrkMultiKeyringExample() { MultiMrkKeyringExample.MultiMrkKeyringGetItemPutItem( TestUtils.TEST_DDB_TABLE_NAME, TestUtils.TEST_MRK_KEY_ID, TestUtils.TEST_KMS_KEY_ID, TestUtils.TEST_MRK_REPLICA_KEY_ID_US_EAST_1); } }
5,225
0
Create_ds/aws-database-encryption-sdk-dynamodb-java/Examples/runtimes/java/DynamoDbEncryption/src/test/java/software/amazon/cryptography/examples
Create_ds/aws-database-encryption-sdk-dynamodb-java/Examples/runtimes/java/DynamoDbEncryption/src/test/java/software/amazon/cryptography/examples/keyring/TestRawAesKeyringExample.java
package software.amazon.cryptography.examples.keyring; import java.nio.ByteBuffer; import org.testng.annotations.Test; import software.amazon.cryptography.examples.TestUtils; public class TestRawAesKeyringExample { @Test public void TestRawAesKeyringExample() { // Generate a new AES key ByteBuffer aesKeyBytes = RawAesKeyringExample.generateAesKeyBytes(); RawAesKeyringExample.RawAesKeyringGetItemPutItem( TestUtils.TEST_DDB_TABLE_NAME, aesKeyBytes); } }
5,226
0
Create_ds/aws-database-encryption-sdk-dynamodb-java/Examples/runtimes/java/DynamoDbEncryption/src/test/java/software/amazon/cryptography/examples
Create_ds/aws-database-encryption-sdk-dynamodb-java/Examples/runtimes/java/DynamoDbEncryption/src/test/java/software/amazon/cryptography/examples/keyring/TestRawRsaKeyringExample.java
package software.amazon.cryptography.examples.keyring; import org.testng.annotations.Test; import software.amazon.cryptography.examples.TestUtils; public class TestRawRsaKeyringExample { @Test public void TestRawRsaKeyringExample() { // You may provide your own RSA key pair in the files located at // - EXAMPLE_RSA_PRIVATE_KEY_FILENAME // - EXAMPLE_RSA_PUBLIC_KEY_FILENAME // If these files are not present, this will generate a pair for you if (RawRsaKeyringExample.shouldGenerateNewRsaKeyPair()) { RawRsaKeyringExample.generateRsaKeyPair(); } RawRsaKeyringExample.RawRsaKeyringGetItemPutItem( TestUtils.TEST_DDB_TABLE_NAME); } }
5,227
0
Create_ds/aws-database-encryption-sdk-dynamodb-java/Examples/runtimes/java/DynamoDbEncryption/src/test/java/software/amazon/cryptography/examples
Create_ds/aws-database-encryption-sdk-dynamodb-java/Examples/runtimes/java/DynamoDbEncryption/src/test/java/software/amazon/cryptography/examples/keyring/TestMultiKeyringExample.java
package software.amazon.cryptography.examples.keyring; import java.nio.ByteBuffer; import org.testng.annotations.Test; import software.amazon.cryptography.examples.TestUtils; public class TestMultiKeyringExample { @Test public void TestMultiKeyringExample() { // Generate a new AES key ByteBuffer aesKeyBytes = RawAesKeyringExample.generateAesKeyBytes(); MultiKeyringExample.MultiKeyringGetItemPutItem( TestUtils.TEST_DDB_TABLE_NAME, TestUtils.TEST_KMS_KEY_ID, aesKeyBytes); } }
5,228
0
Create_ds/aws-database-encryption-sdk-dynamodb-java/Examples/runtimes/java/DynamoDbEncryption/src/test/java/software/amazon/cryptography/examples
Create_ds/aws-database-encryption-sdk-dynamodb-java/Examples/runtimes/java/DynamoDbEncryption/src/test/java/software/amazon/cryptography/examples/keyring/TestHierarchicalKeyringExample.java
package software.amazon.cryptography.examples.keyring; import org.testng.annotations.Test; import software.amazon.cryptography.examples.CreateKeyStoreKeyExample; import software.amazon.cryptography.examples.TestUtils; public class TestHierarchicalKeyringExample { @Test public void TestHierarchicalKeyringExample() throws InterruptedException { // Create new branch keys for test String keyId1 = CreateKeyStoreKeyExample.KeyStoreCreateKey( TestUtils.TEST_KEYSTORE_NAME, TestUtils.TEST_LOGICAL_KEYSTORE_NAME, TestUtils.TEST_KEYSTORE_KMS_KEY_ID); String keyId2 = CreateKeyStoreKeyExample.KeyStoreCreateKey( TestUtils.TEST_KEYSTORE_NAME, TestUtils.TEST_LOGICAL_KEYSTORE_NAME, TestUtils.TEST_KEYSTORE_KMS_KEY_ID); // Key creation is eventually consistent, so wait 5 seconds to decrease the likelihood // our test fails due to eventual consistency issues. Thread.sleep(5000); HierarchicalKeyringExample.HierarchicalKeyringGetItemPutItem( TestUtils.TEST_DDB_TABLE_NAME, keyId1, keyId2, TestUtils.TEST_KEYSTORE_NAME, TestUtils.TEST_LOGICAL_KEYSTORE_NAME, TestUtils.TEST_KEYSTORE_KMS_KEY_ID); } }
5,229
0
Create_ds/aws-database-encryption-sdk-dynamodb-java/Examples/runtimes/java/DynamoDbEncryption/src/test/java/software/amazon/cryptography/examples
Create_ds/aws-database-encryption-sdk-dynamodb-java/Examples/runtimes/java/DynamoDbEncryption/src/test/java/software/amazon/cryptography/examples/keyring/TestKmsRsaKeyringExample.java
package software.amazon.cryptography.examples.keyring; import software.amazon.cryptography.examples.TestUtils; import static software.amazon.cryptography.examples.keyring.KmsRsaKeyringExample.shouldGetNewPublicKey; import static software.amazon.cryptography.examples.keyring.KmsRsaKeyringExample.writePublicKeyPemForRsaKey; import org.testng.annotations.Test; public class TestKmsRsaKeyringExample { @Test public void TestKmsRsaKeyringExample() { // You may provide your own RSA public key at EXAMPLE_RSA_PUBLIC_KEY_FILENAME. // This must be the public key for the RSA key represented at rsaKeyArn. // If this file is not present, this will write a UTF-8 encoded PEM file for you. if (shouldGetNewPublicKey()) { writePublicKeyPemForRsaKey(TestUtils.TEST_KMS_RSA_KEY_ID); } software.amazon.cryptography.examples.keyring.KmsRsaKeyringExample.KmsRsaKeyringGetItemPutItem( TestUtils.TEST_DDB_TABLE_NAME, TestUtils.TEST_KMS_RSA_KEY_ID); } }
5,230
0
Create_ds/aws-database-encryption-sdk-dynamodb-java/Examples/runtimes/java/DynamoDbEncryption/src/test/java/software/amazon/cryptography/examples
Create_ds/aws-database-encryption-sdk-dynamodb-java/Examples/runtimes/java/DynamoDbEncryption/src/test/java/software/amazon/cryptography/examples/enhanced/TestEnhancedPutGetExample.java
package software.amazon.cryptography.examples.enhanced; import org.testng.annotations.Test; import software.amazon.cryptography.examples.TestUtils; public class TestEnhancedPutGetExample { @Test public void TestEnhancedPutGet() { EnhancedPutGetExample.PutItemGetItem(TestUtils.TEST_KMS_KEY_ID, TestUtils.TEST_DDB_TABLE_NAME); } @Test public void TestLombokPutGet() { LombokPutGetExample.PutItemGetItem(TestUtils.TEST_KMS_KEY_ID, TestUtils.TEST_DDB_TABLE_NAME); } @Test public void TestTableSchemaBuilderPutGet() { TableSchemaBuilderPutGetExample.PutItemGetItem(TestUtils.TEST_KMS_KEY_ID, TestUtils.TEST_DDB_TABLE_NAME); } }
5,231
0
Create_ds/aws-database-encryption-sdk-dynamodb-java/Examples/runtimes/java/DynamoDbEncryption/src/test/java/software/amazon/cryptography/examples
Create_ds/aws-database-encryption-sdk-dynamodb-java/Examples/runtimes/java/DynamoDbEncryption/src/test/java/software/amazon/cryptography/examples/itemencryptor/TestItemEncryptDecryptExample.java
package software.amazon.cryptography.examples.itemencryptor; import org.testng.annotations.Test; import software.amazon.cryptography.examples.TestUtils; public class TestItemEncryptDecryptExample { @Test public void TestItemEncryptDecrypt() { ItemEncryptDecryptExample.PutItemGetItem(TestUtils.TEST_KMS_KEY_ID, TestUtils.TEST_DDB_TABLE_NAME); } }
5,232
0
Create_ds/aws-database-encryption-sdk-dynamodb-java/Examples/runtimes/java/DynamoDbEncryption/src/test/java/software/amazon/cryptography/examples
Create_ds/aws-database-encryption-sdk-dynamodb-java/Examples/runtimes/java/DynamoDbEncryption/src/test/java/software/amazon/cryptography/examples/clientsupplier/TestClientSupplierExample.java
package software.amazon.cryptography.examples.clientsupplier; import java.util.Collections; import java.util.List; import org.testng.annotations.Test; import software.amazon.awssdk.regions.Region; import software.amazon.cryptography.examples.TestUtils; public class TestClientSupplierExample { @Test public void TestClientSupplierExample() { List<String> accounts = Collections.singletonList(TestUtils.TEST_AWS_ACCOUNT_ID); List<String> regions = Collections.singletonList(Region.EU_WEST_1.id()); ClientSupplierExample.ClientSupplierPutItemGetItem( TestUtils.TEST_DDB_TABLE_NAME, // Note that we pass in an MRK in us-east-1... TestUtils.TEST_MRK_REPLICA_KEY_ID_US_EAST_1, accounts, // ...and access its replica in eu-west-1 regions); } }
5,233
0
Create_ds/aws-database-encryption-sdk-dynamodb-java/Examples/runtimes/java/DynamoDbEncryption/src/test/java/software/amazon/cryptography/examples
Create_ds/aws-database-encryption-sdk-dynamodb-java/Examples/runtimes/java/DynamoDbEncryption/src/test/java/software/amazon/cryptography/examples/searchableencryption/TestCompoundBeaconSearchableEncryptionExample.java
package software.amazon.cryptography.examples.searchableencryption; import org.testng.annotations.Test; import software.amazon.cryptography.examples.CreateKeyStoreKeyExample; public class TestCompoundBeaconSearchableEncryptionExample { @Test public void TestCompoundItemEncryptDecrypt() throws InterruptedException { // Create new branch key for test String keyId = CreateKeyStoreKeyExample.KeyStoreCreateKey( SearchableEncryptionTestUtils.TEST_BRANCH_KEYSTORE_DDB_TABLE_NAME, SearchableEncryptionTestUtils.TEST_LOGICAL_KEYSTORE_NAME, SearchableEncryptionTestUtils.TEST_BRANCH_KEY_WRAPPING_KMS_KEY_ARN); // Key creation is eventually consistent, so wait 5 seconds to decrease the likelihood // our test fails due to eventual consistency issues. Thread.sleep(5000); CompoundBeaconSearchableEncryptionExample.PutItemQueryItemWithCompoundBeacon( SearchableEncryptionTestUtils.UNIT_INSPECTION_TEST_DDB_TABLE_NAME, keyId, SearchableEncryptionTestUtils.TEST_BRANCH_KEY_WRAPPING_KMS_KEY_ARN, SearchableEncryptionTestUtils.TEST_BRANCH_KEYSTORE_DDB_TABLE_NAME); } }
5,234
0
Create_ds/aws-database-encryption-sdk-dynamodb-java/Examples/runtimes/java/DynamoDbEncryption/src/test/java/software/amazon/cryptography/examples
Create_ds/aws-database-encryption-sdk-dynamodb-java/Examples/runtimes/java/DynamoDbEncryption/src/test/java/software/amazon/cryptography/examples/searchableencryption/TestVirtualBeaconSearchableEncryptionExample.java
package software.amazon.cryptography.examples.searchableencryption; import org.testng.annotations.Test; import software.amazon.cryptography.examples.CreateKeyStoreKeyExample; public class TestVirtualBeaconSearchableEncryptionExample { @Test public void TestVirtualBeaconExample() throws InterruptedException { // Create new branch key for test String keyId = CreateKeyStoreKeyExample.KeyStoreCreateKey( SearchableEncryptionTestUtils.TEST_BRANCH_KEYSTORE_DDB_TABLE_NAME, SearchableEncryptionTestUtils.TEST_LOGICAL_KEYSTORE_NAME, SearchableEncryptionTestUtils.TEST_BRANCH_KEY_WRAPPING_KMS_KEY_ARN); // Key creation is eventually consistent, so wait 5 seconds to decrease the likelihood // our test fails due to eventual consistency issues. Thread.sleep(5000); VirtualBeaconSearchableEncryptionExample.PutItemQueryItemWithVirtualBeacon( SearchableEncryptionTestUtils.SIMPLE_BEACON_TEST_DDB_TABLE_NAME, keyId, SearchableEncryptionTestUtils.TEST_BRANCH_KEY_WRAPPING_KMS_KEY_ARN, SearchableEncryptionTestUtils.TEST_BRANCH_KEYSTORE_DDB_TABLE_NAME); } }
5,235
0
Create_ds/aws-database-encryption-sdk-dynamodb-java/Examples/runtimes/java/DynamoDbEncryption/src/test/java/software/amazon/cryptography/examples
Create_ds/aws-database-encryption-sdk-dynamodb-java/Examples/runtimes/java/DynamoDbEncryption/src/test/java/software/amazon/cryptography/examples/searchableencryption/TestBasicSearchableEncryptionExample.java
package software.amazon.cryptography.examples.searchableencryption; import org.testng.annotations.Test; import software.amazon.cryptography.examples.CreateKeyStoreKeyExample; public class TestBasicSearchableEncryptionExample { @Test public void TestBasicExample() throws InterruptedException { // Create new branch key for test String keyId = CreateKeyStoreKeyExample.KeyStoreCreateKey( SearchableEncryptionTestUtils.TEST_BRANCH_KEYSTORE_DDB_TABLE_NAME, SearchableEncryptionTestUtils.TEST_LOGICAL_KEYSTORE_NAME, SearchableEncryptionTestUtils.TEST_BRANCH_KEY_WRAPPING_KMS_KEY_ARN); // Key creation is eventually consistent, so wait 5 seconds to decrease the likelihood // our test fails due to eventual consistency issues. Thread.sleep(5000); BasicSearchableEncryptionExample.PutItemQueryItemWithBeacon( SearchableEncryptionTestUtils.UNIT_INSPECTION_TEST_DDB_TABLE_NAME, keyId, SearchableEncryptionTestUtils.TEST_BRANCH_KEY_WRAPPING_KMS_KEY_ARN, SearchableEncryptionTestUtils.TEST_BRANCH_KEYSTORE_DDB_TABLE_NAME); } }
5,236
0
Create_ds/aws-database-encryption-sdk-dynamodb-java/Examples/runtimes/java/DynamoDbEncryption/src/test/java/software/amazon/cryptography/examples
Create_ds/aws-database-encryption-sdk-dynamodb-java/Examples/runtimes/java/DynamoDbEncryption/src/test/java/software/amazon/cryptography/examples/searchableencryption/TestBeaconStylesSearchableEncryptionExample.java
package software.amazon.cryptography.examples.searchableencryption; import org.testng.annotations.Test; import software.amazon.cryptography.examples.CreateKeyStoreKeyExample; public class TestBeaconStylesSearchableEncryptionExample { @Test public void TestCompoundItemEncryptDecrypt() throws InterruptedException { // Create new branch key for test String keyId = CreateKeyStoreKeyExample.KeyStoreCreateKey( SearchableEncryptionTestUtils.TEST_BRANCH_KEYSTORE_DDB_TABLE_NAME, SearchableEncryptionTestUtils.TEST_LOGICAL_KEYSTORE_NAME, SearchableEncryptionTestUtils.TEST_BRANCH_KEY_WRAPPING_KMS_KEY_ARN); // Key creation is eventually consistent, so wait 5 seconds to decrease the likelihood // our test fails due to eventual consistency issues. Thread.sleep(5000); BeaconStylesSearchableEncryptionExample.PutItemQueryItemWithBeaconStyles( SearchableEncryptionTestUtils.UNIT_INSPECTION_TEST_DDB_TABLE_NAME, keyId, SearchableEncryptionTestUtils.TEST_BRANCH_KEY_WRAPPING_KMS_KEY_ARN, SearchableEncryptionTestUtils.TEST_BRANCH_KEYSTORE_DDB_TABLE_NAME); } }
5,237
0
Create_ds/aws-database-encryption-sdk-dynamodb-java/Examples/runtimes/java/DynamoDbEncryption/src/test/java/software/amazon/cryptography/examples
Create_ds/aws-database-encryption-sdk-dynamodb-java/Examples/runtimes/java/DynamoDbEncryption/src/test/java/software/amazon/cryptography/examples/searchableencryption/SearchableEncryptionTestUtils.java
package software.amazon.cryptography.examples.searchableencryption; public class SearchableEncryptionTestUtils { // Our tests require access to DDB Tables with these name public static final String SIMPLE_BEACON_TEST_DDB_TABLE_NAME = "SimpleBeaconTestTable"; public static final String UNIT_INSPECTION_TEST_DDB_TABLE_NAME = "UnitInspectionTestTable"; // The branch key must have been created using this KMS key // Note: This is a public resource that anyone can access. // This MUST NOT be used to encrypt any production data. public static final String TEST_BRANCH_KEY_WRAPPING_KMS_KEY_ARN = "arn:aws:kms:us-west-2:370957321024:key/9d989aa2-2f9c-438c-a745-cc57d3ad0126"; // Our tests require access to DDB Table with this name configured as a branch keystore public static final String TEST_BRANCH_KEYSTORE_DDB_TABLE_NAME = "KeyStoreDdbTable"; public static final String TEST_LOGICAL_KEYSTORE_NAME = "KeyStoreDdbTable"; }
5,238
0
Create_ds/aws-database-encryption-sdk-dynamodb-java/Examples/runtimes/java/DynamoDbEncryption/src/test/java/software/amazon/cryptography/examples/searchableencryption
Create_ds/aws-database-encryption-sdk-dynamodb-java/Examples/runtimes/java/DynamoDbEncryption/src/test/java/software/amazon/cryptography/examples/searchableencryption/complexexample/ComplexSearchableEncryptionTestUtils.java
package software.amazon.cryptography.examples.searchableencryption.complexexample; public class ComplexSearchableEncryptionTestUtils { // Our tests require access to DDB Table with this name public static final String TEST_DDB_TABLE_NAME = "ComplexBeaconTestTable"; }
5,239
0
Create_ds/aws-database-encryption-sdk-dynamodb-java/Examples/runtimes/java/DynamoDbEncryption/src/test/java/software/amazon/cryptography/examples/searchableencryption
Create_ds/aws-database-encryption-sdk-dynamodb-java/Examples/runtimes/java/DynamoDbEncryption/src/test/java/software/amazon/cryptography/examples/searchableencryption/complexexample/TestComplexSearchableEncryptionExample.java
package software.amazon.cryptography.examples.searchableencryption.complexexample; import org.testng.annotations.Test; import software.amazon.cryptography.examples.CreateKeyStoreKeyExample; import software.amazon.cryptography.examples.searchableencryption.SearchableEncryptionTestUtils; public class TestComplexSearchableEncryptionExample { @Test public void TestComplexExample() throws InterruptedException { // Create new branch key for test String keyId = CreateKeyStoreKeyExample.KeyStoreCreateKey( SearchableEncryptionTestUtils.TEST_BRANCH_KEYSTORE_DDB_TABLE_NAME, SearchableEncryptionTestUtils.TEST_LOGICAL_KEYSTORE_NAME, SearchableEncryptionTestUtils.TEST_BRANCH_KEY_WRAPPING_KMS_KEY_ARN); // Key creation is eventually consistent, so wait 5 seconds to decrease the likelihood // our test fails due to eventual consistency issues. Thread.sleep(5000); ComplexSearchableEncryptionExample.runExample( ComplexSearchableEncryptionTestUtils.TEST_DDB_TABLE_NAME, keyId, SearchableEncryptionTestUtils.TEST_BRANCH_KEY_WRAPPING_KMS_KEY_ARN, SearchableEncryptionTestUtils.TEST_BRANCH_KEYSTORE_DDB_TABLE_NAME); } }
5,240
0
Create_ds/aws-database-encryption-sdk-dynamodb-java/Examples/runtimes/java/DynamoDbEncryption/src/main/java/software/amazon/cryptography
Create_ds/aws-database-encryption-sdk-dynamodb-java/Examples/runtimes/java/DynamoDbEncryption/src/main/java/software/amazon/cryptography/examples/BasicPutGetExample.java
package software.amazon.cryptography.examples; import software.amazon.awssdk.core.client.config.ClientOverrideConfiguration; import software.amazon.awssdk.services.dynamodb.DynamoDbClient; import software.amazon.awssdk.services.dynamodb.model.*; import software.amazon.cryptography.dbencryptionsdk.dynamodb.model.DynamoDbTableEncryptionConfig; import software.amazon.cryptography.dbencryptionsdk.dynamodb.model.DynamoDbTablesEncryptionConfig; import software.amazon.cryptography.materialproviders.IKeyring; import software.amazon.cryptography.materialproviders.MaterialProviders; import software.amazon.cryptography.materialproviders.model.CreateAwsKmsMrkMultiKeyringInput; import software.amazon.cryptography.materialproviders.model.DBEAlgorithmSuiteId; import software.amazon.cryptography.materialproviders.model.MaterialProvidersConfig; import software.amazon.cryptography.dbencryptionsdk.structuredencryption.model.CryptoAction; import software.amazon.cryptography.dbencryptionsdk.dynamodb.DynamoDbEncryptionInterceptor; import java.util.HashMap; import java.util.Map; /* This example sets up DynamoDb Encryption for the AWS SDK client and uses the low level PutItem and GetItem DDB APIs to demonstrate putting a client-side encrypted item into DynamoDb and then retrieving and decrypting that item from DynamoDb. Running this example requires access to the DDB Table whose name is provided in CLI arguments. This table must be configured with the following primary key configuration: - Partition key is named "partition_key" with type (S) - Sort key is named "sort_key" with type (N) */ public class BasicPutGetExample { public static void PutItemGetItem(String kmsKeyId, String ddbTableName) { // 1. Create a Keyring. This Keyring will be responsible for protecting the data keys that protect your data. // For this example, we will create a AWS KMS Keyring with the AWS KMS Key we want to use. // We will use the `CreateMrkMultiKeyring` method to create this keyring, // as it will correctly handle both single region and Multi-Region KMS Keys. final MaterialProviders matProv = MaterialProviders.builder() .MaterialProvidersConfig(MaterialProvidersConfig.builder().build()) .build(); final CreateAwsKmsMrkMultiKeyringInput keyringInput = CreateAwsKmsMrkMultiKeyringInput.builder() .generator(kmsKeyId) .build(); final IKeyring kmsKeyring = matProv.CreateAwsKmsMrkMultiKeyring(keyringInput); // 2. Configure which attributes are encrypted and/or signed when writing new items. // For each attribute that may exist on the items we plan to write to our DynamoDbTable, // we must explicitly configure how they should be treated during item encryption: // - ENCRYPT_AND_SIGN: The attribute is encrypted and included in the signature // - SIGN_ONLY: The attribute not encrypted, but is still included in the signature // - DO_NOTHING: The attribute is not encrypted and not included in the signature final Map<String, CryptoAction> attributeActionsOnEncrypt = new HashMap<>(); attributeActionsOnEncrypt.put("partition_key", CryptoAction.SIGN_ONLY); // Our partition attribute must be SIGN_ONLY attributeActionsOnEncrypt.put("sort_key", CryptoAction.SIGN_ONLY); // Our sort attribute must be SIGN_ONLY attributeActionsOnEncrypt.put("attribute1", CryptoAction.ENCRYPT_AND_SIGN); attributeActionsOnEncrypt.put("attribute2", CryptoAction.SIGN_ONLY); attributeActionsOnEncrypt.put(":attribute3", CryptoAction.DO_NOTHING); // 3. Configure which attributes we expect to be included in the signature // when reading items. There are two options for configuring this: // // - (Recommended) Configure `allowedUnsignedAttributesPrefix`: // When defining your DynamoDb schema and deciding on attribute names, // choose a distinguishing prefix (such as ":") for all attributes that // you do not want to include in the signature. // This has two main benefits: // - It is easier to reason about the security and authenticity of data within your item // when all unauthenticated data is easily distinguishable by their attribute name. // - If you need to add new unauthenticated attributes in the future, // you can easily make the corresponding update to your `attributeActionsOnEncrypt` // and immediately start writing to that new attribute, without // any other configuration update needed. // Once you configure this field, it is not safe to update it. // // - Configure `allowedUnsignedAttributes`: You may also explicitly list // a set of attributes that should be considered unauthenticated when encountered // on read. Be careful if you use this configuration. Do not remove an attribute // name from this configuration, even if you are no longer writing with that attribute, // as old items may still include this attribute, and our configuration needs to know // to continue to exclude this attribute from the signature scope. // If you add new attribute names to this field, you must first deploy the update to this // field to all readers in your host fleet before deploying the update to start writing // with that new attribute. // // For this example, we have designed our DynamoDb table such that any attribute name with // the ":" prefix should be considered unauthenticated. final String unsignAttrPrefix = ":"; // 4. Create the DynamoDb Encryption configuration for the table we will be writing to. final Map<String, DynamoDbTableEncryptionConfig> tableConfigs = new HashMap<>(); final DynamoDbTableEncryptionConfig config = DynamoDbTableEncryptionConfig.builder() .logicalTableName(ddbTableName) .partitionKeyName("partition_key") .sortKeyName("sort_key") .attributeActionsOnEncrypt(attributeActionsOnEncrypt) .keyring(kmsKeyring) .allowedUnsignedAttributePrefix(unsignAttrPrefix) // Specifying an algorithm suite is not required, // but is done here to demonstrate how to do so. // We suggest using the // `ALG_AES_256_GCM_HKDF_SHA512_COMMIT_KEY_ECDSA_P384_SYMSIG_HMAC_SHA384` suite, // which includes AES-GCM with key derivation, signing, and key commitment. // This is also the default algorithm suite if one is not specified in this config. // For more information on supported algorithm suites, see: // https://docs.aws.amazon.com/database-encryption-sdk/latest/devguide/supported-algorithms.html .algorithmSuiteId( DBEAlgorithmSuiteId.ALG_AES_256_GCM_HKDF_SHA512_COMMIT_KEY_ECDSA_P384_SYMSIG_HMAC_SHA384) .build(); tableConfigs.put(ddbTableName, config); // 5. Create the DynamoDb Encryption Interceptor DynamoDbEncryptionInterceptor encryptionInterceptor = DynamoDbEncryptionInterceptor.builder() .config(DynamoDbTablesEncryptionConfig.builder() .tableEncryptionConfigs(tableConfigs) .build()) .build(); // 6. Create a new AWS SDK DynamoDb client using the DynamoDb Encryption Interceptor above final DynamoDbClient ddb = DynamoDbClient.builder() .overrideConfiguration( ClientOverrideConfiguration.builder() .addExecutionInterceptor(encryptionInterceptor) .build()) .build(); // 7. Put an item into our table using the above client. // Before the item gets sent to DynamoDb, it will be encrypted // client-side, according to our configuration. final HashMap<String, AttributeValue> item = new HashMap<>(); item.put("partition_key", AttributeValue.builder().s("BasicPutGetExample").build()); item.put("sort_key", AttributeValue.builder().n("0").build()); item.put("attribute1", AttributeValue.builder().s("encrypt and sign me!").build()); item.put("attribute2", AttributeValue.builder().s("sign me!").build()); item.put(":attribute3", AttributeValue.builder().s("ignore me!").build()); final PutItemRequest putRequest = PutItemRequest.builder() .tableName(ddbTableName) .item(item) .build(); final PutItemResponse putResponse = ddb.putItem(putRequest); // Demonstrate that PutItem succeeded assert 200 == putResponse.sdkHttpResponse().statusCode(); // 8. Get the item back from our table using the same client. // The client will decrypt the item client-side, and return // back the original item. final HashMap<String, AttributeValue> keyToGet = new HashMap<>(); keyToGet.put("partition_key", AttributeValue.builder().s("BasicPutGetExample").build()); keyToGet.put("sort_key", AttributeValue.builder().n("0").build()); final GetItemRequest getRequest = GetItemRequest.builder() .key(keyToGet) .tableName(ddbTableName) // In this example we configure a strongly consistent read // because we perform a read immediately after a write (for demonstrative purposes). // By default, reads are only eventually consistent. // Read our docs to determine which read consistency to use for your application: // https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/HowItWorks.ReadConsistency.html .consistentRead(Boolean.TRUE) .build(); final GetItemResponse getResponse = ddb.getItem(getRequest); // Demonstrate that GetItem succeeded and returned the decrypted item assert 200 == getResponse.sdkHttpResponse().statusCode(); final Map<String, AttributeValue> returnedItem = getResponse.item(); assert returnedItem.get("attribute1").s().equals("encrypt and sign me!"); } public static void main(final String[] args) { if (args.length < 2) { throw new IllegalArgumentException("To run this example, include the kmsKeyId as args[0] and ddbTableName as args[1]"); } final String kmsKeyId = args[0]; final String ddbTableName = args[1]; PutItemGetItem(kmsKeyId, ddbTableName); } }
5,241
0
Create_ds/aws-database-encryption-sdk-dynamodb-java/Examples/runtimes/java/DynamoDbEncryption/src/main/java/software/amazon/cryptography
Create_ds/aws-database-encryption-sdk-dynamodb-java/Examples/runtimes/java/DynamoDbEncryption/src/main/java/software/amazon/cryptography/examples/CreateKeyStoreKeyExample.java
package software.amazon.cryptography.examples; import software.amazon.awssdk.services.dynamodb.DynamoDbClient; import software.amazon.awssdk.services.kms.KmsClient; import software.amazon.cryptography.keystore.KeyStore; import software.amazon.cryptography.keystore.model.CreateKeyInput; import software.amazon.cryptography.keystore.model.KMSConfiguration; import software.amazon.cryptography.keystore.model.KeyStoreConfig; /* The Hierarchical Keyring Example and Searchable Encryption Examples rely on the existence of a DDB-backed key store with pre-existing branch key material or beacon key material. See the "Create KeyStore Table Example" for how to first set up the DDB Table that will back this KeyStore. This example demonstrates configuring a KeyStore and then using a helper method to create a branch key and beacon key that share the same Id, then return that Id. We will always create a new beacon key alongside a new branch key, even if you are not using searchable encryption. This key creation should occur within your control plane. */ public class CreateKeyStoreKeyExample { public static String KeyStoreCreateKey(String keyStoreTableName, String logicalKeyStoreName, String kmsKeyArn) { // 1. Configure your KeyStore resource. // This SHOULD be the same configuration that was used to create the DDB table // in the "Create KeyStore Table Example". final KeyStore keystore = KeyStore.builder().KeyStoreConfig( KeyStoreConfig.builder() .ddbClient(DynamoDbClient.create()) .ddbTableName(keyStoreTableName) .logicalKeyStoreName(logicalKeyStoreName) .kmsClient(KmsClient.create()) .kmsConfiguration(KMSConfiguration.builder() .kmsKeyArn(kmsKeyArn) .build()) .build()).build(); // 2. Create a new branch key and beacon key in our KeyStore. // Both the branch key and the beacon key will share an Id. // This creation is eventually consistent. final String branchKeyId = keystore.CreateKey(CreateKeyInput.builder().build()).branchKeyIdentifier(); return branchKeyId; } public static void main(final String[] args) { if (args.length <= 1) { throw new IllegalArgumentException("To run this example, include the keyStoreTableName, logicalKeyStoreName, and kmsKeyArn in args"); } final String keyStoreTableName = args[0]; final String logicalKeyStoreName = args[1]; final String kmsKeyArn = args[1]; KeyStoreCreateKey(keyStoreTableName, logicalKeyStoreName, kmsKeyArn); } }
5,242
0
Create_ds/aws-database-encryption-sdk-dynamodb-java/Examples/runtimes/java/DynamoDbEncryption/src/main/java/software/amazon/cryptography
Create_ds/aws-database-encryption-sdk-dynamodb-java/Examples/runtimes/java/DynamoDbEncryption/src/main/java/software/amazon/cryptography/examples/ConfigUtils.java
package software.amazon.cryptography.examples; import java.util.Objects; import software.amazon.cryptography.dbencryptionsdk.dynamodb.DynamoDbEncryptionInterceptor; import software.amazon.cryptography.dbencryptionsdk.dynamodb.itemencryptor.model.DynamoDbItemEncryptorConfig; import software.amazon.cryptography.dbencryptionsdk.dynamodb.model.DynamoDbTableEncryptionConfig; public class ConfigUtils { public static DynamoDbItemEncryptorConfig fromEncryptionInterceptor( final DynamoDbEncryptionInterceptor encryptionInterceptor, final String tableName ) { DynamoDbTableEncryptionConfig tableEncryptionConfig = encryptionInterceptor.config().tableEncryptionConfigs().get(tableName); DynamoDbItemEncryptorConfig.Builder builder = DynamoDbItemEncryptorConfig.builder(); builder.logicalTableName(tableEncryptionConfig.logicalTableName()); builder.partitionKeyName(tableEncryptionConfig.partitionKeyName()); builder.attributeActionsOnEncrypt(tableEncryptionConfig.attributeActionsOnEncrypt()); builder.algorithmSuiteId(tableEncryptionConfig.algorithmSuiteId()); if (Objects.nonNull(tableEncryptionConfig.sortKeyName())) builder.sortKeyName(tableEncryptionConfig.sortKeyName()); if (Objects.nonNull(tableEncryptionConfig.allowedUnsignedAttributes())) builder.allowedUnsignedAttributes(tableEncryptionConfig.allowedUnsignedAttributes()); if (Objects.nonNull(tableEncryptionConfig.allowedUnsignedAttributePrefix())) builder.allowedUnsignedAttributePrefix(tableEncryptionConfig.allowedUnsignedAttributePrefix()); if (Objects.nonNull(tableEncryptionConfig.keyring())) builder.keyring(tableEncryptionConfig.keyring()); if (Objects.nonNull(tableEncryptionConfig.cmm())) builder.cmm(tableEncryptionConfig.cmm()); if (Objects.nonNull(tableEncryptionConfig.legacyOverride())) builder.legacyOverride(tableEncryptionConfig.legacyOverride()); if (Objects.nonNull(tableEncryptionConfig.plaintextOverride())) builder.plaintextOverride(tableEncryptionConfig.plaintextOverride()); return builder.build(); } }
5,243
0
Create_ds/aws-database-encryption-sdk-dynamodb-java/Examples/runtimes/java/DynamoDbEncryption/src/main/java/software/amazon/cryptography
Create_ds/aws-database-encryption-sdk-dynamodb-java/Examples/runtimes/java/DynamoDbEncryption/src/main/java/software/amazon/cryptography/examples/CreateKeyStoreTableExample.java
package software.amazon.cryptography.examples; import software.amazon.awssdk.services.dynamodb.DynamoDbClient; import software.amazon.awssdk.services.kms.KmsClient; import software.amazon.cryptography.keystore.KeyStore; import software.amazon.cryptography.keystore.model.CreateKeyStoreInput; import software.amazon.cryptography.keystore.model.KMSConfiguration; import software.amazon.cryptography.keystore.model.KeyStoreConfig; /* The Hierarchical Keyring Example and Searchable Encryption Examples rely on the existence of a DDB-backed key store with pre-existing branch key material or beacon key material. This example demonstrates configuring a KeyStore and then using a helper method to create the DDB table that will be used to persist branch keys and beacons keys for this KeyStore. This table creation should occur within your control plane. This only needs to occur once. While not demonstrated in this example, you should additionally use the `VersionKey` API on the KeyStore to periodically rotate your branch key material. */ public class CreateKeyStoreTableExample { // Create KeyStore Table Example public static void KeyStoreCreateTable(String keyStoreTableName, String logicalKeyStoreName, String kmsKeyArn) { // 1. Configure your KeyStore resource. // `ddbTableName` is the name you want for the DDB table that // will back your keystore. // `kmsKeyArn` is the KMS Key that will protect your branch keys and beacon keys // when they are stored in your DDB table. final KeyStore keystore = KeyStore.builder().KeyStoreConfig( KeyStoreConfig.builder() .ddbClient(DynamoDbClient.create()) .ddbTableName(keyStoreTableName) .logicalKeyStoreName(logicalKeyStoreName) .kmsClient(KmsClient.create()) .kmsConfiguration(KMSConfiguration.builder() .kmsKeyArn(kmsKeyArn) .build()) .build()).build(); // 2. Create the DynamoDb table that will store the branch keys and beacon keys. // This checks if the correct table already exists at `ddbTableName` // by using the DescribeTable API. If no table exists, // it will create one. If a table exists, it will verify // the table's configuration and will error if the configuration is incorrect. keystore.CreateKeyStore(CreateKeyStoreInput.builder().build()); // It may take a couple minutes for the table to become ACTIVE, // at which point it is ready to store branch and beacon keys. // See the Create KeyStore Key Example for how to populate // this table. } public static void main(final String[] args) { if (args.length <= 1) { throw new IllegalArgumentException("To run this example, include the keyStoreTableName, logicalKeyStoreName, and kmsKeyArn in args"); } final String keyStoreTableName = args[0]; final String logicalKeyStoreName = args[1]; final String kmsKeyArn = args[2]; KeyStoreCreateTable(keyStoreTableName, logicalKeyStoreName, kmsKeyArn); } }
5,244
0
Create_ds/aws-database-encryption-sdk-dynamodb-java/Examples/runtimes/java/DynamoDbEncryption/src/main/java/software/amazon/cryptography
Create_ds/aws-database-encryption-sdk-dynamodb-java/Examples/runtimes/java/DynamoDbEncryption/src/main/java/software/amazon/cryptography/examples/ManipulationUtils.java
package software.amazon.cryptography.examples; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.nio.charset.Charset; import java.util.HashMap; import java.util.Map; import software.amazon.awssdk.core.SdkBytes; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; import software.amazon.awssdk.services.kms.model.InvalidCiphertextException; import software.amazon.cryptography.dbencryptionsdk.dynamodb.itemencryptor.DynamoDbItemEncryptor; import software.amazon.cryptography.dbencryptionsdk.dynamodb.itemencryptor.model.DecryptItemInput; import software.amazon.cryptography.dbencryptionsdk.structuredencryption.model.StructuredEncryptionException; import software.amazon.cryptography.materialproviders.model.CollectionOfErrors; public class ManipulationUtils { public static class ManipulationException extends RuntimeException { public ManipulationException(String msg) {super(msg);} public ManipulationException(Throwable throwable){super(throwable);} public ManipulationException(String msg, Throwable throwable){super(msg, throwable);} }; public static void assertManipulationProof( final DynamoDbItemEncryptor itemEncryptor, final Map<String, AttributeValue> manipulated, final String attributeName ) { boolean manipulationProof = false; try { itemEncryptor.DecryptItem(DecryptItemInput.builder().encryptedItem(manipulated).build()); } catch (StructuredEncryptionException ex) { manipulationProof = true; } if (!manipulationProof) { throw new ManipulationException(String.format( "Attribute Named %s was supposedly manipulated but did not fail Authorization Check!", attributeName )); } } public static void assertProtectedByEncryptionContext( final DynamoDbItemEncryptor itemEncryptor, final Map<String, AttributeValue> manipulated, final String attributeName ) { boolean manipulationProof = false; String exceptionMsg = String.format( "Attribute Named %s was supposedly manipulated but did not fail Encryption Context Check!" + " (Or at least it did not fail it as expected!)", attributeName ); try { itemEncryptor.DecryptItem(DecryptItemInput.builder().encryptedItem(manipulated).build()); } catch (CollectionOfErrors ex) { ex.list().stream().filter(nestedEx -> nestedEx instanceof CollectionOfErrors) .map(nestedEx -> (CollectionOfErrors) nestedEx) .map(nestedEx -> nestedEx.list().stream() .filter(doubleNestedEx -> doubleNestedEx instanceof InvalidCiphertextException) .map(doubleNestedEx -> (InvalidCiphertextException) doubleNestedEx) .findAny().orElseThrow(() -> new ManipulationException(exceptionMsg, ex)) ).findAny().orElseThrow(() -> new ManipulationException(exceptionMsg, ex)); manipulationProof = true; } if (!manipulationProof) { throw new ManipulationException(String.format( "Attribute Named %s was supposedly manipulated but did not fail Authorization Check!", attributeName )); } } public static void assertNotManipulationProof( final DynamoDbItemEncryptor itemEncryptor, final Map<String, AttributeValue> manipulated, final String attributeName ) { try { itemEncryptor.DecryptItem(DecryptItemInput.builder().encryptedItem(manipulated).build()); } catch (StructuredEncryptionException ex) { throw new ManipulationException(String.format( "Attribute Named %s was supposedly manipulated and is NOT SIGNED " + "but it failed Authorization Check!\n" + "\tAttribute Value: %s", attributeName, manipulated.get(attributeName) ), ex); } } public static Map<String, AttributeValue> manipulateByteAttribute( final Map<String, AttributeValue> item, final String attributeName ) throws IOException { Map<String, AttributeValue> manipulated = new HashMap<>(item); ByteArrayOutputStream concatStream = new ByteArrayOutputStream(); concatStream.write(item.get(attributeName).b().asByteArray()); concatStream.write(SdkBytes.fromString("Manipulation!", Charset.defaultCharset()).asByteArray()); manipulated.put(attributeName, AttributeValue.fromB(SdkBytes.fromByteArray(concatStream.toByteArray()))); return manipulated; } public static Map<String, AttributeValue> manipulateStringAttribute( final Map<String, AttributeValue> item, final String attributeName ) { Map<String, AttributeValue> manipulated = new HashMap<>(item); String concatString = item.get(attributeName).s() + "Manipulation!"; manipulated.put(attributeName, AttributeValue.fromS(concatString)); return manipulated; } public static Map<String, AttributeValue> manipulateNumberAttribute( final Map<String, AttributeValue> item, final String attributeName ) { Map<String, AttributeValue> manipulated = new HashMap<>(item); int manipulatedInt = Integer.parseInt(item.get(attributeName).n()) + 1; manipulated.put(attributeName, AttributeValue.fromN(Integer.toString(manipulatedInt))); return manipulated; } }
5,245
0
Create_ds/aws-database-encryption-sdk-dynamodb-java/Examples/runtimes/java/DynamoDbEncryption/src/main/java/software/amazon/cryptography/examples
Create_ds/aws-database-encryption-sdk-dynamodb-java/Examples/runtimes/java/DynamoDbEncryption/src/main/java/software/amazon/cryptography/examples/keyring/ExampleBranchKeyIdSupplier.java
package software.amazon.cryptography.examples.keyring; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; import software.amazon.cryptography.dbencryptionsdk.dynamodb.IDynamoDbKeyBranchKeyIdSupplier; import software.amazon.cryptography.dbencryptionsdk.dynamodb.model.GetBranchKeyIdFromDdbKeyInput; import software.amazon.cryptography.dbencryptionsdk.dynamodb.model.GetBranchKeyIdFromDdbKeyOutput; import java.util.Map; // Used in the 'HierarchicalKeyringExample'. // In that example, we have a table where we distinguish multiple tenants // by a tenant ID that is stored in our partition attribute. // The expectation is that this does not produce a confused deputy // because the tenants are separated by partition. // In order to create a Hierarchical Keyring that is capable of encrypting or // decrypting data for either tenant, we implement this interface // to map the correct branch key ID to the correct tenant ID. class ExampleBranchKeyIdSupplier implements IDynamoDbKeyBranchKeyIdSupplier { private static String branchKeyIdForTenant1; private static String branchKeyIdForTenant2; public ExampleBranchKeyIdSupplier(String tenant1Id, String tenant2Id) { this.branchKeyIdForTenant1 = tenant1Id; this.branchKeyIdForTenant2 = tenant2Id; } public GetBranchKeyIdFromDdbKeyOutput GetBranchKeyIdFromDdbKey(GetBranchKeyIdFromDdbKeyInput input) { Map<String, AttributeValue> key = input.ddbKey(); if (!key.containsKey("partition_key")) { throw new IllegalArgumentException("Item invalid, does not contain expected partition key attribute."); } String tenantKeyId = key.get("partition_key").s(); String branchKeyId; if (tenantKeyId.equals("tenant1Id")) { branchKeyId = branchKeyIdForTenant1; } else if (tenantKeyId.equals("tenant2Id")) { branchKeyId = branchKeyIdForTenant2; } else { throw new IllegalArgumentException("Item does not contain valid tenant ID"); } return GetBranchKeyIdFromDdbKeyOutput.builder().branchKeyId(branchKeyId).build(); } }
5,246
0
Create_ds/aws-database-encryption-sdk-dynamodb-java/Examples/runtimes/java/DynamoDbEncryption/src/main/java/software/amazon/cryptography/examples
Create_ds/aws-database-encryption-sdk-dynamodb-java/Examples/runtimes/java/DynamoDbEncryption/src/main/java/software/amazon/cryptography/examples/keyring/MultiMrkKeyringExample.java
package software.amazon.cryptography.examples.keyring; import java.util.Collections; import java.util.HashMap; import java.util.Map; import software.amazon.awssdk.arns.Arn; import software.amazon.awssdk.core.client.config.ClientOverrideConfiguration; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.dynamodb.DynamoDbClient; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; import software.amazon.awssdk.services.dynamodb.model.GetItemRequest; import software.amazon.awssdk.services.dynamodb.model.GetItemResponse; import software.amazon.awssdk.services.dynamodb.model.PutItemRequest; import software.amazon.awssdk.services.dynamodb.model.PutItemResponse; import software.amazon.awssdk.services.kms.KmsClient; import software.amazon.cryptography.dbencryptionsdk.dynamodb.model.DynamoDbTableEncryptionConfig; import software.amazon.cryptography.dbencryptionsdk.dynamodb.model.DynamoDbTablesEncryptionConfig; import software.amazon.cryptography.materialproviders.IKeyring; import software.amazon.cryptography.materialproviders.MaterialProviders; import software.amazon.cryptography.materialproviders.model.CreateAwsKmsKeyringInput; import software.amazon.cryptography.materialproviders.model.CreateAwsKmsMrkKeyringInput; import software.amazon.cryptography.materialproviders.model.CreateAwsKmsMrkMultiKeyringInput; import software.amazon.cryptography.materialproviders.model.MaterialProvidersConfig; import software.amazon.cryptography.dbencryptionsdk.structuredencryption.model.CryptoAction; import software.amazon.cryptography.dbencryptionsdk.dynamodb.DynamoDbEncryptionInterceptor; /* This example sets up DynamoDb Encryption for the AWS SDK client using the MRK multi-keyring. This keyring takes in multiple AWS KMS MRKs (multi-region keys) or regular AWS KMS keys (single-region keys) and uses them to encrypt and decrypt data. Data encrypted using an MRK multi-keyring can be decrypted using any of its component keys. If a component key is an MRK with a replica in a second region, the replica key can also be used to decrypt data. For more information on MRKs, see https://docs.aws.amazon.com/kms/latest/developerguide/multi-region-keys-overview.html For more information on multi-keyrings, see https://docs.aws.amazon.com/encryption-sdk/latest/developer-guide/use-multi-keyring.html This example creates a new MRK multi-keyring consisting of one MRK (labeled as the "generator keyring") and one single-region key (labeled as the only "child keyring"). The MRK also has a replica in a second region. This example encrypts a test item using the MRK multi-keyring and puts the encrypted item to the provided DynamoDb table. Then, it gets the item from the table and decrypts it using three different configs: 1. The MRK multi-keyring, where the MRK key is used to decrypt 2. Another MRK multi-keyring, where the replica MRK key is used to decrypt 3. Another MRK multi-keyring, where the single-region key that was present in the original MRK multi-keyring is used to decrypt Running this example requires access to the DDB Table whose name is provided in CLI arguments. This table must be configured with the following primary key configuration: - Partition key is named "partition_key" with type (S) - Sort key is named "sort_key" with type (S) This example demonstrates multi-region use cases. As a result, it requires that you have a default region set in your AWS client. You can set a default region through the AWS CLI with `aws configure set region [region-name]` e.g. `aws configure set region us-west-2` For more information on using AWS CLI to set config, see https://awscli.amazonaws.com/v2/documentation/api/latest/reference/configure/set.html */ public class MultiMrkKeyringExample { public static void MultiMrkKeyringGetItemPutItem(String ddbTableName, String mrkKeyArn, String keyArn, String mrkReplicaKeyArn) { // 1. Create a single MRK multi-keyring using the MRK arn and the single-region key arn. final MaterialProviders matProv = MaterialProviders.builder() .MaterialProvidersConfig(MaterialProvidersConfig.builder().build()) .build(); // Create the multi-keyring, using the MRK as the generator key, // and the single-region key as a child key. // Note that the generator key will generate and encrypt a plaintext data key // and all child keys will only encrypt that same plaintext data key. // As such, you must have permission to call KMS:GenerateDataKey on your generator key // and permission to call KMS:Encrypt on all child keys. // For more information, see the AWS docs on multi-keyrings above. final CreateAwsKmsMrkMultiKeyringInput createAwsKmsMrkMultiKeyringInput = CreateAwsKmsMrkMultiKeyringInput.builder() .generator(mrkKeyArn) .kmsKeyIds(Collections.singletonList(keyArn)) .build(); IKeyring awsKmsMrkMultiKeyring = matProv.CreateAwsKmsMrkMultiKeyring(createAwsKmsMrkMultiKeyringInput); // 2. Configure which attributes are encrypted and/or signed when writing new items. // For each attribute that may exist on the items we plan to write to our DynamoDbTable, // we must explicitly configure how they should be treated during item encryption: // - ENCRYPT_AND_SIGN: The attribute is encrypted and included in the signature // - SIGN_ONLY: The attribute not encrypted, but is still included in the signature // - DO_NOTHING: The attribute is not encrypted and not included in the signature final Map<String, CryptoAction> attributeActionsOnEncrypt = new HashMap<>(); attributeActionsOnEncrypt.put("partition_key", CryptoAction.SIGN_ONLY); // Our partition attribute must be SIGN_ONLY attributeActionsOnEncrypt.put("sort_key", CryptoAction.SIGN_ONLY); // Our sort attribute must be SIGN_ONLY attributeActionsOnEncrypt.put("sensitive_data", CryptoAction.ENCRYPT_AND_SIGN); // 3. Configure which attributes we expect to be included in the signature // when reading items. There are two options for configuring this: // // - (Recommended) Configure `allowedUnsignedAttributesPrefix`: // When defining your DynamoDb schema and deciding on attribute names, // choose a distinguishing prefix (such as ":") for all attributes that // you do not want to include in the signature. // This has two main benefits: // - It is easier to reason about the security and authenticity of data within your item // when all unauthenticated data is easily distinguishable by their attribute name. // - If you need to add new unauthenticated attributes in the future, // you can easily make the corresponding update to your `attributeActionsOnEncrypt` // and immediately start writing to that new attribute, without // any other configuration update needed. // Once you configure this field, it is not safe to update it. // // - Configure `allowedUnsignedAttributes`: You may also explicitly list // a set of attributes that should be considered unauthenticated when encountered // on read. Be careful if you use this configuration. Do not remove an attribute // name from this configuration, even if you are no longer writing with that attribute, // as old items may still include this attribute, and our configuration needs to know // to continue to exclude this attribute from the signature scope. // If you add new attribute names to this field, you must first deploy the update to this // field to all readers in your host fleet before deploying the update to start writing // with that new attribute. // // For this example, we currently authenticate all attributes. To make it easier to // add unauthenticated attributes in the future, we define a prefix ":" for such attributes. final String unsignAttrPrefix = ":"; // 4. Create the DynamoDb Encryption configuration for the table we will be writing to. final Map<String, DynamoDbTableEncryptionConfig> tableConfigs = new HashMap<>(); final DynamoDbTableEncryptionConfig config = DynamoDbTableEncryptionConfig.builder() .logicalTableName(ddbTableName) .partitionKeyName("partition_key") .sortKeyName("sort_key") .attributeActionsOnEncrypt(attributeActionsOnEncrypt) .keyring(awsKmsMrkMultiKeyring) .allowedUnsignedAttributePrefix(unsignAttrPrefix) .build(); tableConfigs.put(ddbTableName, config); // 5. Create the DynamoDb Encryption Interceptor DynamoDbEncryptionInterceptor encryptionInterceptor = DynamoDbEncryptionInterceptor.builder() .config(DynamoDbTablesEncryptionConfig.builder() .tableEncryptionConfigs(tableConfigs) .build()) .build(); // 6. Create a new AWS SDK DynamoDb client using the DynamoDb Encryption Interceptor above final DynamoDbClient ddbClient = DynamoDbClient.builder() .overrideConfiguration( ClientOverrideConfiguration.builder() .addExecutionInterceptor(encryptionInterceptor) .build()) .build(); // 7. Put an item into our table using the above client. // Before the item gets sent to DynamoDb, it will be encrypted // client-side using the MRK multi-keyring. // The data key protecting this item will be encrypted // with all the KMS Keys in this keyring, so that it can be // decrypted with any one of those KMS Keys. final HashMap<String, AttributeValue> item = new HashMap<>(); item.put("partition_key", AttributeValue.builder().s("awsKmsMrkMultiKeyringItem").build()); item.put("sort_key", AttributeValue.builder().n("0").build()); item.put("sensitive_data", AttributeValue.builder().s("encrypt and sign me!").build()); final PutItemRequest putRequest = PutItemRequest.builder() .tableName(ddbTableName) .item(item) .build(); final PutItemResponse putResponse = ddbClient.putItem(putRequest); // Demonstrate that PutItem succeeded assert 200 == putResponse.sdkHttpResponse().statusCode(); // 8. Get the item back from our table using the client. // The client will decrypt the item client-side using the MRK // and return back the original item. // Since the generator key is the first available key in the keyring, // that is the KMS Key that will be used to decrypt this item. final HashMap<String, AttributeValue> keyToGet = new HashMap<>(); keyToGet.put("partition_key", AttributeValue.builder().s("awsKmsMrkMultiKeyringItem").build()); keyToGet.put("sort_key", AttributeValue.builder().n("0").build()); final GetItemRequest getRequest = GetItemRequest.builder() .key(keyToGet) .tableName(ddbTableName) .build(); final GetItemResponse getResponse = ddbClient.getItem(getRequest); // Demonstrate that GetItem succeeded and returned the decrypted item assert 200 == getResponse.sdkHttpResponse().statusCode(); final Map<String, AttributeValue> returnedItem = getResponse.item(); assert returnedItem.get("sensitive_data").s().equals("encrypt and sign me!"); // 9. Create a MRK keyring using the replica MRK arn. // We will use this to demonstrate that the replica MRK // can decrypt data created with the original MRK, // even when the replica MRK was not present in the // encrypting multi-keyring. final CreateAwsKmsMrkMultiKeyringInput onlyReplicaKeyCreateAwsKmsMrkMultiKeyringInput = CreateAwsKmsMrkMultiKeyringInput.builder() .kmsKeyIds(Collections.singletonList(mrkReplicaKeyArn)) .build(); IKeyring onlyReplicaKeyMrkMultiKeyring = matProv.CreateAwsKmsMrkMultiKeyring( onlyReplicaKeyCreateAwsKmsMrkMultiKeyringInput); // 10. Create a new config and client using the MRK keyring. // This is the same setup as above, except we provide the MRK keyring to the config. final Map<String, DynamoDbTableEncryptionConfig> onlyReplicaKeyTableConfigs = new HashMap<>(); final DynamoDbTableEncryptionConfig onlyReplicaKeyConfig = DynamoDbTableEncryptionConfig.builder() .logicalTableName(ddbTableName) .partitionKeyName("partition_key") .sortKeyName("sort_key") .attributeActionsOnEncrypt(attributeActionsOnEncrypt) // Only replica keyring added here .keyring(onlyReplicaKeyMrkMultiKeyring) .allowedUnsignedAttributePrefix(unsignAttrPrefix) .build(); onlyReplicaKeyTableConfigs.put(ddbTableName, onlyReplicaKeyConfig); DynamoDbEncryptionInterceptor onlyReplicaKeyEncryptionInterceptor = DynamoDbEncryptionInterceptor.builder() .config(DynamoDbTablesEncryptionConfig.builder() .tableEncryptionConfigs(onlyReplicaKeyTableConfigs) .build()) .build(); final DynamoDbClient onlyReplicaKeyDdbClient = DynamoDbClient.builder() .overrideConfiguration( ClientOverrideConfiguration.builder() .addExecutionInterceptor(onlyReplicaKeyEncryptionInterceptor) .build()) .build(); // 11. Get the item back from our table using the client configured with the replica. // The client will decrypt the item client-side using the replica MRK // and return back the original item. final HashMap<String, AttributeValue> onlyReplicaKeyKeyToGet = new HashMap<>(); onlyReplicaKeyKeyToGet.put("partition_key", AttributeValue.builder().s("awsKmsMrkMultiKeyringItem").build()); onlyReplicaKeyKeyToGet.put("sort_key", AttributeValue.builder().n("0").build()); final GetItemRequest onlyReplicaKeyGetRequest = GetItemRequest.builder() .key(onlyReplicaKeyKeyToGet) .tableName(ddbTableName) .build(); final GetItemResponse onlyReplicaKeyGetResponse = onlyReplicaKeyDdbClient.getItem(onlyReplicaKeyGetRequest); // Demonstrate that GetItem succeeded and returned the decrypted item assert 200 == onlyReplicaKeyGetResponse.sdkHttpResponse().statusCode(); final Map<String, AttributeValue> onlyReplicaKeyReturnedItem = onlyReplicaKeyGetResponse.item(); assert onlyReplicaKeyReturnedItem.get("sensitive_data").s().equals("encrypt and sign me!"); // 12. Create an AWS KMS keyring using the single-region key ARN. // We will use this to demonstrate that the single-region key // can decrypt data created with the MRK multi-keyring, // since it is present in the keyring used to encrypt. final CreateAwsKmsMrkMultiKeyringInput onlySrkCreateAwsKmsMrkMultiKeyringInput = CreateAwsKmsMrkMultiKeyringInput.builder() .kmsKeyIds(Collections.singletonList(keyArn)) .build(); IKeyring onlySrkKeyring = matProv.CreateAwsKmsMrkMultiKeyring(onlySrkCreateAwsKmsMrkMultiKeyringInput); // 13. Create a new config and client using the AWS KMS keyring. // This is the same setup as above, except we provide the AWS KMS keyring to the config. final Map<String, DynamoDbTableEncryptionConfig> onlySrkTableConfigs = new HashMap<>(); final DynamoDbTableEncryptionConfig onlySrkConfig = DynamoDbTableEncryptionConfig.builder() .logicalTableName(ddbTableName) .partitionKeyName("partition_key") .sortKeyName("sort_key") .attributeActionsOnEncrypt(attributeActionsOnEncrypt) // Only single-region key keyring added here .keyring(onlySrkKeyring) .allowedUnsignedAttributePrefix(unsignAttrPrefix) .build(); onlySrkTableConfigs.put(ddbTableName, onlySrkConfig); DynamoDbEncryptionInterceptor onlySrkEncryptionInterceptor = DynamoDbEncryptionInterceptor.builder() .config(DynamoDbTablesEncryptionConfig.builder() .tableEncryptionConfigs(onlySrkTableConfigs) .build()) .build(); final DynamoDbClient onlySrkDdbClient = DynamoDbClient.builder() .overrideConfiguration( ClientOverrideConfiguration.builder() .addExecutionInterceptor(onlySrkEncryptionInterceptor) .build()) .build(); // 14. Get the item back from our table using the client configured with the AWS KMS keyring. // The client will decrypt the item client-side using the single-region key // and return back the original item. final HashMap<String, AttributeValue> onlySrkKeyToGet = new HashMap<>(); onlySrkKeyToGet.put("partition_key", AttributeValue.builder().s("awsKmsMrkMultiKeyringItem").build()); onlySrkKeyToGet.put("sort_key", AttributeValue.builder().n("0").build()); final GetItemRequest onlySrkGetRequest = GetItemRequest.builder() .key(onlySrkKeyToGet) .tableName(ddbTableName) .build(); final GetItemResponse onlySrkGetResponse = onlySrkDdbClient.getItem(onlySrkGetRequest); // Demonstrate that GetItem succeeded and returned the decrypted item assert 200 == onlySrkGetResponse.sdkHttpResponse().statusCode(); final Map<String, AttributeValue> onlySrkReturnedItem = onlySrkGetResponse.item(); assert onlySrkReturnedItem.get("sensitive_data").s().equals("encrypt and sign me!"); } public static void main(final String[] args) { if (args.length <= 1) { throw new IllegalArgumentException("To run this example, include the ddbTable, mrkKeyArn, keyArn, and mrkReplicaKeyArn in args"); } final String ddbTableName = args[0]; final String mrkKeyArn = args[1]; final String srkArn = args[2]; final String mrkReplicaKeyArn = args[3]; MultiMrkKeyringGetItemPutItem(ddbTableName, mrkKeyArn, srkArn, mrkReplicaKeyArn); } }
5,247
0
Create_ds/aws-database-encryption-sdk-dynamodb-java/Examples/runtimes/java/DynamoDbEncryption/src/main/java/software/amazon/cryptography/examples
Create_ds/aws-database-encryption-sdk-dynamodb-java/Examples/runtimes/java/DynamoDbEncryption/src/main/java/software/amazon/cryptography/examples/keyring/RawAesKeyringExample.java
package software.amazon.cryptography.examples.keyring; import java.nio.ByteBuffer; 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 software.amazon.awssdk.core.client.config.ClientOverrideConfiguration; import software.amazon.awssdk.services.dynamodb.DynamoDbClient; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; import software.amazon.awssdk.services.dynamodb.model.GetItemRequest; import software.amazon.awssdk.services.dynamodb.model.GetItemResponse; import software.amazon.awssdk.services.dynamodb.model.PutItemRequest; import software.amazon.awssdk.services.dynamodb.model.PutItemResponse; import software.amazon.cryptography.dbencryptionsdk.dynamodb.model.DynamoDbTableEncryptionConfig; import software.amazon.cryptography.dbencryptionsdk.dynamodb.model.DynamoDbTablesEncryptionConfig; 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 software.amazon.cryptography.dbencryptionsdk.dynamodb.DynamoDbEncryptionInterceptor; /* This example sets up DynamoDb Encryption for the AWS SDK client using the raw AES Keyring. This keyring takes in an AES key and uses that key to protect the data keys that encrypt and decrypt DynamoDb table items. This example takes in an `aesKeyBytes` parameter. This parameter should be a ByteBuffer representing a 256-bit AES key. If this example is run through the class' main method, it will create a new key. In practice, users of this library should not randomly generate a key, and should instead retrieve an existing key from a secure key management system (e.g. an HSM). This example encrypts a test item using the provided AES key and puts the encrypted item to the provided DynamoDb table. Then, it gets the item from the table and decrypts it. Running this example requires access to the DDB Table whose name is provided in CLI arguments. This table must be configured with the following primary key configuration: - Partition key is named "partition_key" with type (S) - Sort key is named "sort_key" with type (S) */ public class RawAesKeyringExample { public static void RawAesKeyringGetItemPutItem(String ddbTableName, ByteBuffer aesKeyBytes) { // 1. Create the keyring. // The DynamoDb encryption client uses this to encrypt and decrypt items. final CreateRawAesKeyringInput keyringInput = CreateRawAesKeyringInput.builder() .keyName("my-aes-key-name") .keyNamespace("my-key-namespace") .wrappingKey(aesKeyBytes) .wrappingAlg(AesWrappingAlg.ALG_AES256_GCM_IV12_TAG16) .build(); final MaterialProviders matProv = MaterialProviders.builder() .MaterialProvidersConfig(MaterialProvidersConfig.builder().build()) .build(); IKeyring rawAesKeyring = matProv.CreateRawAesKeyring(keyringInput); // 2. Configure which attributes are encrypted and/or signed when writing new items. // For each attribute that may exist on the items we plan to write to our DynamoDbTable, // we must explicitly configure how they should be treated during item encryption: // - ENCRYPT_AND_SIGN: The attribute is encrypted and included in the signature // - SIGN_ONLY: The attribute not encrypted, but is still included in the signature // - DO_NOTHING: The attribute is not encrypted and not included in the signature final Map<String, CryptoAction> attributeActionsOnEncrypt = new HashMap<>(); attributeActionsOnEncrypt.put("partition_key", CryptoAction.SIGN_ONLY); // Our partition attribute must be SIGN_ONLY attributeActionsOnEncrypt.put("sort_key", CryptoAction.SIGN_ONLY); // Our sort attribute must be SIGN_ONLY attributeActionsOnEncrypt.put("sensitive_data", CryptoAction.ENCRYPT_AND_SIGN); // 3. Configure which attributes we expect to be included in the signature // when reading items. There are two options for configuring this: // // - (Recommended) Configure `allowedUnsignedAttributesPrefix`: // When defining your DynamoDb schema and deciding on attribute names, // choose a distinguishing prefix (such as ":") for all attributes that // you do not want to include in the signature. // This has two main benefits: // - It is easier to reason about the security and authenticity of data within your item // when all unauthenticated data is easily distinguishable by their attribute name. // - If you need to add new unauthenticated attributes in the future, // you can easily make the corresponding update to your `attributeActionsOnEncrypt` // and immediately start writing to that new attribute, without // any other configuration update needed. // Once you configure this field, it is not safe to update it. // // - Configure `allowedUnsignedAttributes`: You may also explicitly list // a set of attributes that should be considered unauthenticated when encountered // on read. Be careful if you use this configuration. Do not remove an attribute // name from this configuration, even if you are no longer writing with that attribute, // as old items may still include this attribute, and our configuration needs to know // to continue to exclude this attribute from the signature scope. // If you add new attribute names to this field, you must first deploy the update to this // field to all readers in your host fleet before deploying the update to start writing // with that new attribute. // // For this example, we currently authenticate all attributes. To make it easier to // add unauthenticated attributes in the future, we define a prefix ":" for such attributes. final String unsignAttrPrefix = ":"; // 4. Create the DynamoDb Encryption configuration for the table we will be writing to. final Map<String, DynamoDbTableEncryptionConfig> tableConfigs = new HashMap<>(); final DynamoDbTableEncryptionConfig config = DynamoDbTableEncryptionConfig.builder() .logicalTableName(ddbTableName) .partitionKeyName("partition_key") .sortKeyName("sort_key") .attributeActionsOnEncrypt(attributeActionsOnEncrypt) .keyring(rawAesKeyring) .allowedUnsignedAttributePrefix(unsignAttrPrefix) .build(); tableConfigs.put(ddbTableName, config); // 5. Create the DynamoDb Encryption Interceptor DynamoDbEncryptionInterceptor encryptionInterceptor = DynamoDbEncryptionInterceptor.builder() .config(DynamoDbTablesEncryptionConfig.builder() .tableEncryptionConfigs(tableConfigs) .build()) .build(); // 6. Create a new AWS SDK DynamoDb client using the DynamoDb Encryption Interceptor above final DynamoDbClient ddb = DynamoDbClient.builder() .overrideConfiguration( ClientOverrideConfiguration.builder() .addExecutionInterceptor(encryptionInterceptor) .build()) .build(); // 7. Put an item into our table using the above client. // Before the item gets sent to DynamoDb, it will be encrypted // client-side, according to our configuration. final HashMap<String, AttributeValue> item = new HashMap<>(); item.put("partition_key", AttributeValue.builder().s("rawAesKeyringItem").build()); item.put("sort_key", AttributeValue.builder().n("0").build()); item.put("sensitive_data", AttributeValue.builder().s("encrypt and sign me!").build()); final PutItemRequest putRequest = PutItemRequest.builder() .tableName(ddbTableName) .item(item) .build(); final PutItemResponse putResponse = ddb.putItem(putRequest); // Demonstrate that PutItem succeeded assert 200 == putResponse.sdkHttpResponse().statusCode(); // 8. Get the item back from our table using the same client. // The client will decrypt the item client-side, and return // back the original item. final HashMap<String, AttributeValue> keyToGet = new HashMap<>(); keyToGet.put("partition_key", AttributeValue.builder().s("rawAesKeyringItem").build()); keyToGet.put("sort_key", AttributeValue.builder().n("0").build()); final GetItemRequest getRequest = GetItemRequest.builder() .key(keyToGet) .tableName(ddbTableName) .build(); final GetItemResponse getResponse = ddb.getItem(getRequest); // Demonstrate that GetItem succeeded and returned the decrypted item assert 200 == getResponse.sdkHttpResponse().statusCode(); final Map<String, AttributeValue> returnedItem = getResponse.item(); assert returnedItem.get("sensitive_data").s().equals("encrypt and sign me!"); } public static void main(final String[] args) { if (args.length <= 0) { throw new IllegalArgumentException("To run this example, include the ddbTable in args"); } final String ddbTableName = args[0]; // Generate a new AES key ByteBuffer aesKeyBytes = generateAesKeyBytes(); RawAesKeyringGetItemPutItem(ddbTableName, aesKeyBytes); } static ByteBuffer generateAesKeyBytes() { // This example uses BouncyCastle's KeyGenerator to generate the key bytes. // In practice, you should not generate this key in your code, and should instead // retrieve this key from a secure key management system (e.g. HSM). // This key is created here for example purposes only and should not be used for any other purpose. KeyGenerator aesGen; try { aesGen = KeyGenerator.getInstance("AES"); } catch (NoSuchAlgorithmException e) { throw new RuntimeException("No such algorithm", e); } aesGen.init(256, new SecureRandom()); SecretKey encryptionKey = aesGen.generateKey(); ByteBuffer encryptionKeyByteBuffer = ByteBuffer.wrap(encryptionKey.getEncoded()); return encryptionKeyByteBuffer; } }
5,248
0
Create_ds/aws-database-encryption-sdk-dynamodb-java/Examples/runtimes/java/DynamoDbEncryption/src/main/java/software/amazon/cryptography/examples
Create_ds/aws-database-encryption-sdk-dynamodb-java/Examples/runtimes/java/DynamoDbEncryption/src/main/java/software/amazon/cryptography/examples/keyring/MultiKeyringExample.java
package software.amazon.cryptography.examples.keyring; import com.amazonaws.services.dynamodbv2.datamodeling.internal.Utils; import java.nio.ByteBuffer; 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 software.amazon.awssdk.core.client.config.ClientOverrideConfiguration; import software.amazon.awssdk.services.dynamodb.DynamoDbClient; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; import software.amazon.awssdk.services.dynamodb.model.GetItemRequest; import software.amazon.awssdk.services.dynamodb.model.GetItemResponse; import software.amazon.awssdk.services.dynamodb.model.PutItemRequest; import software.amazon.awssdk.services.dynamodb.model.PutItemResponse; import software.amazon.awssdk.services.kms.KmsClient; import software.amazon.cryptography.dbencryptionsdk.dynamodb.model.DynamoDbTableEncryptionConfig; import software.amazon.cryptography.dbencryptionsdk.dynamodb.model.DynamoDbTablesEncryptionConfig; 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.CreateAwsKmsKeyringInput; import software.amazon.cryptography.materialproviders.model.CreateAwsKmsMrkMultiKeyringInput; import software.amazon.cryptography.materialproviders.model.CreateMultiKeyringInput; import software.amazon.cryptography.materialproviders.model.CreateRawAesKeyringInput; import software.amazon.cryptography.materialproviders.model.MaterialProvidersConfig; import software.amazon.cryptography.dbencryptionsdk.structuredencryption.model.CryptoAction; import software.amazon.cryptography.dbencryptionsdk.dynamodb.DynamoDbEncryptionInterceptor; /* This example sets up DynamoDb Encryption for the AWS SDK client using the multi-keyring. This keyring takes in multiple keyrings and uses them to encrypt and decrypt data. Data encrypted with a multi-keyring can be decrypted with any of its component keyrings. For more information on multi-keyrings, see https://docs.aws.amazon.com/encryption-sdk/latest/developer-guide/use-multi-keyring.html This example creates a new multi-keyring consisting of an AWS KMS keyring (labeled the "generator keyring") and a raw AES keyring (labeled as the only "child keyring"). It encrypts a test item using the multi-keyring and puts the encrypted item to the provided DynamoDb table. Then, it gets the item from the table and decrypts it using only the raw AES keyring. This example takes in an `aesKeyBytes` parameter. This parameter should be a ByteBuffer representing a 256-bit AES key. If this example is run through the class' main method, it will create a new key. In practice, users of this library should not randomly generate a key, and should instead retrieve an existing key from a secure key management system (e.g. an HSM). Running this example requires access to the DDB Table whose name is provided in CLI arguments. This table must be configured with the following primary key configuration: - Partition key is named "partition_key" with type (S) - Sort key is named "sort_key" with type (S) */ public class MultiKeyringExample { public static void MultiKeyringGetItemPutItem(String ddbTableName, String keyArn, ByteBuffer aesKeyBytes) { // 1. Create the raw AES keyring. final MaterialProviders matProv = MaterialProviders.builder() .MaterialProvidersConfig(MaterialProvidersConfig.builder().build()) .build(); final CreateRawAesKeyringInput createRawAesKeyringInput = CreateRawAesKeyringInput.builder() .keyName("my-aes-key-name") .keyNamespace("my-key-namespace") .wrappingKey(aesKeyBytes) .wrappingAlg(AesWrappingAlg.ALG_AES256_GCM_IV12_TAG16) .build(); IKeyring rawAesKeyring = matProv.CreateRawAesKeyring(createRawAesKeyringInput); // 2. Create the AWS KMS keyring. // We create a MRK multi keyring, as this interface also supports // single-region KMS keys (standard KMS keys), // and creates the KMS client for us automatically. final CreateAwsKmsMrkMultiKeyringInput createAwsKmsMrkMultiKeyringInput = CreateAwsKmsMrkMultiKeyringInput.builder() .generator(keyArn) .build(); IKeyring awsKmsMrkMultiKeyring = matProv.CreateAwsKmsMrkMultiKeyring(createAwsKmsMrkMultiKeyringInput); // 3. Create the multi-keyring. // We will label the AWS KMS keyring as the generator and the raw AES keyring as the // only child keyring. // You must provide a generator keyring to encrypt data. // You may provide additional child keyrings. Each child keyring will be able to // decrypt data encrypted with the multi-keyring on its own. It does not need // knowledge of any other child keyrings or the generator keyring to decrypt. final CreateMultiKeyringInput createMultiKeyringInput = CreateMultiKeyringInput.builder() .generator(awsKmsMrkMultiKeyring) .childKeyrings(Collections.singletonList(rawAesKeyring)) .build(); IKeyring multiKeyring = matProv.CreateMultiKeyring(createMultiKeyringInput); // 4. Configure which attributes are encrypted and/or signed when writing new items. // For each attribute that may exist on the items we plan to write to our DynamoDbTable, // we must explicitly configure how they should be treated during item encryption: // - ENCRYPT_AND_SIGN: The attribute is encrypted and included in the signature // - SIGN_ONLY: The attribute not encrypted, but is still included in the signature // - DO_NOTHING: The attribute is not encrypted and not included in the signature final Map<String, CryptoAction> attributeActionsOnEncrypt = new HashMap<>(); attributeActionsOnEncrypt.put("partition_key", CryptoAction.SIGN_ONLY); // Our partition attribute must be SIGN_ONLY attributeActionsOnEncrypt.put("sort_key", CryptoAction.SIGN_ONLY); // Our sort attribute must be SIGN_ONLY attributeActionsOnEncrypt.put("sensitive_data", CryptoAction.ENCRYPT_AND_SIGN); // 5. Configure which attributes we expect to be included in the signature // when reading items. There are two options for configuring this: // // - (Recommended) Configure `allowedUnsignedAttributesPrefix`: // When defining your DynamoDb schema and deciding on attribute names, // choose a distinguishing prefix (such as ":") for all attributes that // you do not want to include in the signature. // This has two main benefits: // - It is easier to reason about the security and authenticity of data within your item // when all unauthenticated data is easily distinguishable by their attribute name. // - If you need to add new unauthenticated attributes in the future, // you can easily make the corresponding update to your `attributeActionsOnEncrypt` // and immediately start writing to that new attribute, without // any other configuration update needed. // Once you configure this field, it is not safe to update it. // // - Configure `allowedUnsignedAttributes`: You may also explicitly list // a set of attributes that should be considered unauthenticated when encountered // on read. Be careful if you use this configuration. Do not remove an attribute // name from this configuration, even if you are no longer writing with that attribute, // as old items may still include this attribute, and our configuration needs to know // to continue to exclude this attribute from the signature scope. // If you add new attribute names to this field, you must first deploy the update to this // field to all readers in your host fleet before deploying the update to start writing // with that new attribute. // // For this example, we currently authenticate all attributes. To make it easier to // add unauthenticated attributes in the future, we define a prefix ":" for such attributes. final String unsignAttrPrefix = ":"; // 6. Create the DynamoDb Encryption configuration for the table we will be writing to. // Note that this example creates one config/client combination for PUT, and another // for GET. The PUT config uses the multi-keyring, while the GET config uses the // raw AES keyring. This is solely done to demonstrate that a keyring included as // a child of a multi-keyring can be used to decrypt data on its own. final Map<String, DynamoDbTableEncryptionConfig> tableConfigs = new HashMap<>(); final DynamoDbTableEncryptionConfig config = DynamoDbTableEncryptionConfig.builder() .logicalTableName(ddbTableName) .partitionKeyName("partition_key") .sortKeyName("sort_key") .attributeActionsOnEncrypt(attributeActionsOnEncrypt) // Multi-keyring is added here .keyring(multiKeyring) .allowedUnsignedAttributePrefix(unsignAttrPrefix) .build(); tableConfigs.put(ddbTableName, config); // 7. Create the DynamoDb Encryption Interceptor DynamoDbEncryptionInterceptor encryptionInterceptor = DynamoDbEncryptionInterceptor.builder() .config(DynamoDbTablesEncryptionConfig.builder() .tableEncryptionConfigs(tableConfigs) .build()) .build(); // 8. Create a new AWS SDK DynamoDb client using the DynamoDb Encryption Interceptor above final DynamoDbClient ddbClient = DynamoDbClient.builder() .overrideConfiguration( ClientOverrideConfiguration.builder() .addExecutionInterceptor(encryptionInterceptor) .build()) .build(); // 9. Put an item into our table using the above client. // Before the item gets sent to DynamoDb, it will be encrypted // client-side using the multi-keyring. // The item will be encrypted with all wrapping keys in the keyring, // so that it can be decrypted with any one of the keys. final HashMap<String, AttributeValue> item = new HashMap<>(); item.put("partition_key", AttributeValue.builder().s("multiKeyringItem").build()); item.put("sort_key", AttributeValue.builder().n("0").build()); item.put("sensitive_data", AttributeValue.builder().s("encrypt and sign me!").build()); final PutItemRequest putRequest = PutItemRequest.builder() .tableName(ddbTableName) .item(item) .build(); final PutItemResponse putResponse = ddbClient.putItem(putRequest); // Demonstrate that PutItem succeeded assert 200 == putResponse.sdkHttpResponse().statusCode(); // 10. Get the item back from our table using the above client. // The client will decrypt the item client-side using the AWS KMS // keyring, and return back the original item. // Since the generator key is the first available key in the keyring, // that is the key that will be used to decrypt this item. final HashMap<String, AttributeValue> keyToGet = new HashMap<>(); keyToGet.put("partition_key", AttributeValue.builder().s("multiKeyringItem").build()); keyToGet.put("sort_key", AttributeValue.builder().n("0").build()); final GetItemRequest getRequest = GetItemRequest.builder() .key(keyToGet) .tableName(ddbTableName) .build(); final GetItemResponse getResponse = ddbClient.getItem(getRequest); // Demonstrate that GetItem succeeded and returned the decrypted item assert 200 == getResponse.sdkHttpResponse().statusCode(); final Map<String, AttributeValue> returnedItem = getResponse.item(); assert returnedItem.get("sensitive_data").s().equals("encrypt and sign me!"); // 11. Create a new config and client with only the raw AES keyring to GET the item // This is the same setup as above, except the config uses the `rawAesKeyring`. final Map<String, DynamoDbTableEncryptionConfig> onlyAesKeyringTableConfigs = new HashMap<>(); final DynamoDbTableEncryptionConfig onlyAesKeyringConfig = DynamoDbTableEncryptionConfig.builder() .logicalTableName(ddbTableName) .partitionKeyName("partition_key") .sortKeyName("sort_key") .attributeActionsOnEncrypt(attributeActionsOnEncrypt) // Raw AES keyring is added here .keyring(rawAesKeyring) .allowedUnsignedAttributePrefix(unsignAttrPrefix) .build(); onlyAesKeyringTableConfigs.put(ddbTableName, onlyAesKeyringConfig); DynamoDbEncryptionInterceptor onlyAesKeyringEncryptionInterceptor = DynamoDbEncryptionInterceptor.builder() .config(DynamoDbTablesEncryptionConfig.builder() .tableEncryptionConfigs(onlyAesKeyringTableConfigs) .build()) .build(); final DynamoDbClient onlyAesKeyringDdbClient = DynamoDbClient.builder() .overrideConfiguration( ClientOverrideConfiguration.builder() .addExecutionInterceptor(onlyAesKeyringEncryptionInterceptor) .build()) .build(); // 12. Get the item back from our table using the client // configured with only the raw AES keyring. // The client will decrypt the item client-side using the raw // AES keyring, and return back the original item. final HashMap<String, AttributeValue> onlyAesKeyringKeyToGet = new HashMap<>(); onlyAesKeyringKeyToGet.put("partition_key", AttributeValue.builder().s("multiKeyringItem").build()); onlyAesKeyringKeyToGet.put("sort_key", AttributeValue.builder().n("0").build()); final GetItemRequest onlyAesKeyringGetRequest = GetItemRequest.builder() .key(onlyAesKeyringKeyToGet) .tableName(ddbTableName) .build(); final GetItemResponse onlyAesKeyringGetResponse = onlyAesKeyringDdbClient.getItem(onlyAesKeyringGetRequest); // Demonstrate that GetItem succeeded and returned the decrypted item assert 200 == getResponse.sdkHttpResponse().statusCode(); final Map<String, AttributeValue> onlyAesKeyringReturnedItem = onlyAesKeyringGetResponse.item(); assert onlyAesKeyringReturnedItem.get("sensitive_data").s().equals("encrypt and sign me!"); } public static void main(final String[] args) { if (args.length <= 1) { throw new IllegalArgumentException("To run this example, include the ddbTable and keyArn in args"); } final String ddbTableName = args[0]; final String keyArn = args[1]; // Generate a new AES key ByteBuffer aesKeyBytes = generateAesKeyBytes(); MultiKeyringGetItemPutItem(ddbTableName, keyArn, aesKeyBytes); } static ByteBuffer generateAesKeyBytes() { // This example uses BouncyCastle's KeyGenerator to generate the key bytes. // In practice, you should not generate this key in your code, and should instead // retrieve this key from a secure key management system (e.g. HSM). // This key is created here for example purposes only and should not be used for any other purpose. KeyGenerator aesGen; try { aesGen = KeyGenerator.getInstance("AES"); } catch (NoSuchAlgorithmException e) { throw new RuntimeException("No such algorithm", e); } aesGen.init(256, new SecureRandom()); SecretKey encryptionKey = aesGen.generateKey(); ByteBuffer encryptionKeyByteBuffer = ByteBuffer.wrap(encryptionKey.getEncoded()); return encryptionKeyByteBuffer; } }
5,249
0
Create_ds/aws-database-encryption-sdk-dynamodb-java/Examples/runtimes/java/DynamoDbEncryption/src/main/java/software/amazon/cryptography/examples
Create_ds/aws-database-encryption-sdk-dynamodb-java/Examples/runtimes/java/DynamoDbEncryption/src/main/java/software/amazon/cryptography/examples/keyring/HierarchicalKeyringExample.java
package software.amazon.cryptography.examples.keyring; import software.amazon.awssdk.core.client.config.ClientOverrideConfiguration; import software.amazon.awssdk.services.dynamodb.DynamoDbClient; import software.amazon.awssdk.services.dynamodb.model.*; import software.amazon.awssdk.services.kms.KmsClient; import software.amazon.cryptography.dbencryptionsdk.dynamodb.DynamoDbEncryption; import software.amazon.cryptography.dbencryptionsdk.dynamodb.model.CreateDynamoDbEncryptionBranchKeyIdSupplierInput; import software.amazon.cryptography.dbencryptionsdk.dynamodb.model.DynamoDbEncryptionConfig; import software.amazon.cryptography.dbencryptionsdk.dynamodb.model.DynamoDbTableEncryptionConfig; import software.amazon.cryptography.dbencryptionsdk.dynamodb.model.DynamoDbTablesEncryptionConfig; import software.amazon.cryptography.keystore.KeyStore; import software.amazon.cryptography.keystore.model.CreateKeyStoreInput; import software.amazon.cryptography.keystore.model.KMSConfiguration; import software.amazon.cryptography.keystore.model.KeyStoreConfig; import software.amazon.cryptography.materialproviders.IBranchKeyIdSupplier; import software.amazon.cryptography.materialproviders.IKeyring; import software.amazon.cryptography.materialproviders.MaterialProviders; import software.amazon.cryptography.materialproviders.model.CreateAwsKmsHierarchicalKeyringInput; import software.amazon.cryptography.materialproviders.model.MaterialProvidersConfig; import software.amazon.cryptography.materialproviders.model.CacheType; import software.amazon.cryptography.materialproviders.model.DefaultCache; import software.amazon.cryptography.dbencryptionsdk.structuredencryption.model.CryptoAction; import software.amazon.cryptography.dbencryptionsdk.dynamodb.DynamoDbEncryptionInterceptor; import java.util.HashMap; import java.util.Map; /* This example sets up DynamoDb Encryption for the AWS SDK client using the Hierarchical Keyring, which establishes a key hierarchy where "branch" keys are persisted in DynamoDb. These branch keys are used to protect your data keys, and these branch keys are themselves protected by a root KMS Key. Establishing a key hierarchy like this has two benefits: First, by caching the branch key material, and only calling back to KMS to re-establish authentication regularly according to your configured TTL, you limit how often you need to call back to KMS to protect your data. This is a performance/security tradeoff, where your authentication, audit, and logging from KMS is no longer one-to-one with every encrypt or decrypt call. However, the benefit is that you no longer have to make a network call to KMS for every encrypt or decrypt. Second, this key hierarchy makes it easy to hold multi-tenant data that is isolated per branch key in a single DynamoDb table. You can create a branch key for each tenant in your table, and encrypt all that tenant's data under that distinct branch key. On decrypt, you can either statically configure a single branch key to ensure you are restricting decryption to a single tenant, or you can implement an interface that lets you map the primary key on your items to the branch key that should be responsible for decrypting that data. This example then demonstrates configuring a Hierarchical Keyring with a Branch Key ID Supplier to encrypt and decrypt data for two separate tenants. Running this example requires access to the DDB Table whose name is provided in CLI arguments. This table must be configured with the following primary key configuration: - Partition key is named "partition_key" with type (S) - Sort key is named "sort_key" with type (S) This example also requires using a KMS Key whose ARN is provided in CLI arguments. You need the following access on this key: - GenerateDataKeyWithoutPlaintext - Decrypt */ public class HierarchicalKeyringExample { public static void HierarchicalKeyringGetItemPutItem( String ddbTableName, String tenant1BranchKeyId, String tenant2BranchKeyId, String keyStoreTableName, String logicalKeyStoreName, String kmsKeyId) { // Initial KeyStore Setup: This example requires that you have already // created your KeyStore, and have populated it with two new branch keys. // See the "Create KeyStore Table Example" and "Create KeyStore Key Example" // for an example of how to do this. // 1. Configure your KeyStore resource. // This SHOULD be the same configuration that you used // to initially create and populate your KeyStore. final KeyStore keystore = KeyStore.builder().KeyStoreConfig( KeyStoreConfig.builder() .ddbClient(DynamoDbClient.create()) .ddbTableName(keyStoreTableName) .logicalKeyStoreName(logicalKeyStoreName) .kmsClient(KmsClient.create()) .kmsConfiguration(KMSConfiguration.builder() .kmsKeyArn(kmsKeyId) .build()) .build()).build(); // 2. Create a Branch Key ID Supplier. See ExampleBranchKeyIdSupplier in this directory. final DynamoDbEncryption ddbEnc = DynamoDbEncryption.builder() .DynamoDbEncryptionConfig(DynamoDbEncryptionConfig.builder().build()) .build(); final IBranchKeyIdSupplier branchKeyIdSupplier = ddbEnc.CreateDynamoDbEncryptionBranchKeyIdSupplier( CreateDynamoDbEncryptionBranchKeyIdSupplierInput.builder() .ddbKeyBranchKeyIdSupplier(new ExampleBranchKeyIdSupplier(tenant1BranchKeyId, tenant2BranchKeyId)) .build()).branchKeyIdSupplier(); // 3. Create the Hierarchical Keyring, using the Branch Key ID Supplier above. // With this configuration, the AWS SDK Client ultimately configured will be capable // of encrypting or decrypting items for either tenant (assuming correct KMS access). // If you want to restrict the client to only encrypt or decrypt for a single tenant, // configure this Hierarchical Keyring using `.branchKeyId(tenant1BranchKeyId)` instead // of `.branchKeyIdSupplier(branchKeyIdSupplier)`. final MaterialProviders matProv = MaterialProviders.builder() .MaterialProvidersConfig(MaterialProvidersConfig.builder().build()) .build(); final CreateAwsKmsHierarchicalKeyringInput keyringInput = CreateAwsKmsHierarchicalKeyringInput.builder() .keyStore(keystore) .branchKeyIdSupplier(branchKeyIdSupplier) .ttlSeconds(600) // This dictates how often we call back to KMS to authorize use of the branch keys .cache(CacheType.builder() .Default(DefaultCache.builder() .entryCapacity(100) .build()) .build()) // This dictates how many branch keys will be held locally .build(); final IKeyring hierarchicalKeyring = matProv.CreateAwsKmsHierarchicalKeyring(keyringInput); // 4. Configure which attributes are encrypted and/or signed when writing new items. // For each attribute that may exist on the items we plan to write to our DynamoDbTable, // we must explicitly configure how they should be treated during item encryption: // - ENCRYPT_AND_SIGN: The attribute is encrypted and included in the signature // - SIGN_ONLY: The attribute not encrypted, but is still included in the signature // - DO_NOTHING: The attribute is not encrypted and not included in the signature final Map<String, CryptoAction> attributeActionsOnEncrypt = new HashMap<>(); attributeActionsOnEncrypt.put("partition_key", CryptoAction.SIGN_ONLY); // Our partition attribute must be SIGN_ONLY attributeActionsOnEncrypt.put("sort_key", CryptoAction.SIGN_ONLY); // Our sort attribute must be SIGN_ONLY attributeActionsOnEncrypt.put("tenant_sensitive_data", CryptoAction.ENCRYPT_AND_SIGN); // 5. Configure which attributes we expect to be included in the signature // when reading items. There are two options for configuring this: // // - (Recommended) Configure `allowedUnsignedAttributesPrefix`: // When defining your DynamoDb schema and deciding on attribute names, // choose a distinguishing prefix (such as ":") for all attributes that // you do not want to include in the signature. // This has two main benefits: // - It is easier to reason about the security and authenticity of data within your item // when all unauthenticated data is easily distinguishable by their attribute name. // - If you need to add new unauthenticated attributes in the future, // you can easily make the corresponding update to your `attributeActionsOnEncrypt` // and immediately start writing to that new attribute, without // any other configuration update needed. // Once you configure this field, it is not safe to update it. // // - Configure `allowedUnsignedAttributes`: You may also explicitly list // a set of attributes that should be considered unauthenticated when encountered // on read. Be careful if you use this configuration. Do not remove an attribute // name from this configuration, even if you are no longer writing with that attribute, // as old items may still include this attribute, and our configuration needs to know // to continue to exclude this attribute from the signature scope. // If you add new attribute names to this field, you must first deploy the update to this // field to all readers in your host fleet before deploying the update to start writing // with that new attribute. // // For this example, we currently authenticate all attributes. To make it easier to // add unauthenticated attributes in the future, we define a prefix ":" for such attributes. final String unsignAttrPrefix = ":"; // 6. Create the DynamoDb Encryption configuration for the table we will be writing to. final Map<String, DynamoDbTableEncryptionConfig> tableConfigs = new HashMap<>(); final DynamoDbTableEncryptionConfig config = DynamoDbTableEncryptionConfig.builder() .logicalTableName(ddbTableName) .partitionKeyName("partition_key") .sortKeyName("sort_key") .attributeActionsOnEncrypt(attributeActionsOnEncrypt) .keyring(hierarchicalKeyring) .allowedUnsignedAttributePrefix(unsignAttrPrefix) .build(); tableConfigs.put(ddbTableName, config); // 7. Create the DynamoDb Encryption Interceptor DynamoDbEncryptionInterceptor encryptionInterceptor = DynamoDbEncryptionInterceptor.builder() .config(DynamoDbTablesEncryptionConfig.builder() .tableEncryptionConfigs(tableConfigs) .build()) .build(); // 8. Create a new AWS SDK DynamoDb client using the DynamoDb Encryption Interceptor above final DynamoDbClient ddb = DynamoDbClient.builder() .overrideConfiguration( ClientOverrideConfiguration.builder() .addExecutionInterceptor(encryptionInterceptor) .build()) .build(); // 9. Put an item into our table using the above client. // Before the item gets sent to DynamoDb, it will be encrypted // client-side, according to our configuration. // Because the item we are writing uses "tenantId1" as our partition value, // based on the code we wrote in the ExampleBranchKeySupplier, // `tenant1BranchKeyId` will be used to encrypt this item. final HashMap<String, AttributeValue> item = new HashMap<>(); item.put("partition_key", AttributeValue.builder().s("tenant1Id").build()); item.put("sort_key", AttributeValue.builder().n("0").build()); item.put("tenant_sensitive_data", AttributeValue.builder().s("encrypt and sign me!").build()); final PutItemRequest putRequest = PutItemRequest.builder() .tableName(ddbTableName) .item(item) .build(); final PutItemResponse putResponse = ddb.putItem(putRequest); // Demonstrate that PutItem succeeded assert 200 == putResponse.sdkHttpResponse().statusCode(); // 10. Get the item back from our table using the same client. // The client will decrypt the item client-side, and return // back the original item. // Because the returned item's partition value is "tenantId1", // based on the code we wrote in the ExampleBranchKeySupplier, // `tenant1BranchKeyId` will be used to decrypt this item. final HashMap<String, AttributeValue> keyToGet = new HashMap<>(); keyToGet.put("partition_key", AttributeValue.builder().s("tenant1Id").build()); keyToGet.put("sort_key", AttributeValue.builder().n("0").build()); final GetItemRequest getRequest = GetItemRequest.builder() .key(keyToGet) .tableName(ddbTableName) .build(); final GetItemResponse getResponse = ddb.getItem(getRequest); // Demonstrate that GetItem succeeded and returned the decrypted item assert 200 == getResponse.sdkHttpResponse().statusCode(); final Map<String, AttributeValue> returnedItem = getResponse.item(); assert returnedItem.get("tenant_sensitive_data").s().equals("encrypt and sign me!"); } public static void main(final String[] args) { if (args.length <= 0) { throw new IllegalArgumentException("To run this example, include the ddbTable, tenant1BranchKeyId, " + "tenant2BranchKeyId, keyStoreTableName, logicalKeyStoreName, and kmsKeyId in args"); } final String ddbTableName = args[0]; final String tenant1BranchKeyId = args[1]; final String tenant2BranchKeyId = args[2]; final String keyStoreTableName = args[3]; final String logicalKeyStoreName = args[4]; final String kmsKeyId = args[5]; HierarchicalKeyringGetItemPutItem(ddbTableName, tenant1BranchKeyId, tenant2BranchKeyId, keyStoreTableName, logicalKeyStoreName, kmsKeyId); } }
5,250
0
Create_ds/aws-database-encryption-sdk-dynamodb-java/Examples/runtimes/java/DynamoDbEncryption/src/main/java/software/amazon/cryptography/examples
Create_ds/aws-database-encryption-sdk-dynamodb-java/Examples/runtimes/java/DynamoDbEncryption/src/main/java/software/amazon/cryptography/examples/keyring/KmsRsaKeyringExample.java
package software.amazon.cryptography.examples.keyring; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.StringWriter; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Paths; import java.util.HashMap; import java.util.Map; import org.bouncycastle.util.io.pem.PemObject; import org.bouncycastle.util.io.pem.PemWriter; import software.amazon.awssdk.core.client.config.ClientOverrideConfiguration; import software.amazon.awssdk.services.dynamodb.DynamoDbClient; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; import software.amazon.awssdk.services.dynamodb.model.GetItemRequest; import software.amazon.awssdk.services.dynamodb.model.GetItemResponse; import software.amazon.awssdk.services.dynamodb.model.PutItemRequest; import software.amazon.awssdk.services.dynamodb.model.PutItemResponse; import software.amazon.awssdk.services.kms.KmsClient; import software.amazon.awssdk.services.kms.model.EncryptionAlgorithmSpec; import software.amazon.awssdk.services.kms.model.GetPublicKeyRequest; import software.amazon.awssdk.services.kms.model.GetPublicKeyResponse; import software.amazon.cryptography.dbencryptionsdk.dynamodb.DynamoDbEncryptionInterceptor; import software.amazon.cryptography.dbencryptionsdk.dynamodb.model.DynamoDbTableEncryptionConfig; import software.amazon.cryptography.dbencryptionsdk.dynamodb.model.DynamoDbTablesEncryptionConfig; import software.amazon.cryptography.dbencryptionsdk.structuredencryption.model.CryptoAction; import software.amazon.cryptography.materialproviders.IKeyring; import software.amazon.cryptography.materialproviders.MaterialProviders; import software.amazon.cryptography.materialproviders.model.CreateAwsKmsRsaKeyringInput; import software.amazon.cryptography.materialproviders.model.DBEAlgorithmSuiteId; import software.amazon.cryptography.materialproviders.model.MaterialProvidersConfig; /* This example sets up DynamoDb Encryption for the AWS SDK client using the KMS RSA Keyring. This keyring uses a KMS RSA key pair to encrypt and decrypt records. The client uses the downloaded public key to encrypt items it adds to the table. The keyring uses the private key to decrypt existing table items it retrieves, by calling KMS' decrypt API. Running this example requires access to the DDB Table whose name is provided in CLI arguments. This table must be configured with the following primary key configuration: - Partition key is named "partition_key" with type (S) - Sort key is named "sort_key" with type (S) This example also requires access to a KMS RSA key. Our tests provide a KMS RSA ARN that anyone can use, but you can also provide your own KMS RSA key. To use your own KMS RSA key, you must have either: - Its public key downloaded in a UTF-8 encoded PEM file - kms:GetPublicKey permissions on that key If you do not have the public key downloaded, running this example through its main method will download the public key for you by calling kms:GetPublicKey. You must also have kms:Decrypt permissions on the KMS RSA key. */ public class KmsRsaKeyringExample { private static String DEFAULT_EXAMPLE_RSA_PUBLIC_KEY_FILENAME = "KmsRsaKeyringExamplePublicKey.pem"; public static void KmsRsaKeyringGetItemPutItem(String ddbTableName, String rsaKeyArn, String rsaPublicKeyFilename) { // 1. Load UTF-8 encoded public key PEM file. // You may have an RSA public key file already defined. // If not, the main method in this class will call // the KMS RSA key, retrieve its public key, and store it // in a PEM file for example use. ByteBuffer publicKeyUtf8EncodedByteBuffer; try { publicKeyUtf8EncodedByteBuffer = ByteBuffer.wrap( Files.readAllBytes(Paths.get(rsaPublicKeyFilename))); } catch (IOException e) { throw new RuntimeException("IOException while reading public key from file", e); } // 2. Create a KMS RSA keyring. // This keyring takes in: // - kmsClient // - kmsKeyId: Must be an ARN representing a KMS RSA key // - publicKey: A ByteBuffer of a UTF-8 encoded PEM file representing the public // key for the key passed into kmsKeyId // - encryptionAlgorithm: Must be either RSAES_OAEP_SHA_256 or RSAES_OAEP_SHA_1 final MaterialProviders matProv = MaterialProviders.builder() .MaterialProvidersConfig(MaterialProvidersConfig.builder().build()) .build(); final CreateAwsKmsRsaKeyringInput createAwsKmsRsaKeyringInput = CreateAwsKmsRsaKeyringInput.builder() .kmsClient(KmsClient.create()) .kmsKeyId(rsaKeyArn) .publicKey(publicKeyUtf8EncodedByteBuffer) .encryptionAlgorithm(EncryptionAlgorithmSpec.RSAES_OAEP_SHA_256) .build(); IKeyring awsKmsRsaKeyring = matProv.CreateAwsKmsRsaKeyring(createAwsKmsRsaKeyringInput); // 3. Configure which attributes are encrypted and/or signed when writing new items. // For each attribute that may exist on the items we plan to write to our DynamoDbTable, // we must explicitly configure how they should be treated during item encryption: // - ENCRYPT_AND_SIGN: The attribute is encrypted and included in the signature // - SIGN_ONLY: The attribute not encrypted, but is still included in the signature // - DO_NOTHING: The attribute is not encrypted and not included in the signature final Map<String, CryptoAction> attributeActions = new HashMap<>(); attributeActions.put("partition_key", CryptoAction.SIGN_ONLY); // Our partition attribute must be SIGN_ONLY attributeActions.put("sort_key", CryptoAction.SIGN_ONLY); // Our sort attribute must be SIGN_ONLY attributeActions.put("sensitive_data", CryptoAction.ENCRYPT_AND_SIGN); // 4. Configure which attributes we expect to be included in the signature // when reading items. There are two options for configuring this: // // - (Recommended) Configure `allowedUnsignedAttributesPrefix`: // When defining your DynamoDb schema and deciding on attribute names, // choose a distinguishing prefix (such as ":") for all attributes that // you do not want to include in the signature. // This has two main benefits: // - It is easier to reason about the security and authenticity of data within your item // when all unauthenticated data is easily distinguishable by their attribute name. // - If you need to add new unauthenticated attributes in the future, // you can easily make the corresponding update to your `attributeActions` // and immediately start writing to that new attribute, without // any other configuration update needed. // Once you configure this field, it is not safe to update it. // // - Configure `allowedUnsignedAttributes`: You may also explicitly list // a set of attributes that should be considered unauthenticated when encountered // on read. Be careful if you use this configuration. Do not remove an attribute // name from this configuration, even if you are no longer writing with that attribute, // as old items may still include this attribute, and our configuration needs to know // to continue to exclude this attribute from the signature scope. // If you add new attribute names to this field, you must first deploy the update to this // field to all readers in your host fleet before deploying the update to start writing // with that new attribute. // // For this example, we currently authenticate all attributes. To make it easier to // add unauthenticated attributes in the future, we define a prefix ":" for such attributes. final String unsignAttrPrefix = ":"; // 5. Create the DynamoDb Encryption configuration for the table we will be writing to. // Note: To use the KMS RSA keyring, your table config must specify an algorithmSuite // that does not use asymmetric signing. final Map<String, DynamoDbTableEncryptionConfig> tableConfigs = new HashMap<>(); final DynamoDbTableEncryptionConfig config = DynamoDbTableEncryptionConfig.builder() .logicalTableName(ddbTableName) .partitionKeyName("partition_key") .sortKeyName("sort_key") .attributeActionsOnEncrypt(attributeActions) .keyring(awsKmsRsaKeyring) .allowedUnsignedAttributePrefix(unsignAttrPrefix) // Specify algorithmSuite without asymmetric signing here // As of v3.0.0, the only supported algorithmSuite without asymmetric signing is // ALG_AES_256_GCM_HKDF_SHA512_COMMIT_KEY_SYMSIG_HMAC_SHA384. .algorithmSuiteId(DBEAlgorithmSuiteId.ALG_AES_256_GCM_HKDF_SHA512_COMMIT_KEY_SYMSIG_HMAC_SHA384) .build(); tableConfigs.put(ddbTableName, config); // 6. Create the DynamoDb Encryption Interceptor DynamoDbEncryptionInterceptor encryptionInterceptor = DynamoDbEncryptionInterceptor.builder() .config(DynamoDbTablesEncryptionConfig.builder() .tableEncryptionConfigs(tableConfigs) .build()) .build(); // 7. Create a new AWS SDK DynamoDb client using the DynamoDb Encryption Interceptor above final DynamoDbClient ddbClient = DynamoDbClient.builder() .overrideConfiguration( ClientOverrideConfiguration.builder() .addExecutionInterceptor(encryptionInterceptor) .build()) .build(); // 8. Put an item into our table using the above client. // Before the item gets sent to DynamoDb, it will be encrypted // client-side, according to our configuration. final HashMap<String, AttributeValue> item = new HashMap<>(); item.put("partition_key", AttributeValue.builder().s("awsKmsRsaKeyringItem").build()); item.put("sort_key", AttributeValue.builder().n("0").build()); item.put("sensitive_data", AttributeValue.builder().s("encrypt and sign me!").build()); final PutItemRequest putRequest = PutItemRequest.builder() .tableName(ddbTableName) .item(item) .build(); final PutItemResponse putResponse = ddbClient.putItem(putRequest); // Demonstrate that PutItem succeeded assert 200 == putResponse.sdkHttpResponse().statusCode(); // 9. Get the item back from our table using the client. // The client will decrypt the item client-side using the RSA keyring // and return the original item. final HashMap<String, AttributeValue> keyToGet = new HashMap<>(); keyToGet.put("partition_key", AttributeValue.builder().s("awsKmsRsaKeyringItem").build()); keyToGet.put("sort_key", AttributeValue.builder().n("0").build()); final GetItemRequest getRequest = GetItemRequest.builder() .key(keyToGet) .tableName(ddbTableName) .build(); final GetItemResponse getResponse = ddbClient.getItem(getRequest); // Demonstrate that GetItem succeeded and returned the decrypted item assert 200 == getResponse.sdkHttpResponse().statusCode(); final Map<String, AttributeValue> returnedItem = getResponse.item(); assert returnedItem.get("sensitive_data").s().equals("encrypt and sign me!"); } public static void KmsRsaKeyringGetItemPutItem(String ddbTableName, String rsaKeyArn) { KmsRsaKeyringGetItemPutItem(ddbTableName, rsaKeyArn, DEFAULT_EXAMPLE_RSA_PUBLIC_KEY_FILENAME); } public static void main(final String[] args) { if (args.length <= 1) { throw new IllegalArgumentException("To run this example, include the ddbTable and rsaKeyArn in args; optionally include rsaPublicKeyFilename"); } final String ddbTableName = args[0]; final String rsaKeyArn = args[1]; String rsaPublicKeyFilename; if (args.length == 3) { rsaPublicKeyFilename = args[2]; } else { rsaPublicKeyFilename = DEFAULT_EXAMPLE_RSA_PUBLIC_KEY_FILENAME; } // You may provide your own RSA public key at EXAMPLE_RSA_PUBLIC_KEY_FILENAME. // This must be the public key for the RSA key represented at rsaKeyArn. // If this file is not present, this will write a UTF-8 encoded PEM file for you. if (shouldGetNewPublicKey(rsaPublicKeyFilename)) { writePublicKeyPemForRsaKey(rsaKeyArn, rsaPublicKeyFilename); } KmsRsaKeyringGetItemPutItem(ddbTableName, rsaKeyArn, rsaPublicKeyFilename); } static boolean shouldGetNewPublicKey() { return shouldGetNewPublicKey(DEFAULT_EXAMPLE_RSA_PUBLIC_KEY_FILENAME); } static boolean shouldGetNewPublicKey(String rsaPublicKeyFilename) { // Check if a public key file already exists File publicKeyFile = new File(rsaPublicKeyFilename); // If a public key file already exists: do not overwrite existing file if (publicKeyFile.exists()) { return false; } // If file is not present, generate a new key pair return true; } static void writePublicKeyPemForRsaKey(String rsaKeyArn) { writePublicKeyPemForRsaKey(rsaKeyArn, DEFAULT_EXAMPLE_RSA_PUBLIC_KEY_FILENAME); } static void writePublicKeyPemForRsaKey(String rsaKeyArn, String rsaPublicKeyFilename) { // Safety check: Validate file is not present File publicKeyFile = new File(rsaPublicKeyFilename); if (publicKeyFile.exists()) { throw new IllegalStateException("getRsaPublicKey will not overwrite existing PEM files"); } // This code will call KMS to get the public key for the KMS RSA key. // You must have kms:GetPublicKey permissions on the key for this to succeed. // The public key will be written to the file EXAMPLE_RSA_PUBLIC_KEY_FILENAME. KmsClient getterForPublicKey = KmsClient.create(); GetPublicKeyResponse response = getterForPublicKey.getPublicKey(GetPublicKeyRequest.builder() .keyId(rsaKeyArn) .build()); byte[] publicKeyByteArray = response.publicKey().asByteArray(); StringWriter publicKeyStringWriter = new StringWriter(); PemWriter publicKeyPemWriter = new PemWriter(publicKeyStringWriter); try { publicKeyPemWriter.writeObject( new PemObject("PUBLIC KEY", publicKeyByteArray)); publicKeyPemWriter.close(); } catch (IOException e) { throw new RuntimeException("IOException while writing public key PEM", e); } ByteBuffer publicKeyUtf8EncodedByteBufferToWrite = StandardCharsets.UTF_8.encode(publicKeyStringWriter.toString()); try { FileChannel fc = new FileOutputStream(rsaPublicKeyFilename).getChannel(); fc.write(publicKeyUtf8EncodedByteBufferToWrite); fc.close(); } catch (FileNotFoundException e) { throw new RuntimeException("FileNotFoundException while opening public key FileChannel", e); } catch (IOException e) { throw new RuntimeException("IOException while writing public key or closing FileChannel", e); } } }
5,251
0
Create_ds/aws-database-encryption-sdk-dynamodb-java/Examples/runtimes/java/DynamoDbEncryption/src/main/java/software/amazon/cryptography/examples
Create_ds/aws-database-encryption-sdk-dynamodb-java/Examples/runtimes/java/DynamoDbEncryption/src/main/java/software/amazon/cryptography/examples/keyring/MrkDiscoveryMultiKeyringExample.java
package software.amazon.cryptography.examples.keyring; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import software.amazon.awssdk.core.client.config.ClientOverrideConfiguration; import software.amazon.awssdk.services.dynamodb.DynamoDbClient; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; import software.amazon.awssdk.services.dynamodb.model.GetItemRequest; import software.amazon.awssdk.services.dynamodb.model.GetItemResponse; import software.amazon.awssdk.services.dynamodb.model.PutItemRequest; import software.amazon.awssdk.services.dynamodb.model.PutItemResponse; import software.amazon.cryptography.dbencryptionsdk.dynamodb.model.DynamoDbTableEncryptionConfig; import software.amazon.cryptography.dbencryptionsdk.dynamodb.model.DynamoDbTablesEncryptionConfig; import software.amazon.cryptography.dbencryptionsdk.structuredencryption.model.CryptoAction; import software.amazon.cryptography.materialproviders.IKeyring; import software.amazon.cryptography.materialproviders.MaterialProviders; import software.amazon.cryptography.materialproviders.model.CreateAwsKmsMrkDiscoveryMultiKeyringInput; import software.amazon.cryptography.materialproviders.model.CreateAwsKmsMrkMultiKeyringInput; import software.amazon.cryptography.materialproviders.model.DiscoveryFilter; import software.amazon.cryptography.materialproviders.model.MaterialProvidersConfig; import software.amazon.cryptography.dbencryptionsdk.dynamodb.DynamoDbEncryptionInterceptor; /* This example sets up a MRK discovery multi-keyring to decrypt data using the DynamoDB encryption client. A discovery keyring is not provided with any wrapping keys; instead, it recognizes the KMS key that was used to encrypt a data key, and asks KMS to decrypt with that KMS key. Discovery keyrings cannot be used to encrypt data. For more information on discovery keyrings, see https://docs.aws.amazon.com/encryption-sdk/latest/developer-guide/use-kms-keyring.html#kms-keyring-discovery This example encrypts an item using an MRK multi-keyring and puts the encrypted item to the configured DynamoDb table. Then, it gets the item from the table and decrypts it using the discovery keyring. Running this example requires access to the DDB Table whose name is provided in CLI arguments. This table must be configured with the following primary key configuration: - Partition key is named "partition_key" with type (S) - Sort key is named "sort_key" with type (S) */ public class MrkDiscoveryMultiKeyringExample { public static void MultiMrkDiscoveryKeyringGetItemPutItem(String ddbTableName, String keyArn, List<String> accountIds, List<String> regions) { // 1. Create a single MRK multi-keyring using the key arn. // Although this example demonstrates use of the MRK discovery multi-keyring, // a discovery keyring cannot be used to encrypt. So we will need to construct // a non-discovery keyring for this example to encrypt. For more information on MRK // multi-keyrings, see the MultiMrkKeyringExample in this directory. // Though this is an "MRK multi-keyring", we do not need to provide multiple keys, // and can use single-region KMS keys. We will provide a single key here; this // can be either an MRK or a single-region key. final MaterialProviders matProv = MaterialProviders.builder() .MaterialProvidersConfig(MaterialProvidersConfig.builder().build()) .build(); final CreateAwsKmsMrkMultiKeyringInput createAwsKmsMrkMultiKeyringInput = CreateAwsKmsMrkMultiKeyringInput.builder() .generator(keyArn) .build(); IKeyring encryptKeyring = matProv.CreateAwsKmsMrkMultiKeyring(createAwsKmsMrkMultiKeyringInput); // 2. Configure which attributes are encrypted and/or signed when writing new items. // For each attribute that may exist on the items we plan to write to our DynamoDbTable, // we must explicitly configure how they should be treated during item encryption: // - ENCRYPT_AND_SIGN: The attribute is encrypted and icncluded in the signature // - SIGN_ONLY: The attribute not encrypted, but is still included in the signature // - DO_NOTHING: The attribute is not encrypted and not included in the signature final Map<String, CryptoAction> attributeActionsOnEncrypt = new HashMap<>(); attributeActionsOnEncrypt.put("partition_key", CryptoAction.SIGN_ONLY); // Our partition attribute must be SIGN_ONLY attributeActionsOnEncrypt.put("sort_key", CryptoAction.SIGN_ONLY); // Our sort attribute must be SIGN_ONLY attributeActionsOnEncrypt.put("sensitive_data", CryptoAction.ENCRYPT_AND_SIGN); // 3. Configure which attributes we expect to be included in the signature // when reading items. There are two options for configuring this: // // - (Recommended) Configure `allowedUnsignedAttributesPrefix`: // When defining your DynamoDb schema and deciding on attribute names, // choose a distinguishing prefix (such as ":") for all attributes that // you do not want to include in the signature. // This has two main benefits: // - It is easier to reason about the security and authenticity of data within your item // when all unauthenticated data is easily distinguishable by their attribute name. // - If you need to add new unauthenticated attributes in the future, // you can easily make the corresponding update to your `attributeActionsOnEncrypt` // and immediately start writing to that new attribute, without // any other configuration update needed. // Once you configure this field, it is not safe to update it. // // - Configure `allowedUnsignedAttributes`: You may also explicitly list // a set of attributes that should be considered unauthenticated when encountered // on read. Be careful if you use this configuration. Do not remove an attribute // name from this configuration, even if you are no longer writing with that attribute, // as old items may still include this attribute, and our configuration needs to know // to continue to exclude this attribute from the signature scope. // If you add new attribute names to this field, you must first deploy the update to this // field to all readers in your host fleet before deploying the update to start writing // with that new attribute. // // For this example, we currently authenticate all attributes. To make it easier to // add unauthenticated attributes in the future, we define a prefix ":" for such attributes. final String unsignAttrPrefix = ":"; // 4. Create the DynamoDb Encryption configuration for the table we will be writing to. final Map<String, DynamoDbTableEncryptionConfig> tableConfigs = new HashMap<>(); final DynamoDbTableEncryptionConfig config = DynamoDbTableEncryptionConfig.builder() .logicalTableName(ddbTableName) .partitionKeyName("partition_key") .sortKeyName("sort_key") .attributeActionsOnEncrypt(attributeActionsOnEncrypt) .keyring(encryptKeyring) .allowedUnsignedAttributePrefix(unsignAttrPrefix) .build(); tableConfigs.put(ddbTableName, config); // 5. Create the DynamoDb Encryption Interceptor DynamoDbEncryptionInterceptor encryptionInterceptor = DynamoDbEncryptionInterceptor.builder() .config(DynamoDbTablesEncryptionConfig.builder() .tableEncryptionConfigs(tableConfigs) .build()) .build(); // 6. Create a new AWS SDK DynamoDb client using the DynamoDb Encryption Interceptor above final DynamoDbClient ddbClient = DynamoDbClient.builder() .overrideConfiguration( ClientOverrideConfiguration.builder() .addExecutionInterceptor(encryptionInterceptor) .build()) .build(); // 7. Put an item into our table using the above client. // Before the item gets sent to DynamoDb, it will be encrypted // client-side using the MRK multi-keyring. final HashMap<String, AttributeValue> item = new HashMap<>(); item.put("partition_key", AttributeValue.builder().s("awsKmsMrkDiscoveryMultiKeyringItem").build()); item.put("sort_key", AttributeValue.builder().n("0").build()); item.put("sensitive_data", AttributeValue.builder().s("encrypt and sign me!").build()); final PutItemRequest putRequest = PutItemRequest.builder() .tableName(ddbTableName) .item(item) .build(); final PutItemResponse putResponse = ddbClient.putItem(putRequest); // Demonstrate that PutItem succeeded assert 200 == putResponse.sdkHttpResponse().statusCode(); // 8. Construct a discovery filter. // A discovery filter limits the set of encrypted data keys // the keyring can use to decrypt data. // We will only let the keyring use keys in the selected AWS accounts // and in the `aws` partition. // This is the suggested config for most users; for more detailed config, see // https://docs.aws.amazon.com/encryption-sdk/latest/developer-guide/use-kms-keyring.html#kms-keyring-discovery DiscoveryFilter discoveryFilter = DiscoveryFilter.builder() .partition("aws") .accountIds(accountIds) .build(); // 9. Construct a discovery keyring. // Note that we choose to use the MRK discovery multi-keyring, even though // our original keyring used a single KMS key. CreateAwsKmsMrkDiscoveryMultiKeyringInput createAwsKmsMrkDiscoveryMultiKeyringInput = CreateAwsKmsMrkDiscoveryMultiKeyringInput.builder() .discoveryFilter(discoveryFilter) .regions(regions) .build(); IKeyring decryptKeyring = matProv.CreateAwsKmsMrkDiscoveryMultiKeyring( createAwsKmsMrkDiscoveryMultiKeyringInput); // 10. Create new DDB config and client using the decrypt discovery keyring. // This is the same as the above config, except we pass in the decrypt keyring. final Map<String, DynamoDbTableEncryptionConfig> tableConfigsForDecrypt = new HashMap<>(); final DynamoDbTableEncryptionConfig configForDecrypt = DynamoDbTableEncryptionConfig.builder() .logicalTableName(ddbTableName) .partitionKeyName("partition_key") .sortKeyName("sort_key") .attributeActionsOnEncrypt(attributeActionsOnEncrypt) // Add decrypt keyring here .keyring(decryptKeyring) .allowedUnsignedAttributePrefix(unsignAttrPrefix) .build(); tableConfigsForDecrypt.put(ddbTableName, configForDecrypt); DynamoDbEncryptionInterceptor encryptionInterceptorForDecrypt = DynamoDbEncryptionInterceptor.builder() .config(DynamoDbTablesEncryptionConfig.builder() .tableEncryptionConfigs(tableConfigsForDecrypt) .build()) .build(); final DynamoDbClient ddbClientForDecrypt = DynamoDbClient.builder() .overrideConfiguration( ClientOverrideConfiguration.builder() .addExecutionInterceptor(encryptionInterceptorForDecrypt) .build()) .build(); // 11. Get the item back from our table using the client. // The client will retrieve encrypted items from the DDB table, then // detect the KMS key that was used to encrypt their data keys. // The client will make a request to KMS to decrypt with the encrypting KMS key. // If the client has permission to decrypt with the KMS key, // the client will decrypt the item client-side using the keyring // and return the original item. final HashMap<String, AttributeValue> keyToGet = new HashMap<>(); keyToGet.put("partition_key", AttributeValue.builder().s("awsKmsMrkDiscoveryMultiKeyringItem").build()); keyToGet.put("sort_key", AttributeValue.builder().n("0").build()); final GetItemRequest getRequest = GetItemRequest.builder() .key(keyToGet) .tableName(ddbTableName) .build(); final GetItemResponse getResponse = ddbClientForDecrypt.getItem(getRequest); // Demonstrate that GetItem succeeded and returned the decrypted item assert 200 == getResponse.sdkHttpResponse().statusCode(); final Map<String, AttributeValue> returnedItem = getResponse.item(); assert returnedItem.get("sensitive_data").s().equals("encrypt and sign me!"); } public static void main(final String[] args) { if (args.length <= 1) { throw new IllegalArgumentException("To run this example, include the ddbTable, mrkKeyArn, accounts, and region in args"); } final String ddbTableName = args[0]; final String mrkArn = args[1]; // We will assume only 1 AWS account and 1 region will be passed into args. // To add more of either, change this number, then pass them into args. int numberOfAwsAccounts = 1; int numberOfRegions = 1; List<String> accounts = new ArrayList<>(); int firstAccountIndex = 2; // 2 because args[0] is ddbTableName and args[1] is mrkArn for (int i = firstAccountIndex; i < firstAccountIndex + numberOfAwsAccounts; i++) { accounts.add(args[i]); } List<String> regions = new ArrayList<>(); int firstRegionIndex = firstAccountIndex + numberOfAwsAccounts; for (int i = firstRegionIndex; i < firstRegionIndex + numberOfRegions; i++) { regions.add(args[i]); } MultiMrkDiscoveryKeyringGetItemPutItem(ddbTableName, mrkArn, accounts, regions); } }
5,252
0
Create_ds/aws-database-encryption-sdk-dynamodb-java/Examples/runtimes/java/DynamoDbEncryption/src/main/java/software/amazon/cryptography/examples
Create_ds/aws-database-encryption-sdk-dynamodb-java/Examples/runtimes/java/DynamoDbEncryption/src/main/java/software/amazon/cryptography/examples/keyring/RawRsaKeyringExample.java
package software.amazon.cryptography.examples.keyring; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.StringWriter; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Paths; 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 org.bouncycastle.util.io.pem.PemObject; import org.bouncycastle.util.io.pem.PemWriter; import software.amazon.awssdk.core.client.config.ClientOverrideConfiguration; import software.amazon.awssdk.services.dynamodb.DynamoDbClient; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; import software.amazon.awssdk.services.dynamodb.model.GetItemRequest; import software.amazon.awssdk.services.dynamodb.model.GetItemResponse; import software.amazon.awssdk.services.dynamodb.model.PutItemRequest; import software.amazon.awssdk.services.dynamodb.model.PutItemResponse; import software.amazon.cryptography.dbencryptionsdk.dynamodb.model.DynamoDbTableEncryptionConfig; import software.amazon.cryptography.dbencryptionsdk.dynamodb.model.DynamoDbTablesEncryptionConfig; import software.amazon.cryptography.materialproviders.IKeyring; import software.amazon.cryptography.materialproviders.MaterialProviders; import software.amazon.cryptography.materialproviders.model.CreateRawRsaKeyringInput; import software.amazon.cryptography.materialproviders.model.MaterialProvidersConfig; import software.amazon.cryptography.materialproviders.model.PaddingScheme; import software.amazon.cryptography.dbencryptionsdk.structuredencryption.model.CryptoAction; import software.amazon.cryptography.dbencryptionsdk.dynamodb.DynamoDbEncryptionInterceptor; /* This example sets up DynamoDb Encryption for the AWS SDK client using the raw RSA Keyring. This keyring uses an RSA key pair to encrypt and decrypt records. This keyring accepts PEM encodings of the key pair as UTF-8 interpreted bytes. The client uses the public key to encrypt items it adds to the table and uses the private key to decrypt existing table items it retrieves. This example loads a key pair from PEM files with paths defined in - EXAMPLE_RSA_PRIVATE_KEY_FILENAME - EXAMPLE_RSA_PUBLIC_KEY_FILENAME If you do not provide these files, running this example through this class' main method will generate these files for you. These files will be generated in the directory where the example is run. In practice, users of this library should not generate new key pairs like this, and should instead retrieve an existing key from a secure key management system (e.g. an HSM). You may also provide your own key pair by placing PEM files in the directory where the example is run or modifying the paths in the code below. These files must be valid PEM encodings of the key pair as UTF-8 encoded bytes. If you do provide your own key pair, or if a key pair already exists, this class' main method will not generate a new key pair. This example loads a key pair from disk, encrypts a test item, and puts the encrypted item to the provided DynamoDb table. Then, it gets the item from the table and decrypts it. Running this example requires access to the DDB Table whose name is provided in CLI arguments. This table must be configured with the following primary key configuration: - Partition key is named "partition_key" with type (S) - Sort key is named "sort_key" with type (S) */ public class RawRsaKeyringExample { private static String EXAMPLE_RSA_PRIVATE_KEY_FILENAME = "RawRsaKeyringExamplePrivateKey.pem"; private static String EXAMPLE_RSA_PUBLIC_KEY_FILENAME = "RawRsaKeyringExamplePublicKey.pem"; public static void RawRsaKeyringGetItemPutItem(String ddbTableName) { // 1. Load key pair from UTF-8 encoded PEM files. // You may provide your own PEM files to use here. // If you do not, the main method in this class will generate PEM // files for example use. Do not use these files for any other purpose. ByteBuffer publicKeyUtf8EncodedByteBuffer; try { publicKeyUtf8EncodedByteBuffer = ByteBuffer.wrap( Files.readAllBytes(Paths.get(EXAMPLE_RSA_PUBLIC_KEY_FILENAME))); } catch (IOException e) { throw new RuntimeException("IOException while reading public key from file", e); } ByteBuffer privateKeyUtf8EncodedByteBuffer; try { privateKeyUtf8EncodedByteBuffer = ByteBuffer.wrap( Files.readAllBytes(Paths.get(EXAMPLE_RSA_PRIVATE_KEY_FILENAME))); } catch (IOException e) { throw new RuntimeException("IOException while reading private key from file", e); } // 2. Create the keyring. // The DynamoDb encryption client uses this to encrypt and decrypt items. final CreateRawRsaKeyringInput keyringInput = CreateRawRsaKeyringInput.builder() .keyName("my-rsa-key-name") .keyNamespace("my-key-namespace") .paddingScheme(PaddingScheme.OAEP_SHA256_MGF1) .publicKey(publicKeyUtf8EncodedByteBuffer) .privateKey(privateKeyUtf8EncodedByteBuffer) .build(); final MaterialProviders matProv = MaterialProviders.builder() .MaterialProvidersConfig(MaterialProvidersConfig.builder().build()) .build(); IKeyring rawRsaKeyring = matProv.CreateRawRsaKeyring(keyringInput); // 3. Configure which attributes are encrypted and/or signed when writing new items. // For each attribute that may exist on the items we plan to write to our DynamoDbTable, // we must explicitly configure how they should be treated during item encryption: // - ENCRYPT_AND_SIGN: The attribute is encrypted and included in the signature // - SIGN_ONLY: The attribute not encrypted, but is still included in the signature // - DO_NOTHING: The attribute is not encrypted and not included in the signature final Map<String, CryptoAction> attributeActionsOnEncrypt = new HashMap<>(); attributeActionsOnEncrypt.put("partition_key", CryptoAction.SIGN_ONLY); // Our partition attribute must be SIGN_ONLY attributeActionsOnEncrypt.put("sort_key", CryptoAction.SIGN_ONLY); // Our sort attribute must be SIGN_ONLY attributeActionsOnEncrypt.put("sensitive_data", CryptoAction.ENCRYPT_AND_SIGN); // 4. Configure which attributes we expect to be included in the signature // when reading items. There are two options for configuring this: // // - (Recommended) Configure `allowedUnsignedAttributesPrefix`: // When defining your DynamoDb schema and deciding on attribute names, // choose a distinguishing prefix (such as ":") for all attributes that // you do not want to include in the signature. // This has two main benefits: // - It is easier to reason about the security and authenticity of data within your item // when all unauthenticated data is easily distinguishable by their attribute name. // - If you need to add new unauthenticated attributes in the future, // you can easily make the corresponding update to your `attributeActionsOnEncrypt` // and immediately start writing to that new attribute, without // any other configuration update needed. // Once you configure this field, it is not safe to update it. // // - Configure `allowedUnsignedAttributes`: You may also explicitly list // a set of attributes that should be considered unauthenticated when encountered // on read. Be careful if you use this configuration. Do not remove an attribute // name from this configuration, even if you are no longer writing with that attribute, // as old items may still include this attribute, and our configuration needs to know // to continue to exclude this attribute from the signature scope. // If you add new attribute names to this field, you must first deploy the update to this // field to all readers in your host fleet before deploying the update to start writing // with that new attribute. // // For this example, we currently authenticate all attributes. To make it easier to // add unauthenticated attributes in the future, we define a prefix ":" for such attributes. final String unsignAttrPrefix = ":"; // 5. Create the DynamoDb Encryption configuration for the table we will be writing to. final Map<String, DynamoDbTableEncryptionConfig> tableConfigs = new HashMap<>(); final DynamoDbTableEncryptionConfig config = DynamoDbTableEncryptionConfig.builder() .logicalTableName(ddbTableName) .partitionKeyName("partition_key") .sortKeyName("sort_key") .attributeActionsOnEncrypt(attributeActionsOnEncrypt) .keyring(rawRsaKeyring) .allowedUnsignedAttributePrefix(unsignAttrPrefix) .build(); tableConfigs.put(ddbTableName, config); // 6. Create the DynamoDb Encryption Interceptor DynamoDbEncryptionInterceptor encryptionInterceptor = DynamoDbEncryptionInterceptor.builder() .config(DynamoDbTablesEncryptionConfig.builder() .tableEncryptionConfigs(tableConfigs) .build()) .build(); // 7. Create a new AWS SDK DynamoDb client using the DynamoDb Encryption Interceptor above final DynamoDbClient ddb = DynamoDbClient.builder() .overrideConfiguration( ClientOverrideConfiguration.builder() .addExecutionInterceptor(encryptionInterceptor) .build()) .build(); // 8. Put an item into our table using the above client. // Before the item gets sent to DynamoDb, it will be encrypted // client-side, according to our configuration. final HashMap<String, AttributeValue> item = new HashMap<>(); item.put("partition_key", AttributeValue.builder().s("rawRsaKeyringItem").build()); item.put("sort_key", AttributeValue.builder().n("0").build()); item.put("sensitive_data", AttributeValue.builder().s("encrypt and sign me!").build()); final PutItemRequest putRequest = PutItemRequest.builder() .tableName(ddbTableName) .item(item) .build(); final PutItemResponse putResponse = ddb.putItem(putRequest); // Demonstrate that PutItem succeeded assert 200 == putResponse.sdkHttpResponse().statusCode(); // 9. Get the item back from our table using the same client. // The client will decrypt the item client-side, and return // back the original item. final HashMap<String, AttributeValue> keyToGet = new HashMap<>(); keyToGet.put("partition_key", AttributeValue.builder().s("rawRsaKeyringItem").build()); keyToGet.put("sort_key", AttributeValue.builder().n("0").build()); final GetItemRequest getRequest = GetItemRequest.builder() .key(keyToGet) .tableName(ddbTableName) .build(); final GetItemResponse getResponse = ddb.getItem(getRequest); // Demonstrate that GetItem succeeded and returned the decrypted item assert 200 == getResponse.sdkHttpResponse().statusCode(); final Map<String, AttributeValue> returnedItem = getResponse.item(); assert returnedItem.get("sensitive_data").s().equals("encrypt and sign me!"); } public static void main(final String[] args) { if (args.length <= 0) { throw new IllegalArgumentException("To run this example, include the ddbTable in args"); } final String ddbTableName = args[0]; // You may provide your own RSA key pair in the files located at // - EXAMPLE_RSA_PRIVATE_KEY_FILENAME // - EXAMPLE_RSA_PUBLIC_KEY_FILENAME // If these files are not present, this will generate a pair for you if (shouldGenerateNewRsaKeyPair()) { generateRsaKeyPair(); } RawRsaKeyringGetItemPutItem(ddbTableName); } static boolean shouldGenerateNewRsaKeyPair() { // Check if a key pair already exists File privateKeyFile = new File(EXAMPLE_RSA_PRIVATE_KEY_FILENAME); File publicKeyFile = new File(EXAMPLE_RSA_PUBLIC_KEY_FILENAME); // If a key pair already exists: do not overwrite existing key pair if (privateKeyFile.exists() && publicKeyFile.exists()) { return false; } // If only one file is present: throw exception if (privateKeyFile.exists() && !publicKeyFile.exists()) { throw new IllegalStateException("Missing public key file at " + EXAMPLE_RSA_PUBLIC_KEY_FILENAME); } if (!privateKeyFile.exists() && publicKeyFile.exists()) { throw new IllegalStateException("Missing private key file at " + EXAMPLE_RSA_PRIVATE_KEY_FILENAME); } // If neither file is present, generate a new key pair return true; } static void generateRsaKeyPair() { // Safety check: Validate neither file is present File privateKeyFile = new File(EXAMPLE_RSA_PRIVATE_KEY_FILENAME); File publicKeyFile = new File(EXAMPLE_RSA_PUBLIC_KEY_FILENAME); if (privateKeyFile.exists() || publicKeyFile.exists()) { throw new IllegalStateException("generateRsaKeyPair will not overwrite existing PEM files"); } // This code will generate a new RSA key pair for example use. // The public and private key will be written to the files: // - public: EXAMPLE_RSA_PUBLIC_KEY_FILENAME // - private: EXAMPLE_RSA_PRIVATE_KEY_FILENAME // This example uses BouncyCastle's KeyPairGenerator to generate the key pair. // In practice, you should not generate this in your code, and should instead // retrieve this key from a secure key management system (e.g. HSM) // This key is created here for example purposes only. KeyPairGenerator rsaGen; try { rsaGen = KeyPairGenerator.getInstance("RSA"); } catch (NoSuchAlgorithmException e) { throw new RuntimeException("No such algorithm", e); } rsaGen.initialize(2048, new SecureRandom()); KeyPair keyPair = rsaGen.generateKeyPair(); StringWriter privateKeyStringWriter = new StringWriter(); PemWriter privateKeyPemWriter = new PemWriter(privateKeyStringWriter); try { privateKeyPemWriter.writeObject(new PemObject("PRIVATE KEY", keyPair.getPrivate().getEncoded())); privateKeyPemWriter.close(); } catch (IOException e) { throw new RuntimeException("IOException while writing private key PEM", e); } ByteBuffer privateKeyUtf8EncodedByteBuffer = StandardCharsets.UTF_8.encode(privateKeyStringWriter.toString()); // Write UTF-8 encoded PEM file try { FileChannel fc = new FileOutputStream(EXAMPLE_RSA_PRIVATE_KEY_FILENAME).getChannel(); fc.write(privateKeyUtf8EncodedByteBuffer); fc.close(); } catch (FileNotFoundException e) { throw new RuntimeException("FileNotFoundException while opening private key FileChannel", e); } catch (IOException e) { throw new RuntimeException("IOException while writing private key or closing FileChannel", e); } StringWriter publicKeyStringWriter = new StringWriter(); PemWriter publicKeyPemWriter = new PemWriter(publicKeyStringWriter); try { publicKeyPemWriter.writeObject( new PemObject("PUBLIC KEY", keyPair.getPublic().getEncoded())); publicKeyPemWriter.close(); } catch (IOException e) { throw new RuntimeException("IOException while writing public key PEM", e); } ByteBuffer publicKeyUtf8EncodedByteBuffer = StandardCharsets.UTF_8.encode(publicKeyStringWriter.toString()); try { FileChannel fc = new FileOutputStream(EXAMPLE_RSA_PUBLIC_KEY_FILENAME).getChannel(); fc.write(publicKeyUtf8EncodedByteBuffer); fc.close(); } catch (FileNotFoundException e) { throw new RuntimeException("FileNotFoundException while opening public key FileChannel", e); } catch (IOException e) { throw new RuntimeException("IOException while writing public key or closing FileChannel", e); } } }
5,253
0
Create_ds/aws-database-encryption-sdk-dynamodb-java/Examples/runtimes/java/DynamoDbEncryption/src/main/java/software/amazon/cryptography/examples
Create_ds/aws-database-encryption-sdk-dynamodb-java/Examples/runtimes/java/DynamoDbEncryption/src/main/java/software/amazon/cryptography/examples/enhanced/SimpleClass.java
package software.amazon.cryptography.examples.enhanced; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbAttribute; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbBean; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbPartitionKey; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbSortKey; import software.amazon.cryptography.dbencryptionsdk.dynamodb.enhancedclient.DynamoDbEncryptionDoNothing; import software.amazon.cryptography.dbencryptionsdk.dynamodb.enhancedclient.DynamoDbEncryptionSignOnly; /** * This class is used by the Enhanced Client Tests */ @DynamoDbBean public class SimpleClass { private String partitionKey; private int sortKey; private String attribute1; private String attribute2; private String attribute3; @DynamoDbPartitionKey @DynamoDbAttribute(value = "partition_key") public String getPartitionKey() { return this.partitionKey; } public void setPartitionKey(String partitionKey) { this.partitionKey = partitionKey; } @DynamoDbSortKey @DynamoDbAttribute(value = "sort_key") public int getSortKey() { return this.sortKey; } public void setSortKey(int sortKey) { this.sortKey = sortKey; } public String getAttribute1() { return this.attribute1; } public void setAttribute1(String attribute1) { this.attribute1 = attribute1; } @DynamoDbEncryptionSignOnly public String getAttribute2() { return this.attribute2; } public void setAttribute2(String attribute2) { this.attribute2 = attribute2; } @DynamoDbEncryptionDoNothing public String getAttribute3() { return this.attribute3; } @DynamoDbAttribute(value = ":attribute3") public void setAttribute3(String attribute3) { this.attribute3 = attribute3; } }
5,254
0
Create_ds/aws-database-encryption-sdk-dynamodb-java/Examples/runtimes/java/DynamoDbEncryption/src/main/java/software/amazon/cryptography/examples
Create_ds/aws-database-encryption-sdk-dynamodb-java/Examples/runtimes/java/DynamoDbEncryption/src/main/java/software/amazon/cryptography/examples/enhanced/EnhancedPutGetExample.java
package software.amazon.cryptography.examples.enhanced; import software.amazon.awssdk.core.client.config.ClientOverrideConfiguration; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClient; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbTable; import software.amazon.awssdk.enhanced.dynamodb.TableSchema; import software.amazon.awssdk.enhanced.dynamodb.model.GetItemEnhancedRequest; import software.amazon.awssdk.services.dynamodb.DynamoDbClient; import software.amazon.cryptography.materialproviders.IKeyring; import software.amazon.cryptography.materialproviders.MaterialProviders; import software.amazon.cryptography.materialproviders.model.CreateAwsKmsMrkMultiKeyringInput; import software.amazon.cryptography.materialproviders.model.DBEAlgorithmSuiteId; import software.amazon.cryptography.materialproviders.model.MaterialProvidersConfig; import software.amazon.cryptography.dbencryptionsdk.dynamodb.DynamoDbEncryptionInterceptor; import software.amazon.cryptography.dbencryptionsdk.dynamodb.enhancedclient.CreateDynamoDbEncryptionInterceptorInput; import software.amazon.cryptography.dbencryptionsdk.dynamodb.enhancedclient.DynamoDbEnhancedClientEncryption; import software.amazon.cryptography.dbencryptionsdk.dynamodb.enhancedclient.DynamoDbEnhancedTableEncryptionConfig; import software.amazon.awssdk.enhanced.dynamodb.Key; import java.util.HashMap; import java.util.Map; /* This example sets up DynamoDb Encryption for the DynamoDb Enhanced Client and uses the high level putItem() and getItem() APIs to demonstrate putting a client-side encrypted item into DynamoDb and then retrieving and decrypting that item from DynamoDb. Running this example requires access to the DDB Table whose name is provided in CLI arguments. This table must be configured with the following primary key configuration: - Partition key is named "partition_key" with type (S) - Sort key is named "sort_key" with type (S) */ public class EnhancedPutGetExample { public static void PutItemGetItem(String kmsKeyId, String ddbTableName) { // 1. Create a Keyring. This Keyring will be responsible for protecting the data keys that protect your data. // For this example, we will create a AWS KMS Keyring with the AWS KMS Key we want to use. // We will use the `CreateMrkMultiKeyring` method to create this keyring, // as it will correctly handle both single region and Multi-Region KMS Keys. final MaterialProviders matProv = MaterialProviders.builder() .MaterialProvidersConfig(MaterialProvidersConfig.builder().build()) .build(); final CreateAwsKmsMrkMultiKeyringInput keyringInput = CreateAwsKmsMrkMultiKeyringInput.builder() .generator(kmsKeyId) .build(); final IKeyring kmsKeyring = matProv.CreateAwsKmsMrkMultiKeyring(keyringInput); // 2. Create a Table Schema over your annotated class (See SimpleClass.java in this directory). // By default, all primary key attributes will be signed but not encrypted (SIGN_ONLY) // and all non-primary key attributes will be encrypted and signed (ENCRYPT_AND_SIGN). // If you want a particular non-primary key attribute to be signed but not encrypted, // use the `DynamoDbEncryptionSignOnly` annotation. // If you want a particular attribute to be neither signed nor encrypted (DO_NOTHING), // use the `DynamoDbEncryptionDoNothing` annotation. final TableSchema<SimpleClass> tableSchema = TableSchema.fromBean(SimpleClass.class); // 3. Configure which attributes we expect to be included in the signature // when reading items. There are two options for configuring this: // // - (Recommended) Configure `allowedUnsignedAttributesPrefix`: // When defining your DynamoDb schema and deciding on attribute names, // choose a distinguishing prefix (such as ":") for all attributes that // you do not want to include in the signature. // This has two main benefits: // - It is easier to reason about the security and authenticity of data within your item // when all unauthenticated data is easily distinguishable by their attribute name. // - If you need to add new unauthenticated attributes in the future, // you can immediately start writing to a new `DynamoDbEncryptionDoNothing` attribute // as long as it's name uses this prefix, without any other configuration update needed. // Once you configure this field, it is not safe to update it. // // - Configure `allowedUnsignedAttributes`: You may also explicitly list // a set of attributes that should be considered unauthenticated when encountered // on read. Be careful if you use this configuration. Do not remove an attribute // name from this configuration, even if you are no longer writing with that attribute, // as old items may still include this attribute, and our configuration needs to know // to continue to exclude this attribute from the signature scope. // If you add new attribute names to this field, you must first deploy the update to this // field to all readers in your host fleet before deploying the update to start writing // with that new attribute. // // For this example, we have designed our DynamoDb table such that any attribute name with // the ":" prefix should be considered unauthenticated. final String unsignAttrPrefix = ":"; // 4. Create the DynamoDb Encryption configuration for the table we will be writing to, final Map<String, DynamoDbEnhancedTableEncryptionConfig> tableConfigs = new HashMap<>(); tableConfigs.put(ddbTableName, DynamoDbEnhancedTableEncryptionConfig.builder() .logicalTableName(ddbTableName) .keyring(kmsKeyring) .allowedUnsignedAttributePrefix(unsignAttrPrefix) .schemaOnEncrypt(tableSchema) // Specifying an algorithm suite is not required, // but is done here to demonstrate how to do so. // We suggest using the // `ALG_AES_256_GCM_HKDF_SHA512_COMMIT_KEY_ECDSA_P384_SYMSIG_HMAC_SHA384` suite, // which includes AES-GCM with key derivation, signing, and key commitment. // This is also the default algorithm suite if one is not specified in this config. // For more information on supported algorithm suites, see: // https://docs.aws.amazon.com/database-encryption-sdk/latest/devguide/supported-algorithms.html .algorithmSuiteId( DBEAlgorithmSuiteId.ALG_AES_256_GCM_HKDF_SHA512_COMMIT_KEY_ECDSA_P384_SYMSIG_HMAC_SHA384) .build()); // 5. Create the DynamoDb Encryption Interceptor, using the DynamoDbEnhancedClientEncryption helper final DynamoDbEncryptionInterceptor encryptionInterceptor = DynamoDbEnhancedClientEncryption.CreateDynamoDbEncryptionInterceptor( CreateDynamoDbEncryptionInterceptorInput.builder() .tableEncryptionConfigs(tableConfigs) .build() ); // 6. Create a new AWS SDK DynamoDb client using the DynamoDb Encryption Interceptor above final DynamoDbClient ddb = DynamoDbClient.builder() .overrideConfiguration( ClientOverrideConfiguration.builder() .addExecutionInterceptor(encryptionInterceptor) .build()) .build(); // 7. Create the DynamoDbEnhancedClient using the AWS SDK Client created above, // and create a Table with your modelled class final DynamoDbEnhancedClient enhancedClient = DynamoDbEnhancedClient.builder() .dynamoDbClient(ddb) .build(); final DynamoDbTable<SimpleClass> table = enhancedClient.table(ddbTableName, tableSchema); // 8. Put an item into your table using the DynamoDb Enhanced Client. // The item will be encrypted client-side according to your // configuration above before it is sent to DynamoDb. final SimpleClass item = new SimpleClass(); item.setPartitionKey("EnhancedPutGetExample"); item.setSortKey(0); item.setAttribute1("encrypt and sign me!"); item.setAttribute2("sign me!"); item.setAttribute3("ignore me!"); table.putItem(item); // 9. Get the item back from the table using the DynamoDb Enhanced Client. // The item will be decrypted client-side, and you will get back the // original item. final Key key = Key.builder() .partitionValue("EnhancedPutGetExample").sortValue(0) .build(); final SimpleClass result = table.getItem( (GetItemEnhancedRequest.Builder requestBuilder) -> requestBuilder.key(key)); // Demonstrate we get the original item back assert result.getAttribute1().equals("encrypt and sign me!"); } public static void main(final String[] args) { if (args.length < 2) { throw new IllegalArgumentException("To run this example, include the kmsKeyId as args[0] and ddbTableName as args[1]"); } final String kmsKeyId = args[0]; final String ddbTableName = args[1]; PutItemGetItem(kmsKeyId, ddbTableName); } }
5,255
0
Create_ds/aws-database-encryption-sdk-dynamodb-java/Examples/runtimes/java/DynamoDbEncryption/src/main/java/software/amazon/cryptography/examples
Create_ds/aws-database-encryption-sdk-dynamodb-java/Examples/runtimes/java/DynamoDbEncryption/src/main/java/software/amazon/cryptography/examples/enhanced/LombokPutGetExample.java
package software.amazon.cryptography.examples.enhanced; import java.io.IOException; import java.util.HashMap; import java.util.Map; import java.util.Objects; import software.amazon.awssdk.core.client.config.ClientOverrideConfiguration; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClient; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbTable; import software.amazon.awssdk.enhanced.dynamodb.Key; import software.amazon.awssdk.enhanced.dynamodb.TableSchema; import software.amazon.awssdk.enhanced.dynamodb.model.GetItemEnhancedRequest; import software.amazon.awssdk.services.dynamodb.DynamoDbClient; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; import software.amazon.awssdk.services.dynamodb.model.GetItemRequest; import software.amazon.awssdk.services.dynamodb.model.GetItemResponse; import software.amazon.cryptography.dbencryptionsdk.dynamodb.DynamoDbEncryptionInterceptor; import software.amazon.cryptography.dbencryptionsdk.dynamodb.enhancedclient.CreateDynamoDbEncryptionInterceptorInput; import software.amazon.cryptography.dbencryptionsdk.dynamodb.enhancedclient.DynamoDbEnhancedClientEncryption; import software.amazon.cryptography.dbencryptionsdk.dynamodb.enhancedclient.DynamoDbEnhancedTableEncryptionConfig; import software.amazon.cryptography.dbencryptionsdk.dynamodb.itemencryptor.DynamoDbItemEncryptor; import software.amazon.cryptography.materialproviders.IKeyring; import software.amazon.cryptography.materialproviders.MaterialProviders; import software.amazon.cryptography.materialproviders.model.CreateAwsKmsMrkMultiKeyringInput; import software.amazon.cryptography.materialproviders.model.DBEAlgorithmSuiteId; import software.amazon.cryptography.materialproviders.model.MaterialProvidersConfig; import static software.amazon.cryptography.examples.ConfigUtils.fromEncryptionInterceptor; import static software.amazon.cryptography.examples.ManipulationUtils.assertManipulationProof; import static software.amazon.cryptography.examples.ManipulationUtils.assertNotManipulationProof; import static software.amazon.cryptography.examples.ManipulationUtils.assertProtectedByEncryptionContext; import static software.amazon.cryptography.examples.ManipulationUtils.manipulateByteAttribute; import static software.amazon.cryptography.examples.ManipulationUtils.manipulateNumberAttribute; import static software.amazon.cryptography.examples.ManipulationUtils.manipulateStringAttribute; /* This example sets up DynamoDb Encryption for the DynamoDb Enhanced Client and uses the high level putItem() and getItem() APIs to demonstrate putting a client-side encrypted item into DynamoDb and then retrieving and decrypting that item from DynamoDb. Running this example requires access to the DDB Table whose name is provided in CLI arguments. This table must be configured with the following primary key configuration: - Partition key is named "partition_key" with type (S) - Sort key is named "sort_key" with type (S) */ public class LombokPutGetExample { public static void PutItemGetItem(String kmsKeyId, String ddbTableName) { // 1. Create a Keyring. This Keyring will be responsible for protecting the data keys that protect your data. // For this example, we will create a AWS KMS Keyring with the AWS KMS Key we want to use. // We will use the `CreateMrkMultiKeyring` method to create this keyring, // as it will correctly handle both single region and Multi-Region KMS Keys. final MaterialProviders matProv = MaterialProviders.builder() .MaterialProvidersConfig(MaterialProvidersConfig.builder().build()) .build(); final CreateAwsKmsMrkMultiKeyringInput keyringInput = CreateAwsKmsMrkMultiKeyringInput.builder() .generator(kmsKeyId) .build(); final IKeyring kmsKeyring = matProv.CreateAwsKmsMrkMultiKeyring(keyringInput); // 2. Create a Table Schema over your annotated class (See SimpleViaLombok.java in this directory). // By default, all primary key attributes will be signed but not encrypted (SIGN_ONLY) // and all non-primary key attributes will be encrypted and signed (ENCRYPT_AND_SIGN). // If you want a particular non-primary key attribute to be signed but not encrypted, // use the `DynamoDbEncryptionSignOnly` annotation. // If you want a particular attribute to be neither signed nor encrypted (DO_NOTHING), // use the `DynamoDbEncryptionDoNothing` annotation. final TableSchema<SimpleViaLombok> tableSchema = TableSchema.fromImmutableClass(SimpleViaLombok.class); // 3. Configure which attributes we expect to be included in the signature // when reading items. There are two options for configuring this: // // - (Recommended) Configure `allowedUnsignedAttributesPrefix`: // When defining your DynamoDb schema and deciding on attribute names, // choose a distinguishing prefix (such as ":") for all attributes that // you do not want to include in the signature. // This has two main benefits: // - It is easier to reason about the security and authenticity of data within your item // when all unauthenticated data is easily distinguishable by their attribute name. // - If you need to add new unauthenticated attributes in the future, // you can immediately start writing to a new `DynamoDbEncryptionDoNothing` attribute // as long as it's name uses this prefix, without any other configuration update needed. // Once you configure this field, it is not safe to update it. // // - Configure `allowedUnsignedAttributes`: You may also explicitly list // a set of attributes that should be considered unauthenticated when encountered // on read. Be careful if you use this configuration. Do not remove an attribute // name from this configuration, even if you are no longer writing with that attribute, // as old items may still include this attribute, and our configuration needs to know // to continue to exclude this attribute from the signature scope. // If you add new attribute names to this field, you must first deploy the update to this // field to all readers in your host fleet before deploying the update to start writing // with that new attribute. // // For this example, we have designed our DynamoDb table such that any attribute name with // the ":" prefix should be considered unauthenticated. final String unsignAttrPrefix = ":"; // 4. Create the DynamoDb Encryption configuration for the table we will be writing to, final Map<String, DynamoDbEnhancedTableEncryptionConfig> tableConfigs = new HashMap<>(); tableConfigs.put(ddbTableName, DynamoDbEnhancedTableEncryptionConfig.builder() .logicalTableName(ddbTableName) .keyring(kmsKeyring) .allowedUnsignedAttributePrefix(unsignAttrPrefix) .schemaOnEncrypt(tableSchema) // Specifying an algorithm suite is not required, // but is done here to demonstrate how to do so. // We suggest using the // `ALG_AES_256_GCM_HKDF_SHA512_COMMIT_KEY_ECDSA_P384_SYMSIG_HMAC_SHA384` suite, // which includes AES-GCM with key derivation, signing, and key commitment. // This is also the default algorithm suite if one is not specified in this config. // For more information on supported algorithm suites, see: // https://docs.aws.amazon.com/database-encryption-sdk/latest/devguide/supported-algorithms.html .algorithmSuiteId( DBEAlgorithmSuiteId.ALG_AES_256_GCM_HKDF_SHA512_COMMIT_KEY_ECDSA_P384_SYMSIG_HMAC_SHA384) .build()); // 5. Create the DynamoDb Encryption Interceptor, using the DynamoDbEnhancedClientEncryption helper final DynamoDbEncryptionInterceptor encryptionInterceptor = DynamoDbEnhancedClientEncryption.CreateDynamoDbEncryptionInterceptor( CreateDynamoDbEncryptionInterceptorInput.builder() .tableEncryptionConfigs(tableConfigs) .build() ); // 6. Create a new AWS SDK DynamoDb client using the DynamoDb Encryption Interceptor above final DynamoDbClient ddb = DynamoDbClient.builder() .overrideConfiguration( ClientOverrideConfiguration.builder() .addExecutionInterceptor(encryptionInterceptor) .build()) .build(); // 7. Create the DynamoDbEnhancedClient using the AWS SDK Client created above, // and create a Table with your modelled class final DynamoDbEnhancedClient enhancedClient = DynamoDbEnhancedClient.builder() .dynamoDbClient(ddb) .build(); final DynamoDbTable<SimpleViaLombok> table = enhancedClient.table(ddbTableName, tableSchema); // 8. Put an item into your table using the DynamoDb Enhanced Client. // The item will be encrypted client-side according to your // configuration above before it is sent to DynamoDb. final SimpleViaLombok.SimpleViaLombokBuilder itemBuilder = SimpleViaLombok.builder(); itemBuilder.partitionKey("LombokPutGetExample"); itemBuilder.sortKey(0); itemBuilder.attribute1("encrypt and sign me!"); itemBuilder.attribute2("sign me!"); itemBuilder.attribute3("ignore me!"); SimpleViaLombok item = itemBuilder.build(); table.putItem(item); // 9. Get the item back from the table using the DynamoDb Enhanced Client. // The item will be decrypted client-side, and you will get back the // original item. final Key key = Key.builder() .partitionValue("LombokPutGetExample").sortValue(0) .build(); final SimpleViaLombok decrypted = table.getItem( (GetItemEnhancedRequest.Builder requestBuilder) -> requestBuilder.key(key)); // Demonstrate we get the original item back assert decrypted.getAttribute1().equals("encrypt and sign me!"); // Demonstrate without the Enhanced Client, the record is encrypted try (DynamoDbClient noEncryptionDdb = DynamoDbClient.builder().build()) { GetItemResponse response = noEncryptionDdb.getItem( (GetItemRequest.Builder requestBuilder) -> { requestBuilder.key(key.primaryKeyMap(tableSchema)); requestBuilder.tableName(ddbTableName); }); final Map<String, AttributeValue> itemDecrypted = response.item(); // Assert the Encrypted Field is in Bytes assert Objects.nonNull(itemDecrypted.get("attribute1").b()); // Assert the Encrypted Field is not a String assert Objects.isNull(itemDecrypted.get("attribute1").s()); // Assert the Signed Only Field is a String and is Equal to the input assert Objects.nonNull(itemDecrypted.get("attribute2").s()); assert itemDecrypted.get("attribute2").s().equals(item.getAttribute2()); // Assert the Not Signed, Not Encrypted Field is a String and is Equal to the input assert Objects.nonNull(response.item().get(":attribute3").s()); assert itemDecrypted.get(":attribute3").s().equals(item.getAttribute3()); // Verify the Signed Items are protected final DynamoDbItemEncryptor itemEncryptor = DynamoDbItemEncryptor.builder() .DynamoDbItemEncryptorConfig(fromEncryptionInterceptor(encryptionInterceptor, ddbTableName)) .build(); assertProtectedByEncryptionContext(itemEncryptor, manipulateStringAttribute(itemDecrypted, "partition_key"), "partition_key"); assertProtectedByEncryptionContext(itemEncryptor, manipulateNumberAttribute(itemDecrypted, "sort_key"), "sort_key"); assertManipulationProof(itemEncryptor, manipulateByteAttribute(itemDecrypted, "attribute1"), "attribute1"); assertManipulationProof(itemEncryptor, manipulateStringAttribute(itemDecrypted, "attribute2"), "attribute2"); assertNotManipulationProof(itemEncryptor, manipulateStringAttribute(itemDecrypted, ":attribute3"), ":attribute3"); } catch (IOException e) { throw new RuntimeException(e); } } public static void main(final String[] args) { if (args.length < 2) { throw new IllegalArgumentException("To run this example, include the kmsKeyId as args[0] and ddbTableName as args[1]"); } final String kmsKeyId = args[0]; final String ddbTableName = args[1]; PutItemGetItem(kmsKeyId, ddbTableName); } }
5,256
0
Create_ds/aws-database-encryption-sdk-dynamodb-java/Examples/runtimes/java/DynamoDbEncryption/src/main/java/software/amazon/cryptography/examples
Create_ds/aws-database-encryption-sdk-dynamodb-java/Examples/runtimes/java/DynamoDbEncryption/src/main/java/software/amazon/cryptography/examples/enhanced/SimpleViaLombok.java
package software.amazon.cryptography.examples.enhanced; import lombok.Builder; import lombok.Getter; import lombok.Value; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbAttribute; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbImmutable; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbPartitionKey; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbSortKey; import software.amazon.cryptography.dbencryptionsdk.dynamodb.enhancedclient.DynamoDbEncryptionDoNothing; import software.amazon.cryptography.dbencryptionsdk.dynamodb.enhancedclient.DynamoDbEncryptionSignOnly; @Value @Builder @DynamoDbImmutable(builder = SimpleViaLombok.SimpleViaLombokBuilder.class) public class SimpleViaLombok { @Getter(onMethod_= {@DynamoDbPartitionKey, @DynamoDbAttribute(value = "partition_key")}) String partitionKey; @Getter(onMethod_= {@DynamoDbSortKey, @DynamoDbAttribute(value = "sort_key")}) int sortKey; String attribute1; @Getter(onMethod_=@DynamoDbEncryptionSignOnly) String attribute2; @Getter(onMethod_= {@DynamoDbEncryptionDoNothing, @DynamoDbAttribute(value = ":attribute3")}) String attribute3; }
5,257
0
Create_ds/aws-database-encryption-sdk-dynamodb-java/Examples/runtimes/java/DynamoDbEncryption/src/main/java/software/amazon/cryptography/examples
Create_ds/aws-database-encryption-sdk-dynamodb-java/Examples/runtimes/java/DynamoDbEncryption/src/main/java/software/amazon/cryptography/examples/enhanced/TableSchemaBuilderPutGetExample.java
package software.amazon.cryptography.examples.enhanced; import java.io.IOException; import java.util.HashMap; import java.util.Map; import java.util.Objects; import software.amazon.awssdk.core.client.config.ClientOverrideConfiguration; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClient; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbTable; import software.amazon.awssdk.enhanced.dynamodb.Key; import software.amazon.awssdk.enhanced.dynamodb.TableSchema; import software.amazon.awssdk.enhanced.dynamodb.model.GetItemEnhancedRequest; import software.amazon.awssdk.services.dynamodb.DynamoDbClient; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; import software.amazon.awssdk.services.dynamodb.model.GetItemRequest; import software.amazon.awssdk.services.dynamodb.model.GetItemResponse; import software.amazon.cryptography.dbencryptionsdk.dynamodb.DynamoDbEncryptionInterceptor; import software.amazon.cryptography.dbencryptionsdk.dynamodb.enhancedclient.CreateDynamoDbEncryptionInterceptorInput; import software.amazon.cryptography.dbencryptionsdk.dynamodb.enhancedclient.DoNothingTag; import software.amazon.cryptography.dbencryptionsdk.dynamodb.enhancedclient.DynamoDbEnhancedClientEncryption; import software.amazon.cryptography.dbencryptionsdk.dynamodb.enhancedclient.DynamoDbEnhancedTableEncryptionConfig; import software.amazon.cryptography.dbencryptionsdk.dynamodb.enhancedclient.SignOnlyTag; import software.amazon.cryptography.dbencryptionsdk.dynamodb.itemencryptor.DynamoDbItemEncryptor; import software.amazon.cryptography.examples.ConfigUtils; import software.amazon.cryptography.materialproviders.IKeyring; import software.amazon.cryptography.materialproviders.MaterialProviders; import software.amazon.cryptography.materialproviders.model.CreateAwsKmsMrkMultiKeyringInput; import software.amazon.cryptography.materialproviders.model.DBEAlgorithmSuiteId; import software.amazon.cryptography.materialproviders.model.MaterialProvidersConfig; import static software.amazon.awssdk.enhanced.dynamodb.mapper.StaticAttributeTags.primaryPartitionKey; import static software.amazon.awssdk.enhanced.dynamodb.mapper.StaticAttributeTags.primarySortKey; import static software.amazon.cryptography.examples.ManipulationUtils.assertManipulationProof; import static software.amazon.cryptography.examples.ManipulationUtils.assertNotManipulationProof; import static software.amazon.cryptography.examples.ManipulationUtils.assertProtectedByEncryptionContext; import static software.amazon.cryptography.examples.ManipulationUtils.manipulateByteAttribute; import static software.amazon.cryptography.examples.ManipulationUtils.manipulateNumberAttribute; import static software.amazon.cryptography.examples.ManipulationUtils.manipulateStringAttribute; /* This example sets up DynamoDb Encryption for the DynamoDb Enhanced Client and uses the high level putItem() and getItem() APIs to demonstrate putting a client-side encrypted item into DynamoDb and then retrieving and decrypting that item from DynamoDb. Running this example requires access to the DDB Table whose name is provided in CLI arguments. This table must be configured with the following primary key configuration: - Partition key is named "partition_key" with type (S) - Sort key is named "sort_key" with type (S) */ public class TableSchemaBuilderPutGetExample { public static void PutItemGetItem(String kmsKeyId, String ddbTableName) { // 1. Create a Keyring. This Keyring will be responsible for protecting the data keys that protect your data. // For this example, we will create a AWS KMS Keyring with the AWS KMS Key we want to use. // We will use the `CreateMrkMultiKeyring` method to create this keyring, // as it will correctly handle both single region and Multi-Region KMS Keys. final MaterialProviders matProv = MaterialProviders.builder() .MaterialProvidersConfig(MaterialProvidersConfig.builder().build()) .build(); final CreateAwsKmsMrkMultiKeyringInput keyringInput = CreateAwsKmsMrkMultiKeyringInput.builder() .generator(kmsKeyId) .build(); final IKeyring kmsKeyring = matProv.CreateAwsKmsMrkMultiKeyring(keyringInput); // 2. Create a Table Schema Manually via the Table Schema Builder. // By default, all primary key attributes will be signed but not encrypted (SIGN_ONLY) // and all non-primary key attributes will be encrypted and signed (ENCRYPT_AND_SIGN). // If you want a particular non-primary key attribute to be signed but not encrypted, // use the `SignOnlyTag`. // If you want a particular attribute to be neither signed nor encrypted (DO_NOTHING), // use the `DoNothingTag`. final TableSchema<SimpleClass> tableSchema = TableSchema.builder(SimpleClass.class) .newItemSupplier(SimpleClass::new) .addAttribute(String.class, a -> a.name("partition_key") .getter(SimpleClass::getPartitionKey) .setter(SimpleClass::setPartitionKey) .tags(primaryPartitionKey())) .addAttribute(int.class, a -> a.name("sort_key") .getter(SimpleClass::getSortKey) .setter(SimpleClass::setSortKey) .tags(primarySortKey())) .addAttribute(String.class, a -> a.name("attribute1") .getter(SimpleClass::getAttribute1) .setter(SimpleClass::setAttribute1)) .addAttribute(String.class, a -> a.name("attribute2") .getter(SimpleClass::getAttribute2) .setter(SimpleClass::setAttribute2) .tags(new SignOnlyTag())) .addAttribute(String.class, a -> a.name(":attribute3") .getter(SimpleClass::getAttribute3) .setter(SimpleClass::setAttribute3) .tags(new DoNothingTag())) .build(); // 3. Configure which attributes we expect to be included in the signature // when reading items. There are two options for configuring this: // // - (Recommended) Configure `allowedUnsignedAttributesPrefix`: // When defining your DynamoDb schema and deciding on attribute names, // choose a distinguishing prefix (such as ":") for all attributes that // you do not want to include in the signature. // This has two main benefits: // - It is easier to reason about the security and authenticity of data within your item // when all unauthenticated data is easily distinguishable by their attribute name. // - If you need to add new unauthenticated attributes in the future, // you can immediately start writing to a new `DynamoDbEncryptionDoNothing` attribute // as long as it's name uses this prefix, without any other configuration update needed. // Once you configure this field, it is not safe to update it. // // - Configure `allowedUnsignedAttributes`: You may also explicitly list // a set of attributes that should be considered unauthenticated when encountered // on read. Be careful if you use this configuration. Do not remove an attribute // name from this configuration, even if you are no longer writing with that attribute, // as old items may still include this attribute, and our configuration needs to know // to continue to exclude this attribute from the signature scope. // If you add new attribute names to this field, you must first deploy the update to this // field to all readers in your host fleet before deploying the update to start writing // with that new attribute. // // For this example, we have designed our DynamoDb table such that any attribute name with // the ":" prefix should be considered unauthenticated. final String unsignAttrPrefix = ":"; // 4. Create the DynamoDb Encryption configuration for the table we will be writing to, final Map<String, DynamoDbEnhancedTableEncryptionConfig> tableConfigs = new HashMap<>(); tableConfigs.put(ddbTableName, DynamoDbEnhancedTableEncryptionConfig.builder() .logicalTableName(ddbTableName) .keyring(kmsKeyring) .allowedUnsignedAttributePrefix(unsignAttrPrefix) .schemaOnEncrypt(tableSchema) // Specifying an algorithm suite is not required, // but is done here to demonstrate how to do so. // We suggest using the // `ALG_AES_256_GCM_HKDF_SHA512_COMMIT_KEY_ECDSA_P384_SYMSIG_HMAC_SHA384` suite, // which includes AES-GCM with key derivation, signing, and key commitment. // This is also the default algorithm suite if one is not specified in this config. // For more information on supported algorithm suites, see: // https://docs.aws.amazon.com/database-encryption-sdk/latest/devguide/supported-algorithms.html .algorithmSuiteId( DBEAlgorithmSuiteId.ALG_AES_256_GCM_HKDF_SHA512_COMMIT_KEY_ECDSA_P384_SYMSIG_HMAC_SHA384) .build()); // 5. Create the DynamoDb Encryption Interceptor, using the DynamoDbEnhancedClientEncryption helper final DynamoDbEncryptionInterceptor encryptionInterceptor = DynamoDbEnhancedClientEncryption.CreateDynamoDbEncryptionInterceptor( CreateDynamoDbEncryptionInterceptorInput.builder() .tableEncryptionConfigs(tableConfigs) .build() ); // 6. Create a new AWS SDK DynamoDb client using the DynamoDb Encryption Interceptor above final DynamoDbClient ddb = DynamoDbClient.builder() .overrideConfiguration( ClientOverrideConfiguration.builder() .addExecutionInterceptor(encryptionInterceptor) .build()) .build(); // 7. Create the DynamoDbEnhancedClient using the AWS SDK Client created above, // and create a Table with your modelled class final DynamoDbEnhancedClient enhancedClient = DynamoDbEnhancedClient.builder() .dynamoDbClient(ddb) .build(); final DynamoDbTable<SimpleClass> table = enhancedClient.table(ddbTableName, tableSchema); // 8. Put an item into your table using the DynamoDb Enhanced Client. // The item will be encrypted client-side according to your // configuration above before it is sent to DynamoDb. final SimpleClass item = new SimpleClass(); item.setPartitionKey("TableSchemaBuilderPutGetExample"); item.setSortKey(0); item.setAttribute1("encrypt and sign me!"); item.setAttribute2("sign me!"); item.setAttribute3("ignore me!"); table.putItem(item); // 9. Get the item back from the table using the DynamoDb Enhanced Client. // The item will be decrypted client-side, and you will get back the // original item. final Key key = Key.builder() .partitionValue("TableSchemaBuilderPutGetExample").sortValue(0) .build(); final SimpleClass decrypted = table.getItem( (GetItemEnhancedRequest.Builder requestBuilder) -> requestBuilder.key(key)); // Demonstrate we get the original item back assert decrypted.getAttribute1().equals("encrypt and sign me!"); // Demonstrate, without the Enhanced Client, the record is encrypted try (DynamoDbClient noEncryptionDdb = DynamoDbClient.builder().build()) { GetItemResponse response = noEncryptionDdb.getItem( (GetItemRequest.Builder requestBuilder) -> { requestBuilder.key(key.primaryKeyMap(tableSchema)); requestBuilder.tableName(ddbTableName); }); final Map<String, AttributeValue> itemDecrypted = response.item(); // Assert the Encrypted Field is in Bytes assert Objects.nonNull(itemDecrypted.get("attribute1").b()); // Assert the Encrypted Field is not a String assert Objects.isNull(itemDecrypted.get("attribute1").s()); // Assert the Signed Only Field is a String and is Equal to the input assert Objects.nonNull(itemDecrypted.get("attribute2").s()); assert itemDecrypted.get("attribute2").s().equals(item.getAttribute2()); // Assert the Not Signed, Not Encrypted Field is a String and is Equal to the input assert Objects.nonNull(response.item().get(":attribute3").s()); assert itemDecrypted.get(":attribute3").s().equals(item.getAttribute3()); // Verify the Signed Items are protected final DynamoDbItemEncryptor itemEncryptor = DynamoDbItemEncryptor.builder() .DynamoDbItemEncryptorConfig(ConfigUtils.fromEncryptionInterceptor(encryptionInterceptor, ddbTableName)) .build(); assertProtectedByEncryptionContext(itemEncryptor, manipulateStringAttribute(itemDecrypted, "partition_key"), "partition_key"); assertProtectedByEncryptionContext(itemEncryptor, manipulateNumberAttribute(itemDecrypted, "sort_key"), "sort_key"); assertManipulationProof(itemEncryptor, manipulateByteAttribute(itemDecrypted, "attribute1"), "attribute1"); assertManipulationProof(itemEncryptor, manipulateStringAttribute(itemDecrypted, "attribute2"), "attribute2"); assertNotManipulationProof(itemEncryptor, manipulateStringAttribute(itemDecrypted, ":attribute3"), ":attribute3"); } catch (IOException e) { throw new RuntimeException(e); } } public static void main(final String[] args) { if (args.length < 2) { throw new IllegalArgumentException("To run this example, include the kmsKeyId as args[0] and ddbTableName as args[1]"); } final String kmsKeyId = args[0]; final String ddbTableName = args[1]; PutItemGetItem(kmsKeyId, ddbTableName); } }
5,258
0
Create_ds/aws-database-encryption-sdk-dynamodb-java/Examples/runtimes/java/DynamoDbEncryption/src/main/java/software/amazon/cryptography/examples
Create_ds/aws-database-encryption-sdk-dynamodb-java/Examples/runtimes/java/DynamoDbEncryption/src/main/java/software/amazon/cryptography/examples/itemencryptor/ItemEncryptDecryptExample.java
package software.amazon.cryptography.examples.itemencryptor; import software.amazon.awssdk.services.dynamodb.model.*; import software.amazon.cryptography.dbencryptionsdk.dynamodb.itemencryptor.DynamoDbItemEncryptor; import software.amazon.cryptography.dbencryptionsdk.dynamodb.itemencryptor.model.DecryptItemInput; import software.amazon.cryptography.dbencryptionsdk.dynamodb.itemencryptor.model.DynamoDbItemEncryptorConfig; import software.amazon.cryptography.dbencryptionsdk.dynamodb.itemencryptor.model.EncryptItemInput; import software.amazon.cryptography.materialproviders.IKeyring; import software.amazon.cryptography.materialproviders.MaterialProviders; import software.amazon.cryptography.materialproviders.model.CreateAwsKmsMrkMultiKeyringInput; import software.amazon.cryptography.materialproviders.model.DBEAlgorithmSuiteId; import software.amazon.cryptography.materialproviders.model.MaterialProvidersConfig; import software.amazon.cryptography.dbencryptionsdk.structuredencryption.model.CryptoAction; import java.util.HashMap; import java.util.Map; /* This example sets up a DynamoDb Item Encryptor and uses the EncryptItem and DecryptItem APIs to directly encrypt and decrypt an existing DynamoDb item. You should use the DynamoDb Item Encryptor if you already have a DynamoDb Item to encrypt or decrypt, and do not need to make a Put or Get call to DynamoDb. For example, if you are using DynamoDb Streams, you may already be working with an encrypted item obtained from DynamoDb, and want to directly decrypt the item. Running this example requires access to the DDB Table whose name is provided in CLI arguments. This table must be configured with the following primary key configuration: - Partition key is named "partition_key" with type (S) - Sort key is named "sort_key" with type (S) */ public class ItemEncryptDecryptExample { public static void PutItemGetItem(String kmsKeyId, String ddbTableName) { // 1. Create a Keyring. This Keyring will be responsible for protecting the data keys that protect your data. // For this example, we will create a AWS KMS Keyring with the AWS KMS Key we want to use. // We will use the `CreateMrkMultiKeyring` method to create this keyring, // as it will correctly handle both single region and Multi-Region KMS Keys. final MaterialProviders matProv = MaterialProviders.builder() .MaterialProvidersConfig(MaterialProvidersConfig.builder().build()) .build(); final CreateAwsKmsMrkMultiKeyringInput keyringInput = CreateAwsKmsMrkMultiKeyringInput.builder() .generator(kmsKeyId) .build(); final IKeyring kmsKeyring = matProv.CreateAwsKmsMrkMultiKeyring(keyringInput); // 2. Configure which attributes are encrypted and/or signed when writing new items. // For each attribute that may exist on the items we plan to write to our DynamoDbTable, // we must explicitly configure how they should be treated during item encryption: // - ENCRYPT_AND_SIGN: The attribute is encrypted and included in the signature // - SIGN_ONLY: The attribute not encrypted, but is still included in the signature // - DO_NOTHING: The attribute is not encrypted and not included in the signature final Map<String, CryptoAction> attributeActionsOnEncrypt = new HashMap<>(); attributeActionsOnEncrypt.put("partition_key", CryptoAction.SIGN_ONLY); // Our partition attribute must be SIGN_ONLY attributeActionsOnEncrypt.put("sort_key", CryptoAction.SIGN_ONLY); // Our sort attribute must be SIGN_ONLY attributeActionsOnEncrypt.put("attribute1", CryptoAction.ENCRYPT_AND_SIGN); attributeActionsOnEncrypt.put("attribute2", CryptoAction.SIGN_ONLY); attributeActionsOnEncrypt.put(":attribute3", CryptoAction.DO_NOTHING); // 3. Configure which attributes we expect to be included in the signature // when reading items. There are two options for configuring this: // // - (Recommended) Configure `allowedUnsignedAttributesPrefix`: // When defining your DynamoDb schema and deciding on attribute names, // choose a distinguishing prefix (such as ":") for all attributes that // you do not want to include in the signature. // This has two main benefits: // - It is easier to reason about the security and authenticity of data within your item // when all unauthenticated data is easily distinguishable by their attribute name. // - If you need to add new unauthenticated attributes in the future, // you can easily make the corresponding update to your `attributeActionsOnEncrypt` // and immediately start writing to that new attribute, without // any other configuration update needed. // Once you configure this field, it is not safe to update it. // // - Configure `allowedUnsignedAttributes`: You may also explicitly list // a set of attributes that should be considered unauthenticated when encountered // on read. Be careful if you use this configuration. Do not remove an attribute // name from this configuration, even if you are no longer writing with that attribute, // as old items may still include this attribute, and our configuration needs to know // to continue to exclude this attribute from the signature scope. // If you add new attribute names to this field, you must first deploy the update to this // field to all readers in your host fleet before deploying the update to start writing // with that new attribute. // // For this example, we have designed our DynamoDb table such that any attribute name with // the ":" prefix should be considered unauthenticated. final String unsignAttrPrefix = ":"; // 4. Create the configuration for the DynamoDb Item Encryptor final DynamoDbItemEncryptorConfig config = DynamoDbItemEncryptorConfig.builder() .logicalTableName(ddbTableName) .partitionKeyName("partition_key") .sortKeyName("sort_key") .attributeActionsOnEncrypt(attributeActionsOnEncrypt) .keyring(kmsKeyring) .allowedUnsignedAttributePrefix(unsignAttrPrefix) // Specifying an algorithm suite is not required, // but is done here to demonstrate how to do so. // We suggest using the // `ALG_AES_256_GCM_HKDF_SHA512_COMMIT_KEY_ECDSA_P384_SYMSIG_HMAC_SHA384` suite, // which includes AES-GCM with key derivation, signing, and key commitment. // This is also the default algorithm suite if one is not specified in this config. // For more information on supported algorithm suites, see: // https://docs.aws.amazon.com/database-encryption-sdk/latest/devguide/supported-algorithms.html .algorithmSuiteId( DBEAlgorithmSuiteId.ALG_AES_256_GCM_HKDF_SHA512_COMMIT_KEY_ECDSA_P384_SYMSIG_HMAC_SHA384) .build(); // 5. Create the DynamoDb Item Encryptor final DynamoDbItemEncryptor itemEncryptor = DynamoDbItemEncryptor.builder() .DynamoDbItemEncryptorConfig(config) .build(); // 6. Directly encrypt a DynamoDb item using the DynamoDb Item Encryptor final Map<String, AttributeValue> originalItem = new HashMap<>(); originalItem.put("partition_key", AttributeValue.builder().s("ItemEncryptDecryptExample").build()); originalItem.put("sort_key", AttributeValue.builder().n("0").build()); originalItem.put("attribute1", AttributeValue.builder().s("encrypt and sign me!").build()); originalItem.put("attribute2", AttributeValue.builder().s("sign me!").build()); originalItem.put(":attribute3", AttributeValue.builder().s("ignore me!").build()); final Map<String, AttributeValue> encryptedItem = itemEncryptor.EncryptItem( EncryptItemInput.builder() .plaintextItem(originalItem) .build() ).encryptedItem(); // Demonstrate that the item has been encrypted assert encryptedItem.get("partition_key").s().equals("ItemEncryptDecryptExample"); assert encryptedItem.get("sort_key").n().equals("0"); assert encryptedItem.get("attribute1").b() != null; // 7. Directly decrypt the encrypted item using the DynamoDb Item Encryptor final Map<String, AttributeValue> decryptedItem = itemEncryptor.DecryptItem( DecryptItemInput.builder() .encryptedItem(encryptedItem) .build() ).plaintextItem(); // Demonstrate that GetItem succeeded and returned the decrypted item assert decryptedItem.get("partition_key").s().equals("ItemEncryptDecryptExample"); assert decryptedItem.get("sort_key").n().equals("0"); assert decryptedItem.get("attribute1").s().equals("encrypt and sign me!"); } public static void main(final String[] args) { if (args.length < 2) { throw new IllegalArgumentException("To run this example, include the kmsKeyId as args[0] and ddbTableName as args[1]"); } final String kmsKeyId = args[0]; final String ddbTableName = args[1]; PutItemGetItem(kmsKeyId, ddbTableName); } }
5,259
0
Create_ds/aws-database-encryption-sdk-dynamodb-java/Examples/runtimes/java/DynamoDbEncryption/src/main/java/software/amazon/cryptography/examples
Create_ds/aws-database-encryption-sdk-dynamodb-java/Examples/runtimes/java/DynamoDbEncryption/src/main/java/software/amazon/cryptography/examples/clientsupplier/ClientSupplierExample.java
package software.amazon.cryptography.examples.clientsupplier; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import software.amazon.awssdk.core.client.config.ClientOverrideConfiguration; import software.amazon.awssdk.services.dynamodb.DynamoDbClient; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; import software.amazon.awssdk.services.dynamodb.model.GetItemRequest; import software.amazon.awssdk.services.dynamodb.model.GetItemResponse; import software.amazon.awssdk.services.dynamodb.model.PutItemRequest; import software.amazon.awssdk.services.dynamodb.model.PutItemResponse; import software.amazon.cryptography.dbencryptionsdk.dynamodb.model.DynamoDbTableEncryptionConfig; import software.amazon.cryptography.dbencryptionsdk.dynamodb.model.DynamoDbTablesEncryptionConfig; import software.amazon.cryptography.dbencryptionsdk.structuredencryption.model.CryptoAction; import software.amazon.cryptography.materialproviders.IKeyring; import software.amazon.cryptography.materialproviders.MaterialProviders; import software.amazon.cryptography.materialproviders.model.CreateAwsKmsMrkDiscoveryMultiKeyringInput; import software.amazon.cryptography.materialproviders.model.CreateAwsKmsMrkMultiKeyringInput; import software.amazon.cryptography.materialproviders.model.DiscoveryFilter; import software.amazon.cryptography.materialproviders.model.MaterialProvidersConfig; import software.amazon.cryptography.dbencryptionsdk.dynamodb.DynamoDbEncryptionInterceptor; /* This example sets up an MRK multi-keyring and an MRK discovery multi-keyring using a custom client supplier. A custom client supplier grants users access to more granular configuration aspects of their authentication details and KMS client. In this example, we create a simple custom client supplier that authenticates with a different IAM role based on the region of the KMS key. This example creates a MRK multi-keyring configured with a custom client supplier using a single MRK and puts an encrypted item to the table. Then, it creates a MRK discovery multi-keyring to decrypt the item and retrieves the item from the table. Running this example requires access to the DDB Table whose name is provided in CLI arguments. This table must be configured with the following primary key configuration: - Partition key is named "partition_key" with type (S) - Sort key is named "sort_key" with type (S) */ public class ClientSupplierExample { public static void ClientSupplierPutItemGetItem(String ddbTableName, String keyArn, List<String> accountIds, List<String> regions) { // 1. Create a single MRK multi-keyring. // This can be either a single-region KMS key or an MRK. // For this example to succeed, the key's region must either // 1) be in the regions list, or // 2) the key must be an MRK with a replica defined // in a region in the regions list, and the client // must have the correct permissions to access the replica. final MaterialProviders matProv = MaterialProviders.builder() .MaterialProvidersConfig(MaterialProvidersConfig.builder().build()) .build(); // Create the multi-keyring using our custom client supplier // defined in the RegionalRoleClientSupplier class in this directory. final CreateAwsKmsMrkMultiKeyringInput createAwsKmsMrkMultiKeyringInput = CreateAwsKmsMrkMultiKeyringInput.builder() // Note: RegionalRoleClientSupplier will internally use the keyArn's region // to retrieve the correct IAM role. .clientSupplier(new RegionalRoleClientSupplier()) .generator(keyArn) .build(); IKeyring mrkKeyringWithClientSupplier = matProv.CreateAwsKmsMrkMultiKeyring(createAwsKmsMrkMultiKeyringInput); // 2. Configure which attributes are encrypted and/or signed when writing new items. // For each attribute that may exist on the items we plan to write to our DynamoDbTable, // we must explicitly configure how they should be treated during item encryption: // - ENCRYPT_AND_SIGN: The attribute is encrypted and included in the signature // - SIGN_ONLY: The attribute is not encrypted, but is still included in the signature // - DO_NOTHING: The attribute is not encrypted and not included in the signature final Map<String, CryptoAction> attributeActionsOnEncrypt = new HashMap<>(); attributeActionsOnEncrypt.put("partition_key", CryptoAction.SIGN_ONLY); // Our partition attribute must be SIGN_ONLY attributeActionsOnEncrypt.put("sort_key", CryptoAction.SIGN_ONLY); // Our sort attribute must be SIGN_ONLY attributeActionsOnEncrypt.put("sensitive_data", CryptoAction.ENCRYPT_AND_SIGN); // 3. Configure which attributes we expect to be included in the signature // when reading items. There are two options for configuring this: // // - (Recommended) Configure `allowedUnsignedAttributesPrefix`: // When defining your DynamoDb schema and deciding on attribute names, // choose a distinguishing prefix (such as ":") for all attributes that // you do not want to include in the signature. // This has two main benefits: // - It is easier to reason about the security and authenticity of data within your item // when all unauthenticated data is easily distinguishable by their attribute name. // - If you need to add new unauthenticated attributes in the future, // you can easily make the corresponding update to your `attributeActionsOnEncrypt` // and immediately start writing to that new attribute, without // any other configuration update needed. // Once you configure this field, it is not safe to update it. // // - Configure `allowedUnsignedAttributes`: You may also explicitly list // a set of attributes that should be considered unauthenticated when encountered // on read. Be careful if you use this configuration. Do not remove an attribute // name from this configuration, even if you are no longer writing with that attribute, // as old items may still include this attribute, and our configuration needs to know // to continue to exclude this attribute from the signature scope. // If you add new attribute names to this field, you must first deploy the update to this // field to all readers in your host fleet before deploying the update to start writing // with that new attribute. // // For this example, we currently authenticate all attributes. To make it easier to // add unauthenticated attributes in the future, we define a prefix ":" for such attributes. final String unsignAttrPrefix = ":"; // 4. Create the DynamoDb Encryption configuration for the table we will be writing to. final Map<String, DynamoDbTableEncryptionConfig> tableConfigs = new HashMap<>(); final DynamoDbTableEncryptionConfig config = DynamoDbTableEncryptionConfig.builder() .logicalTableName(ddbTableName) .partitionKeyName("partition_key") .sortKeyName("sort_key") .attributeActionsOnEncrypt(attributeActionsOnEncrypt) .keyring(mrkKeyringWithClientSupplier) .allowedUnsignedAttributePrefix(unsignAttrPrefix) .build(); tableConfigs.put(ddbTableName, config); // 5. Create the DynamoDb Encryption Interceptor DynamoDbEncryptionInterceptor encryptionInterceptor = DynamoDbEncryptionInterceptor.builder() .config(DynamoDbTablesEncryptionConfig.builder() .tableEncryptionConfigs(tableConfigs) .build()) .build(); // 6. Create a new AWS SDK DynamoDb client using the DynamoDb Encryption Interceptor above final DynamoDbClient ddbClient = DynamoDbClient.builder() .overrideConfiguration( ClientOverrideConfiguration.builder() .addExecutionInterceptor(encryptionInterceptor) .build()) .build(); // 7. Put an item into our table using the above client. // Before the item gets sent to DynamoDb, it will be encrypted // client-side using the MRK multi-keyring. // The data key protecting this item will be encrypted // with all the KMS Keys in this keyring, so that it can be // decrypted with any one of those KMS Keys. final HashMap<String, AttributeValue> item = new HashMap<>(); item.put("partition_key", AttributeValue.builder().s("clientSupplierItem").build()); item.put("sort_key", AttributeValue.builder().n("0").build()); item.put("sensitive_data", AttributeValue.builder().s("encrypt and sign me!").build()); final PutItemRequest putRequest = PutItemRequest.builder() .tableName(ddbTableName) .item(item) .build(); final PutItemResponse putResponse = ddbClient.putItem(putRequest); // Demonstrate that PutItem succeeded assert 200 == putResponse.sdkHttpResponse().statusCode(); // 8. Get the item back from our table using the same keyring. // The client will decrypt the item client-side using the MRK // and return the original item. final HashMap<String, AttributeValue> keyToGet = new HashMap<>(); keyToGet.put("partition_key", AttributeValue.builder().s("clientSupplierItem").build()); keyToGet.put("sort_key", AttributeValue.builder().n("0").build()); final GetItemRequest getRequest = GetItemRequest.builder() .key(keyToGet) .tableName(ddbTableName) .build(); final GetItemResponse getResponse = ddbClient.getItem(getRequest); // Demonstrate that GetItem succeeded and returned the decrypted item assert 200 == getResponse.sdkHttpResponse().statusCode(); final Map<String, AttributeValue> returnedItem = getResponse.item(); assert returnedItem.get("sensitive_data").s().equals("encrypt and sign me!"); // 9. Create a MRK discovery multi-keyring with a custom client supplier. // A discovery MRK multi-keyring will be composed of // multiple discovery MRK keyrings, one for each region. // Each component keyring has its own KMS client in a particular region. // When we provide a client supplier to the multi-keyring, all component // keyrings will use that client supplier configuration. // In our tests, we make `keyArn` an MRK with a replica, and // provide only the replica region in our discovery filter. DiscoveryFilter discoveryFilter = DiscoveryFilter.builder() .partition("aws") .accountIds(accountIds) .build(); final CreateAwsKmsMrkDiscoveryMultiKeyringInput mrkDiscoveryClientSupplierInput = CreateAwsKmsMrkDiscoveryMultiKeyringInput.builder() .clientSupplier(new RegionalRoleClientSupplier()) .discoveryFilter(discoveryFilter) .regions(regions) .build(); IKeyring mrkDiscoveryClientSupplierKeyring = matProv.CreateAwsKmsMrkDiscoveryMultiKeyring( mrkDiscoveryClientSupplierInput); // 10. Create a new config and client using the discovery keyring. // This is the same setup as above, except we provide the discovery keyring to the config. final Map<String, DynamoDbTableEncryptionConfig> onlyReplicaKeyTableConfigs = new HashMap<>(); final DynamoDbTableEncryptionConfig onlyReplicaKeyConfig = DynamoDbTableEncryptionConfig.builder() .logicalTableName(ddbTableName) .partitionKeyName("partition_key") .sortKeyName("sort_key") .attributeActionsOnEncrypt(attributeActionsOnEncrypt) // Provide discovery keyring here .keyring(mrkDiscoveryClientSupplierKeyring) .allowedUnsignedAttributePrefix(unsignAttrPrefix) .build(); onlyReplicaKeyTableConfigs.put(ddbTableName, onlyReplicaKeyConfig); DynamoDbEncryptionInterceptor onlyReplicaKeyEncryptionInterceptor = DynamoDbEncryptionInterceptor.builder() .config(DynamoDbTablesEncryptionConfig.builder() .tableEncryptionConfigs(onlyReplicaKeyTableConfigs) .build()) .build(); final DynamoDbClient onlyReplicaKeyDdbClient = DynamoDbClient.builder() .overrideConfiguration( ClientOverrideConfiguration.builder() .addExecutionInterceptor(onlyReplicaKeyEncryptionInterceptor) .build()) .build(); // 11. Get the item back from our table using the discovery keyring client. // The client will decrypt the item client-side using the keyring, // and return the original item. // The discovery keyring will only use KMS keys in the provided regions and // AWS accounts. Since we have provided it with a custom client supplier // which uses different IAM roles based on the key region, // the discovery keyring will use a particular IAM role to decrypt // based on the region of the KMS key it uses to decrypt. final HashMap<String, AttributeValue> onlyReplicaKeyKeyToGet = new HashMap<>(); onlyReplicaKeyKeyToGet.put("partition_key", AttributeValue.builder().s("awsKmsMrkMultiKeyringItem").build()); onlyReplicaKeyKeyToGet.put("sort_key", AttributeValue.builder().n("0").build()); final GetItemRequest onlyReplicaKeyGetRequest = GetItemRequest.builder() .key(onlyReplicaKeyKeyToGet) .tableName(ddbTableName) .build(); final GetItemResponse onlyReplicaKeyGetResponse = onlyReplicaKeyDdbClient.getItem(onlyReplicaKeyGetRequest); // Demonstrate that GetItem succeeded and returned the decrypted item assert 200 == onlyReplicaKeyGetResponse.sdkHttpResponse().statusCode(); final Map<String, AttributeValue> onlyReplicaKeyReturnedItem = onlyReplicaKeyGetResponse.item(); assert onlyReplicaKeyReturnedItem.get("sensitive_data").s().equals("encrypt and sign me!"); } public static void main(final String[] args) { if (args.length <= 1) { throw new IllegalArgumentException("To run this example, include the ddbTable, keyArn, AWS accounts, and regions in args"); } final String ddbTableName = args[0]; final String keyArn = args[1]; // We will assume only 1 AWS account and 1 region will be passed into args. // To add more of either, change this number, then pass them into args. int numberOfAwsAccounts = 1; int numberOfRegions = 1; List<String> accounts = new ArrayList<>(); int firstAccountIndex = 2; // 2 because args[0] is ddbTableName and args[1] is mrkArn for (int i = firstAccountIndex; i < firstAccountIndex + numberOfAwsAccounts; i++) { accounts.add(args[i]); } List<String> regions = new ArrayList<>(); int firstRegionIndex = firstAccountIndex + numberOfAwsAccounts; for (int i = firstRegionIndex; i < firstRegionIndex + numberOfRegions; i++) { regions.add(args[i]); } ClientSupplierPutItemGetItem(ddbTableName, keyArn, accounts, regions); } }
5,260
0
Create_ds/aws-database-encryption-sdk-dynamodb-java/Examples/runtimes/java/DynamoDbEncryption/src/main/java/software/amazon/cryptography/examples
Create_ds/aws-database-encryption-sdk-dynamodb-java/Examples/runtimes/java/DynamoDbEncryption/src/main/java/software/amazon/cryptography/examples/clientsupplier/RegionalRoleClientSupplier.java
package software.amazon.cryptography.examples.clientsupplier; import software.amazon.awssdk.auth.credentials.AwsSessionCredentials; import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.kms.KmsClient; import software.amazon.awssdk.services.sts.model.AssumeRoleRequest; import software.amazon.awssdk.services.sts.model.Credentials; import software.amazon.cryptography.materialproviders.IClientSupplier; import software.amazon.awssdk.services.sts.StsClient; import software.amazon.cryptography.materialproviders.model.GetClientInput; /* Example class demonstrating an implementation of a custom client supplier. This particular implementation will create KMS clients with different IAM roles, depending on the region passed. */ public class RegionalRoleClientSupplier implements IClientSupplier { private static StsClient stsClient; private static RegionalRoleClientSupplierConfig config; public RegionalRoleClientSupplier() { stsClient = StsClient.create(); config = new RegionalRoleClientSupplierConfig(); } @Override public KmsClient GetClient(GetClientInput getClientInput) { if (!config.regionIamRoleMap.containsKey(getClientInput.region())) { throw new RuntimeException("Missing region"); } String arn = config.regionIamRoleMap.get(getClientInput.region()); Credentials creds = stsClient.assumeRole(AssumeRoleRequest.builder() .roleArn(arn) .durationSeconds(900) // 15 minutes is the minimum value .roleSessionName("Java-Client-Supplier-Example-Session") .build()).credentials(); return KmsClient.builder() .credentialsProvider( StaticCredentialsProvider.create( AwsSessionCredentials.create( creds.accessKeyId(), creds.secretAccessKey(), creds.sessionToken() ) ) ) .region(Region.of(getClientInput.region())) .build(); } }
5,261
0
Create_ds/aws-database-encryption-sdk-dynamodb-java/Examples/runtimes/java/DynamoDbEncryption/src/main/java/software/amazon/cryptography/examples
Create_ds/aws-database-encryption-sdk-dynamodb-java/Examples/runtimes/java/DynamoDbEncryption/src/main/java/software/amazon/cryptography/examples/clientsupplier/RegionalRoleClientSupplierConfig.java
package software.amazon.cryptography.examples.clientsupplier; import java.util.HashMap; import java.util.Map; import software.amazon.awssdk.regions.Region; /* Class containing config for the RegionalRoleClientSupplier. In your own code, this might be hardcoded, or reference an external source, e.g. environment variables or AWS AppConfig. */ public class RegionalRoleClientSupplierConfig { private static final String US_EAST_1_IAM_ROLE = "arn:aws:iam::370957321024:role/GitHub-CI-DDBEC-Dafny-Role-only-us-east-1-KMS-keys"; private static final String EU_WEST_1_IAM_ROLE = "arn:aws:iam::370957321024:role/GitHub-CI-DDBEC-Dafny-Role-only-eu-west-1-KMS-keys"; public Map<String, String> regionIamRoleMap; public RegionalRoleClientSupplierConfig() { regionIamRoleMap = new HashMap<>(); regionIamRoleMap.put(Region.US_EAST_1.id(), US_EAST_1_IAM_ROLE); regionIamRoleMap.put(Region.EU_WEST_1.id(), EU_WEST_1_IAM_ROLE); } }
5,262
0
Create_ds/aws-database-encryption-sdk-dynamodb-java/Examples/runtimes/java/DynamoDbEncryption/src/main/java/software/amazon/cryptography/examples
Create_ds/aws-database-encryption-sdk-dynamodb-java/Examples/runtimes/java/DynamoDbEncryption/src/main/java/software/amazon/cryptography/examples/searchableencryption/CompoundBeaconSearchableEncryptionExample.java
package software.amazon.cryptography.examples.searchableencryption; import java.util.ArrayList; import java.util.List; import java.util.HashMap; import java.util.Map; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import software.amazon.awssdk.core.client.config.ClientOverrideConfiguration; import software.amazon.awssdk.services.dynamodb.DynamoDbClient; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; import software.amazon.awssdk.services.dynamodb.model.PutItemRequest; import software.amazon.awssdk.services.dynamodb.model.PutItemResponse; import software.amazon.awssdk.services.dynamodb.model.QueryRequest; import software.amazon.awssdk.services.dynamodb.model.QueryResponse; import software.amazon.awssdk.services.kms.KmsClient; import software.amazon.cryptography.dbencryptionsdk.dynamodb.model.BeaconKeySource; import software.amazon.cryptography.dbencryptionsdk.dynamodb.model.BeaconVersion; import software.amazon.cryptography.dbencryptionsdk.dynamodb.model.CompoundBeacon; import software.amazon.cryptography.dbencryptionsdk.dynamodb.model.Constructor; import software.amazon.cryptography.dbencryptionsdk.dynamodb.model.ConstructorPart; import software.amazon.cryptography.dbencryptionsdk.dynamodb.model.DynamoDbTableEncryptionConfig; import software.amazon.cryptography.dbencryptionsdk.dynamodb.model.DynamoDbTablesEncryptionConfig; import software.amazon.cryptography.dbencryptionsdk.dynamodb.model.SearchConfig; import software.amazon.cryptography.dbencryptionsdk.dynamodb.model.EncryptedPart; import software.amazon.cryptography.dbencryptionsdk.dynamodb.model.SingleKeyStore; import software.amazon.cryptography.dbencryptionsdk.dynamodb.model.StandardBeacon; import software.amazon.cryptography.dbencryptionsdk.dynamodb.transforms.DynamoDbEncryptionTransforms; import software.amazon.cryptography.dbencryptionsdk.dynamodb.transforms.model.ResolveAttributesInput; import software.amazon.cryptography.dbencryptionsdk.dynamodb.transforms.model.ResolveAttributesOutput; import software.amazon.cryptography.keystore.KeyStore; import software.amazon.cryptography.keystore.model.CreateKeyOutput; import software.amazon.cryptography.keystore.model.KMSConfiguration; import software.amazon.cryptography.keystore.model.KeyStoreConfig; import software.amazon.cryptography.materialproviders.IKeyring; import software.amazon.cryptography.materialproviders.MaterialProviders; import software.amazon.cryptography.materialproviders.model.CreateAwsKmsHierarchicalKeyringInput; import software.amazon.cryptography.materialproviders.model.MaterialProvidersConfig; import software.amazon.cryptography.dbencryptionsdk.structuredencryption.model.CryptoAction; import software.amazon.cryptography.dbencryptionsdk.dynamodb.DynamoDbEncryptionInterceptor; /* This example demonstrates how to set up a compound beacon on encrypted attributes, put an item with the beacon, and query against that beacon. This example follows a use case of a database that stores unit inspection information. This is an extension of the "BasicSearchableEncryptionExample" in this directory. This example uses the same situation (storing unit inspection information) and the same table schema. However, this example uses a different Global Secondary Index (GSI) that is based on a compound beacon configuration composed of the `last4` and `unit` attributes. Running this example requires access to a DDB table with the following key configuration: - Partition key is named "work_id" with type (S) - Sort key is named "inspection_time" with type (S) This table must have a Global Secondary Index (GSI) configured named "last4UnitCompound-index": - Partition key is named "aws_dbe_b_last4UnitCompound" with type (S) In this example for storing unit inspection information, this schema is utilized for the data: - "work_id" stores a unique identifier for a unit inspection work order (v4 UUID) - "inspection_date" stores an ISO 8601 date for the inspection (YYYY-MM-DD) - "inspector_id_last4" stores the last 4 digits of the ID of the inspector performing the work - "unit" stores a 12-digit serial number for the unit being inspected The example requires the following ordered input command line parameters: 1. DDB table name for table to put/query data from 2. Branch key ID for a branch key that was previously created in your key store. See the CreateKeyStoreKeyExample. 3. Branch key wrapping KMS key ARN for the KMS key used to create the branch key with ID provided in arg 2 4. Branch key DDB table ARN for the DDB table representing the branch key store */ public class CompoundBeaconSearchableEncryptionExample { static String GSI_NAME = "last4UnitCompound-index"; static int MAX_CONCURRENT_QUERY_THREADS = 10; public static void PutItemQueryItemWithCompoundBeacon(String ddbTableName, String branchKeyId, String branchKeyWrappingKmsKeyArn, String branchKeyDdbTableName) { // 1. Create Beacons. // These are the same beacons as in the "BasicSearchableEncryptionExample" in this directory. // See that file to see details on beacon construction and parameters. // While we will not directly query against these beacons, // you must create standard beacons on encrypted fields // that we wish to use in compound beacons. List<StandardBeacon> standardBeaconList = new ArrayList<>(); StandardBeacon last4Beacon = StandardBeacon.builder() .name("inspector_id_last4") .length(10) .build(); standardBeaconList.add(last4Beacon); StandardBeacon unitBeacon = StandardBeacon.builder() .name("unit") .length(30) .build(); standardBeaconList.add(unitBeacon); // 2. Define encrypted parts. // Encrypted parts define the beacons that can be used to construct a compound beacon, // and how the compound beacon prefixes those beacon values. List<EncryptedPart> encryptedPartList = new ArrayList<>(); // A encrypted part must receive: // - name: Name of a standard beacon // - prefix: Any string. This is plaintext that prefixes the beaconized value in the compound beacon. // Prefixes must be unique across the configuration, and must not be a prefix of another prefix; // i.e. for all configured prefixes, the first N characters of a prefix must not equal another prefix. // In practice, it is suggested to have a short value distinguishable from other parts served on the prefix. // For this example, we will choose "L-" as the prefix for "Last 4 digits of inspector ID". // With this prefix and the standard beacon's bit length definition (10), the beaconized // version of the inspector ID's last 4 digits will appear as // `L-000` to `L-3ff` inside a compound beacon. EncryptedPart last4EncryptedPart = EncryptedPart.builder() .name("inspector_id_last4") .prefix("L-") .build(); encryptedPartList.add(last4EncryptedPart); // For this example, we will choose "U-" as the prefix for "unit". // With this prefix and the standard beacon's bit length definition (30), a unit beacon will appear // as `U-00000000` to `U-3fffffff` inside a compound beacon. EncryptedPart unitEncryptedPart = EncryptedPart.builder() .name("unit") .prefix("U-") .build(); encryptedPartList.add(unitEncryptedPart); // 3. Define compound beacon. // A compound beacon allows one to serve multiple beacons or attributes from a single index. // A compound beacon must receive: // - name: The name of the beacon. Compound beacon values will be written to `aws_ddb_e_[name]`. // - split: A character separating parts in a compound beacon // A compound beacon may also receive: // - encrypted: A list of encrypted parts. This is effectively a list of beacons. We provide the list // that we created above. // - constructors: A list of constructors. This is an ordered list of possible ways to create a beacon. // We have not defined any constructors here; see the complex example for how to do this. // The client will provide a default constructor, which will write a compound beacon as: // all signed parts in the order they are added to the signed list; // all encrypted parts in order they are added to the encrypted list; all parts required. // In this example, we expect compound beacons to be written as // `L-XXX.U-YYYYYYYY`, since our encrypted list looks like // [last4EncryptedPart, unitEncryptedPart]. // - signed: A list of signed parts, i.e. plaintext attributes. This would be provided if we // wanted to use plaintext values as part of constructing our compound beacon. We do not // provide this here; see the Complex example for an example. List<CompoundBeacon> compoundBeaconList = new ArrayList<>(); CompoundBeacon last4UnitCompoundBeacon = CompoundBeacon.builder() .name("last4UnitCompound") .split(".") .encrypted(encryptedPartList) .build(); compoundBeaconList.add(last4UnitCompoundBeacon); // 4. Configure the Keystore // These are the same constructions as in the Basic example, which describes these in more detail. KeyStore keyStore = KeyStore.builder() .KeyStoreConfig(KeyStoreConfig.builder() .kmsClient(KmsClient.create()) .ddbClient(DynamoDbClient.create()) .ddbTableName(branchKeyDdbTableName) .logicalKeyStoreName(branchKeyDdbTableName) .kmsConfiguration(KMSConfiguration.builder().kmsKeyArn(branchKeyWrappingKmsKeyArn).build()) .build()) .build(); // 5. Create BeaconVersion. // This is similar to the Basic example, except we have also provided a compoundBeaconList. // We must also continue to provide all of the standard beacons that compose a compound beacon list. List<BeaconVersion> beaconVersions = new ArrayList<>(); beaconVersions.add( BeaconVersion.builder() .standardBeacons(standardBeaconList) .compoundBeacons(compoundBeaconList) .version(1) // MUST be 1 .keyStore(keyStore) .keySource(BeaconKeySource.builder() .single(SingleKeyStore.builder() .keyId(branchKeyId) .cacheTTL(6000) .build()) .build()) .build() ); // 6. Create a Hierarchical Keyring // This is the same configuration as in the Basic example. final MaterialProviders matProv = MaterialProviders.builder() .MaterialProvidersConfig(MaterialProvidersConfig.builder().build()) .build(); CreateAwsKmsHierarchicalKeyringInput keyringInput = CreateAwsKmsHierarchicalKeyringInput.builder() .branchKeyId(branchKeyId) .keyStore(keyStore) .ttlSeconds(6000l) .build(); final IKeyring kmsKeyring = matProv.CreateAwsKmsHierarchicalKeyring(keyringInput); // 7. Configure which attributes are encrypted and/or signed when writing new items. final Map<String, CryptoAction> attributeActionsOnEncrypt = new HashMap<>(); attributeActionsOnEncrypt.put("work_id", CryptoAction.SIGN_ONLY); // Our partition attribute must be SIGN_ONLY attributeActionsOnEncrypt.put("inspection_date", CryptoAction.SIGN_ONLY); // Our sort attribute must be SIGN_ONLY attributeActionsOnEncrypt.put("inspector_id_last4", CryptoAction.ENCRYPT_AND_SIGN); // Beaconized attributes must be encrypted attributeActionsOnEncrypt.put("unit", CryptoAction.ENCRYPT_AND_SIGN); // Beaconized attributes must be encrypted // We do not need to define a crypto action on last4UnitCompound. // We only need to define crypto actions on attributes that we pass to PutItem. // 8. Create the DynamoDb Encryption configuration for the table we will be writing to. // The beaconVersions are added to the search configuration. final Map<String, DynamoDbTableEncryptionConfig> tableConfigs = new HashMap<>(); final DynamoDbTableEncryptionConfig config = DynamoDbTableEncryptionConfig.builder() .logicalTableName(ddbTableName) .partitionKeyName("work_id") .sortKeyName("inspection_date") .attributeActionsOnEncrypt(attributeActionsOnEncrypt) .keyring(kmsKeyring) .search(SearchConfig.builder() .writeVersion(1) // MUST be 1 .versions(beaconVersions) .build()) .build(); tableConfigs.put(ddbTableName, config); // 9. Create config final DynamoDbTablesEncryptionConfig encryptionConfig = DynamoDbTablesEncryptionConfig.builder() .tableEncryptionConfigs(tableConfigs) .build(); // 10. Create an item with both attributes used in the compound beacon. final HashMap<String, AttributeValue> item = new HashMap<>(); item.put("work_id", AttributeValue.builder().s("9ce39272-8068-4efd-a211-cd162ad65d4c").build()); item.put("inspection_date", AttributeValue.builder().s("2023-06-13").build()); item.put("inspector_id_last4", AttributeValue.builder().s("5678").build()); item.put("unit", AttributeValue.builder().s("011899988199").build()); // 11. If developing or debugging, verify config by checking compound beacon values directly final DynamoDbEncryptionTransforms trans = DynamoDbEncryptionTransforms.builder() .DynamoDbTablesEncryptionConfig(encryptionConfig).build(); final ResolveAttributesInput resolveInput = ResolveAttributesInput.builder() .TableName(ddbTableName) .Item(item) .Version(1) .build(); final ResolveAttributesOutput resolveOutput = trans.ResolveAttributes(resolveInput); // VirtualFields is empty because we have no Virtual Fields configured assert resolveOutput.VirtualFields().isEmpty(); // Verify that CompoundBeacons has the expected value Map<String, String> cbs = new HashMap<>(); cbs.put("last4UnitCompound", "L-5678.U-011899988199"); assert resolveOutput.CompoundBeacons().equals(cbs); // Note : the compound beacon actually stored in the table is not "L-5678.U-011899988199" // but rather something like "L-abc.U-123", as both parts are EncryptedParts // and therefore the text is replaced by the associated beacon // 12. Create the DynamoDb Encryption Interceptor DynamoDbEncryptionInterceptor encryptionInterceptor = DynamoDbEncryptionInterceptor.builder() .config(encryptionConfig) .build(); // 13. Create a new AWS SDK DynamoDb client using the DynamoDb Encryption Interceptor above final DynamoDbClient ddb = DynamoDbClient.builder() .overrideConfiguration( ClientOverrideConfiguration.builder() .addExecutionInterceptor(encryptionInterceptor) .build()) .build(); PutAndQueryItemWithCompoundBeacon(ddb, ddbTableName, item); // If instead you were working in a multi-threaded context // it might look like this Runnable myThread = () -> { for(int i = 0; i < 20; ++i) { PutAndQueryItemWithCompoundBeacon(ddb, ddbTableName, item); } }; ExecutorService pool = Executors.newFixedThreadPool(MAX_CONCURRENT_QUERY_THREADS); for(int i = 0; i < (2*MAX_CONCURRENT_QUERY_THREADS); i++) { pool.execute(myThread); } pool.shutdown(); try {pool.awaitTermination(30, TimeUnit.SECONDS);} catch (Exception e) {} } public static void PutAndQueryItemWithCompoundBeacon(DynamoDbClient ddb, String ddbTableName, HashMap<String, AttributeValue> item) { // 14. Write the item to the table final PutItemRequest putRequest = PutItemRequest.builder() .tableName(ddbTableName) .item(item) .build(); final PutItemResponse putResponse = ddb.putItem(putRequest); // Validate object put successfully assert 200 == putResponse.sdkHttpResponse().statusCode(); // 15. Query for the item we just put. Map<String, String> expressionAttributesNames = new HashMap<>(); expressionAttributesNames.put("#compound", "last4UnitCompound"); Map<String, AttributeValue> expressionAttributeValues = new HashMap<>(); // This query expression takes a few factors into consideration: // - The configured prefix for the last 4 digits of an inspector ID is "L-"; // the prefix for the unit is "U-" // - The configured split character, separating component parts, is "." // - The default constructor adds encrypted parts in the order they are in the encrypted list, which // configures `last4` to come before `unit`` // NOTE: We did not need to create a compound beacon for this query. This query could have also been // done by querying on the partition and sort key, as was done in the Basic example. // This is intended to be a simple example to demonstrate how one might set up a compound beacon. // For examples where compound beacons are required, see the Complex example. // The most basic extension to this example that would require a compound beacon would add a third // part to the compound beacon, then query against three parts. expressionAttributeValues.put(":value", AttributeValue.builder().s("L-5678.U-011899988199").build()); QueryRequest queryRequest = QueryRequest.builder() .tableName(ddbTableName) .indexName(GSI_NAME) .keyConditionExpression("#compound = :value") .expressionAttributeNames(expressionAttributesNames) .expressionAttributeValues(expressionAttributeValues) .build(); for (int i=0; i<10; ++i) { QueryResponse queryResponse = ddb.query(queryRequest); List<Map<String, AttributeValue>> attributeValues = queryResponse.items(); // Validate query was returned successfully assert 200 == queryResponse.sdkHttpResponse().statusCode(); // if no results, sleep and try again if (attributeValues.size() == 0) { try {Thread.sleep(20);} catch (Exception e) {} continue; } // Validate only 1 item was returned: the item we just put assert attributeValues.size() == 1; Map<String, AttributeValue> returnedItem = attributeValues.get(0); // Validate the item has the expected attributes assert returnedItem.get("inspector_id_last4").s().equals("5678"); assert returnedItem.get("unit").s().equals("011899988199"); break; } } public static void main(final String[] args) { if (args.length <= 1) { throw new IllegalArgumentException("To run this example, include ddbTableName as args[0], branchKeyId as args[1], " + "branchKeyWrappingKmsKeyId as args[2], and branchKeyDdbTableName as args[3]"); } final String ddbTableName = args[0]; final String branchKeyId = args[1]; final String branchKeyWrappingKmsKeyId = args[2]; final String branchKeyDdbTableName = args[3]; PutItemQueryItemWithCompoundBeacon(ddbTableName, branchKeyId, branchKeyWrappingKmsKeyId, branchKeyDdbTableName); } }
5,263
0
Create_ds/aws-database-encryption-sdk-dynamodb-java/Examples/runtimes/java/DynamoDbEncryption/src/main/java/software/amazon/cryptography/examples
Create_ds/aws-database-encryption-sdk-dynamodb-java/Examples/runtimes/java/DynamoDbEncryption/src/main/java/software/amazon/cryptography/examples/searchableencryption/BasicSearchableEncryptionExample.java
package software.amazon.cryptography.examples.searchableencryption; import java.util.ArrayList; import java.util.List; import java.util.HashMap; import java.util.Map; import software.amazon.awssdk.core.client.config.ClientOverrideConfiguration; import software.amazon.awssdk.services.dynamodb.DynamoDbClient; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; import software.amazon.awssdk.services.dynamodb.model.PutItemRequest; import software.amazon.awssdk.services.dynamodb.model.PutItemResponse; import software.amazon.awssdk.services.dynamodb.model.QueryRequest; import software.amazon.awssdk.services.dynamodb.model.QueryResponse; import software.amazon.awssdk.services.kms.KmsClient; import software.amazon.cryptography.dbencryptionsdk.dynamodb.model.BeaconKeySource; import software.amazon.cryptography.dbencryptionsdk.dynamodb.model.BeaconVersion; import software.amazon.cryptography.dbencryptionsdk.dynamodb.model.DynamoDbTableEncryptionConfig; import software.amazon.cryptography.dbencryptionsdk.dynamodb.model.DynamoDbTablesEncryptionConfig; import software.amazon.cryptography.dbencryptionsdk.dynamodb.model.SearchConfig; import software.amazon.cryptography.dbencryptionsdk.dynamodb.model.SingleKeyStore; import software.amazon.cryptography.dbencryptionsdk.dynamodb.model.StandardBeacon; import software.amazon.cryptography.keystore.KeyStore; import software.amazon.cryptography.keystore.model.CreateKeyOutput; import software.amazon.cryptography.keystore.model.KMSConfiguration; import software.amazon.cryptography.keystore.model.KeyStoreConfig; import software.amazon.cryptography.materialproviders.IKeyring; import software.amazon.cryptography.materialproviders.MaterialProviders; import software.amazon.cryptography.materialproviders.model.CreateAwsKmsHierarchicalKeyringInput; import software.amazon.cryptography.materialproviders.model.MaterialProvidersConfig; import software.amazon.cryptography.dbencryptionsdk.structuredencryption.model.CryptoAction; import software.amazon.cryptography.dbencryptionsdk.dynamodb.DynamoDbEncryptionInterceptor; /* This example demonstrates how to set up a beacon on an encrypted attribute, put an item with the beacon, and query against that beacon. This example follows a use case of a database that stores unit inspection information. Running this example requires access to a DDB table with the following key configuration: - Partition key is named "work_id" with type (S) - Sort key is named "inspection_date" with type (S) This table must have a Global Secondary Index (GSI) configured named "last4-unit-index": - Partition key is named "aws_dbe_b_inspector_id_last4" with type (S) - Sort key is named "aws_dbe_b_unit" with type (S) In this example for storing unit inspection information, this schema is utilized for the data: - "work_id" stores a unique identifier for a unit inspection work order (v4 UUID) - "inspection_date" stores an ISO 8601 date for the inspection (YYYY-MM-DD) - "inspector_id_last4" stores the last 4 digits of the ID of the inspector performing the work - "unit" stores a 12-digit serial number for the unit being inspected The example requires the following ordered input command line parameters: 1. DDB table name for table to put/query data from 2. Branch key ID for a branch key that was previously created in your key store. See the CreateKeyStoreKeyExample. 3. Branch key wrapping KMS key ARN for the KMS key used to create the branch key with ID provided in arg 2 4. Branch key DDB table name for the DDB table representing the branch key store */ public class BasicSearchableEncryptionExample { static String GSI_NAME = "last4-unit-index"; public static void PutItemQueryItemWithBeacon(String ddbTableName, String branchKeyId, String branchKeyWrappingKmsKeyArn, String branchKeyDdbTableName) { // 1. Configure Beacons. // The beacon name must be the name of a table attribute that will be encrypted. // The `length` parameter dictates how many bits are in the beacon attribute value. // The following link provides guidance on choosing a beacon length: // https://docs.aws.amazon.com/database-encryption-sdk/latest/devguide/choosing-beacon-length.html List<StandardBeacon> standardBeaconList = new ArrayList<>(); // The configured DDB table has a GSI on the `aws_dbe_b_inspector_id_last4` AttributeName. // This field holds the last 4 digits of an inspector ID. // For our example, this field may range from 0 to 9,999 (10,000 possible values). // For our example, we assume a full inspector ID is an integer // ranging from 0 to 99,999,999. We do not assume that the full inspector ID's // values are uniformly distributed across its range of possible values. // In many use cases, the prefix of an identifier encodes some information // about that identifier (e.g. zipcode and SSN prefixes encode geographic // information), while the suffix does not and is more uniformly distributed. // We will assume that the inspector ID field matches a similar use case. // So for this example, we only store and use the last // 4 digits of the inspector ID, which we assume is uniformly distributed. // Since the full ID's range is divisible by the range of the last 4 digits, // then the last 4 digits of the inspector ID are uniformly distributed // over the range from 0 to 9,999. // See our documentation for why you should avoid creating beacons over non-uniform distributions // https://docs.aws.amazon.com/database-encryption-sdk/latest/devguide/searchable-encryption.html#are-beacons-right-for-me // A single inspector ID suffix may be assigned to multiple `work_id`s. // // This link provides guidance for choosing a beacon length: // https://docs.aws.amazon.com/database-encryption-sdk/latest/devguide/choosing-beacon-length.html // We follow the guidance in the link above to determine reasonable bounds // for the length of a beacon on the last 4 digits of an inspector ID: // - min: log(sqrt(10,000))/log(2) ~= 6.6, round up to 7 // - max: log((10,000/2))/log(2) ~= 12.3, round down to 12 // You will somehow need to round results to a nearby integer. // We choose to round to the nearest integer; you might consider a different rounding approach. // Rounding up will return fewer expected "false positives" in queries, // leading to fewer decrypt calls and better performance, // but it is easier to identify which beacon values encode distinct plaintexts. // Rounding down will return more expected "false positives" in queries, // leading to more decrypt calls and worse performance, // but it is harder to identify which beacon values encode distinct plaintexts. // We can choose a beacon length between 7 and 12: // - Closer to 7, we expect more "false positives" to be returned, // making it harder to identify which beacon values encode distinct plaintexts, // but leading to more decrypt calls and worse performance // - Closer to 12, we expect fewer "false positives" returned in queries, // leading to fewer decrypt calls and better performance, // but it is easier to identify which beacon values encode distinct plaintexts. // As an example, we will choose 10. // // Values stored in aws_dbe_b_inspector_id_last4 will be 10 bits long (0x000 - 0x3ff) // There will be 2^10 = 1,024 possible HMAC values. // With a sufficiently large number of well-distributed inspector IDs, // for a particular beacon we expect (10,000/1,024) ~= 9.8 4-digit inspector ID suffixes // sharing that beacon value. StandardBeacon last4Beacon = StandardBeacon.builder() .name("inspector_id_last4") .length(10) .build(); standardBeaconList.add(last4Beacon); // The configured DDB table has a GSI on the `aws_dbe_b_unit` AttributeName. // This field holds a unit serial number. // For this example, this is a 12-digit integer from 0 to 999,999,999,999 (10^12 possible values). // We will assume values for this attribute are uniformly distributed across this range. // A single unit serial number may be assigned to multiple `work_id`s. // // This link provides guidance for choosing a beacon length: // https://docs.aws.amazon.com/database-encryption-sdk/latest/devguide/choosing-beacon-length.html // We follow the guidance in the link above to determine reasonable bounds // for the length of a beacon on a unit serial number: // - min: log(sqrt(999,999,999,999))/log(2) ~= 19.9, round up to 20 // - max: log((999,999,999,999/2))/log(2) ~= 38.9, round up to 39 // We can choose a beacon length between 20 and 39: // - Closer to 20, we expect more "false positives" to be returned, // making it harder to identify which beacon values encode distinct plaintexts, // but leading to more decrypt calls and worse performance // - Closer to 39, we expect fewer "false positives" returned in queries, // leading to fewer decrypt calls and better performance, // but it is easier to identify which beacon values encode distinct plaintexts. // As an example, we will choose 30. // // Values stored in aws_dbe_b_unit will be 30 bits long (0x00000000 - 0x3fffffff) // There will be 2^30 = 1,073,741,824 ~= 1.1B possible HMAC values. // With a sufficiently large number of well-distributed inspector IDs, // for a particular beacon we expect (10^12/2^30) ~= 931.3 unit serial numbers // sharing that beacon value. StandardBeacon unitBeacon = StandardBeacon.builder() .name("unit") .length(30) .build(); standardBeaconList.add(unitBeacon); // 2. Configure Keystore. // The keystore is a separate DDB table where the client stores encryption and decryption materials. // In order to configure beacons on the DDB client, you must configure a keystore. // // This example expects that you have already set up a KeyStore with a single branch key. // See the "Create KeyStore Table Example" and "Create KeyStore Key Example" for how to do this. // After you create a branch key, you should persist its ID for use in this example. KeyStore keyStore = KeyStore.builder() .KeyStoreConfig(KeyStoreConfig.builder() .kmsClient(KmsClient.create()) .ddbClient(DynamoDbClient.create()) .ddbTableName(branchKeyDdbTableName) .logicalKeyStoreName(branchKeyDdbTableName) .kmsConfiguration(KMSConfiguration.builder().kmsKeyArn(branchKeyWrappingKmsKeyArn).build()) .build()) .build(); // 3. Create BeaconVersion. // The BeaconVersion inside the list holds the list of beacons on the table. // The BeaconVersion also stores information about the keystore. // BeaconVersion must be provided: // - keyStore: The keystore configured in step 2. // - keySource: A configuration for the key source. // For simple use cases, we can configure a 'singleKeySource' which // statically configures a single beaconKey. That is the approach this example takes. // For use cases where you want to use different beacon keys depending on the data // (for example if your table holds data for multiple tenants, and you want to use // a different beacon key per tenant), look into configuring a MultiKeyStore: // https://docs.aws.amazon.com/database-encryption-sdk/latest/devguide/searchable-encryption-multitenant.html List<BeaconVersion> beaconVersions = new ArrayList<>(); beaconVersions.add( BeaconVersion.builder() .standardBeacons(standardBeaconList) .version(1) // MUST be 1 .keyStore(keyStore) .keySource(BeaconKeySource.builder() .single(SingleKeyStore.builder() // `keyId` references a beacon key. // For every branch key we create in the keystore, // we also create a beacon key. // This beacon key is not the same as the branch key, // but is created with the same ID as the branch key. .keyId(branchKeyId) .cacheTTL(6000) .build()) .build()) .build() ); // 4. Create a Hierarchical Keyring // This is a KMS keyring that utilizes the keystore table. // This config defines how items are encrypted and decrypted. // NOTE: You should configure this to use the same keystore as your search config. final MaterialProviders matProv = MaterialProviders.builder() .MaterialProvidersConfig(MaterialProvidersConfig.builder().build()) .build(); CreateAwsKmsHierarchicalKeyringInput keyringInput = CreateAwsKmsHierarchicalKeyringInput.builder() .branchKeyId(branchKeyId) .keyStore(keyStore) .ttlSeconds(6000l) .build(); final IKeyring kmsKeyring = matProv.CreateAwsKmsHierarchicalKeyring(keyringInput); // 5. Configure which attributes are encrypted and/or signed when writing new items. // For each attribute that may exist on the items we plan to write to our DynamoDbTable, // we must explicitly configure how they should be treated during item encryption: // - ENCRYPT_AND_SIGN: The attribute is encrypted and included in the signature // - SIGN_ONLY: The attribute not encrypted, but is still included in the signature // - DO_NOTHING: The attribute is not encrypted and not included in the signature // Any attributes that will be used in beacons must be configured as ENCRYPT_AND_SIGN. final Map<String, CryptoAction> attributeActionsOnEncrypt = new HashMap<>(); attributeActionsOnEncrypt.put("work_id", CryptoAction.SIGN_ONLY); // Our partition attribute must be SIGN_ONLY attributeActionsOnEncrypt.put("inspection_date", CryptoAction.SIGN_ONLY); // Our sort attribute must be SIGN_ONLY attributeActionsOnEncrypt.put("inspector_id_last4", CryptoAction.ENCRYPT_AND_SIGN); // Beaconized attributes must be encrypted attributeActionsOnEncrypt.put("unit", CryptoAction.ENCRYPT_AND_SIGN); // Beaconized attributes must be encrypted // 6. Create the DynamoDb Encryption configuration for the table we will be writing to. // The beaconVersions are added to the search configuration. final Map<String, DynamoDbTableEncryptionConfig> tableConfigs = new HashMap<>(); final DynamoDbTableEncryptionConfig config = DynamoDbTableEncryptionConfig.builder() .logicalTableName(ddbTableName) .partitionKeyName("work_id") .sortKeyName("inspection_date") .attributeActionsOnEncrypt(attributeActionsOnEncrypt) .keyring(kmsKeyring) .search(SearchConfig.builder() .writeVersion(1) // MUST be 1 .versions(beaconVersions) .build()) .build(); tableConfigs.put(ddbTableName, config); // 7. Create the DynamoDb Encryption Interceptor DynamoDbEncryptionInterceptor encryptionInterceptor = DynamoDbEncryptionInterceptor.builder() .config(DynamoDbTablesEncryptionConfig.builder() .tableEncryptionConfigs(tableConfigs) .build()) .build(); // 8. Create a new AWS SDK DynamoDb client using the DynamoDb Encryption Interceptor above final DynamoDbClient ddb = DynamoDbClient.builder() .overrideConfiguration( ClientOverrideConfiguration.builder() .addExecutionInterceptor(encryptionInterceptor) .build()) .build(); // 9. Put an item into our table using the above client. // Before the item gets sent to DynamoDb, it will be encrypted // client-side, according to our configuration. // Since our configuration includes beacons for `inspector_id_last4` and `unit`, // the client will add two additional attributes to the item. These attributes will have names // `aws_dbe_b_inspector_id_last4` and `aws_dbe_b_unit`. Their values will be HMACs // truncated to as many bits as the beacon's `length` parameter; e.g. // aws_dbe_b_inspector_id_last4 = truncate(HMAC("4321"), 10) // aws_dbe_b_unit = truncate(HMAC("123456789012"), 30) final HashMap<String, AttributeValue> item = new HashMap<>(); item.put("work_id", AttributeValue.builder().s("1313ba89-5661-41eb-ba6c-cb1b4cb67b2d").build()); item.put("inspection_date", AttributeValue.builder().s("2023-06-13").build()); item.put("inspector_id_last4", AttributeValue.builder().s("4321").build()); item.put("unit", AttributeValue.builder().s("123456789012").build()); final PutItemRequest putRequest = PutItemRequest.builder() .tableName(ddbTableName) .item(item) .build(); final PutItemResponse putResponse = ddb.putItem(putRequest); assert 200 == putResponse.sdkHttpResponse().statusCode(); // 10. Query for the item we just put. // Note that we are constructing the query as if we were querying on plaintext values. // However, the DDB encryption client will detect that this attribute name has a beacon configured. // The client will add the beaconized attribute name and attribute value to the query, // and transform the query to use the beaconized name and value. // Internally, the client will query for and receive all items with a matching HMAC value in the beacon field. // This may include a number of "false positives" with different ciphertext, but the same truncated HMAC. // e.g. if truncate(HMAC("123456789012"), 30) // == truncate(HMAC("098765432109"), 30), // the query will return both items. // The client will decrypt all returned items to determine which ones have the expected attribute values, // and only surface items with the correct plaintext to the user. // This procedure is internal to the client and is abstracted away from the user; // e.g. the user will only see "123456789012" and never // "098765432109", though the actual query returned both. Map<String,String> expressionAttributesNames = new HashMap<>(); expressionAttributesNames.put("#last4", "inspector_id_last4"); expressionAttributesNames.put("#unit", "unit"); Map<String,AttributeValue> expressionAttributeValues = new HashMap<>(); expressionAttributeValues.put(":last4", AttributeValue.builder().s("4321").build()); expressionAttributeValues.put(":unit", AttributeValue.builder().s("123456789012").build()); QueryRequest queryRequest = QueryRequest.builder() .tableName(ddbTableName) .indexName(GSI_NAME) .keyConditionExpression("#last4 = :last4 and #unit = :unit") .expressionAttributeNames(expressionAttributesNames) .expressionAttributeValues(expressionAttributeValues) .build(); // GSIs do not update instantly // so if the results come back empty // we retry after a short sleep for (int i=0; i<10; ++i) { final QueryResponse queryResponse = ddb.query(queryRequest); List<Map<String, AttributeValue>> attributeValues = queryResponse.items(); // Validate query was returned successfully assert 200 == queryResponse.sdkHttpResponse().statusCode(); // if no results, sleep and try again if (attributeValues.size() == 0) { try {Thread.sleep(20);} catch (Exception e) {} continue; } // Validate only 1 item was returned: the item we just put assert attributeValues.size() == 1; final Map<String, AttributeValue> returnedItem = attributeValues.get(0); // Validate the item has the expected attributes assert returnedItem.get("inspector_id_last4").s().equals("4321"); assert returnedItem.get("unit").s().equals("123456789012"); break; } } public static void main(final String[] args) { if (args.length <= 1) { throw new IllegalArgumentException("To run this example, include ddbTableName as args[0], " + "branchKeyId as args[1], branchKeyWrappingKmsKeyId as args[2], and branchKeyDdbTableName as args[3]"); } final String ddbTableName = args[0]; final String branchKeyId = args[1]; final String branchKeyWrappingKmsKeyArn = args[2]; final String branchKeyDdbTableName = args[3]; PutItemQueryItemWithBeacon(ddbTableName, branchKeyId, branchKeyWrappingKmsKeyArn, branchKeyDdbTableName); } }
5,264
0
Create_ds/aws-database-encryption-sdk-dynamodb-java/Examples/runtimes/java/DynamoDbEncryption/src/main/java/software/amazon/cryptography/examples
Create_ds/aws-database-encryption-sdk-dynamodb-java/Examples/runtimes/java/DynamoDbEncryption/src/main/java/software/amazon/cryptography/examples/searchableencryption/VirtualBeaconSearchableEncryptionExample.java
package software.amazon.cryptography.examples.searchableencryption; import java.util.ArrayList; import java.util.List; import java.util.HashMap; import java.util.Map; import software.amazon.awssdk.core.client.config.ClientOverrideConfiguration; import software.amazon.awssdk.services.dynamodb.DynamoDbClient; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; import software.amazon.awssdk.services.dynamodb.model.PutItemRequest; import software.amazon.awssdk.services.dynamodb.model.PutItemResponse; import software.amazon.awssdk.services.dynamodb.model.QueryRequest; import software.amazon.awssdk.services.dynamodb.model.QueryResponse; import software.amazon.awssdk.services.kms.KmsClient; import software.amazon.cryptography.dbencryptionsdk.dynamodb.model.BeaconKeySource; import software.amazon.cryptography.dbencryptionsdk.dynamodb.model.BeaconVersion; import software.amazon.cryptography.dbencryptionsdk.dynamodb.model.DynamoDbTableEncryptionConfig; import software.amazon.cryptography.dbencryptionsdk.dynamodb.model.DynamoDbTablesEncryptionConfig; import software.amazon.cryptography.dbencryptionsdk.dynamodb.model.GetPrefix; import software.amazon.cryptography.dbencryptionsdk.dynamodb.model.SearchConfig; import software.amazon.cryptography.dbencryptionsdk.dynamodb.model.SingleKeyStore; import software.amazon.cryptography.dbencryptionsdk.dynamodb.model.StandardBeacon; import software.amazon.cryptography.dbencryptionsdk.dynamodb.model.VirtualField; import software.amazon.cryptography.dbencryptionsdk.dynamodb.model.VirtualPart; import software.amazon.cryptography.dbencryptionsdk.dynamodb.model.VirtualTransform; import software.amazon.cryptography.dbencryptionsdk.dynamodb.transforms.DynamoDbEncryptionTransforms; import software.amazon.cryptography.dbencryptionsdk.dynamodb.transforms.model.ResolveAttributesInput; import software.amazon.cryptography.dbencryptionsdk.dynamodb.transforms.model.ResolveAttributesOutput; import software.amazon.cryptography.keystore.KeyStore; import software.amazon.cryptography.keystore.model.KMSConfiguration; import software.amazon.cryptography.keystore.model.KeyStoreConfig; import software.amazon.cryptography.materialproviders.IKeyring; import software.amazon.cryptography.materialproviders.MaterialProviders; import software.amazon.cryptography.materialproviders.model.CreateAwsKmsHierarchicalKeyringInput; import software.amazon.cryptography.materialproviders.model.MaterialProvidersConfig; import software.amazon.cryptography.dbencryptionsdk.structuredencryption.model.CryptoAction; import software.amazon.cryptography.dbencryptionsdk.dynamodb.DynamoDbEncryptionInterceptor; /* This example demonstrates how to set up a virtual field from two DDB attributes, create a standard beacon with that field, put an item with that beacon, and query against that beacon. A virtual field is a field consisting of a transformation of one or more attributes in a DDB item. Virtual fields are useful in querying against encrypted fields that only have a handful of possible values. They allow you to take fields with few possible values, concatenate them to other fields, then query against the combined field. This enables using these types of fields in queries while making it infeasible to identify which beacon values encode the few possible distinct plaintexts. This is explained in more detail below. Virtual fields are not stored in the DDB table. However, they are used to construct a beacon, the value of which is stored. For more information on virtual fields, see https://docs.aws.amazon.com/database-encryption-sdk/latest/devguide/beacons.html#virtual-field For our example, we will construct a virtual field from two DDB attributes `state` and `hasTestResult` as `state`+prefix(`hasTestResult`, 1). We will then create a beacon out of this virtual field and use it to search. This example follows a use case of a database that stores customer test result metadata. Records are indexed by `customer_id` and store a `state` attribute, representing the US state or territory where the customer lives, and a `hasTestResult` boolean attribute, representing whether the customer has a "test result" available. (Maybe this represents some medical test result, and this table stores "result available" metadata.) We assume that values in these fields are uniformly distributed across all possible values for these fields (56 for `state`, 2 for `hasTestResult`), and are uniformly distributed across customer IDs. The motivation behind this example is to demonstrate how and why one would use a virtual beacon. In this example, our table stores records with an encrypted boolean `hasTestResult` attribute. We would like to be able to query for customers in a given state with a `true` hasTestResult attribute. To be able to execute this query securely and efficiently, we want the following properties on our table: 1. Hide the distribution of `hasTestResult` attribute values (i.e. it should be infeasible to determine the percentage of `true`s to `false`s across the dataset from beaconized values) 2. Query against a combination of whether `hasTestResult` is true/false and the `state` field We cannot achieve these properties with a standard beacon on a true/false attribute. Following the guidance to choose a beacon length: https://docs.aws.amazon.com/database-encryption-sdk/latest/devguide/choosing-beacon-length.html For a boolean value (in our case, whether `hasTestResult` is true or false), the acceptable bounds for beacon length are either 0 or 1. This corresponds to either not storing a beacon (length 0), or effectively storing another boolean attribute (length 1). With length 0, this beacon is useless for searching (violating property 2); with length 1, this beacon may not hide the attribute (violating property 1). In addition, choosing a longer beacon length does not help us. Each attribute value is mapped to a distinct beacon. Since booleans only have 2 possible attribute values, we will still only have 2 possible beacon values, though those values may be longer. A longer beacon provides no advantages over beacon of length 1 in this situation. A compound beacon also does not help. To (over)simplify, a compound beacon is a concatenation of standard beacons, i.e. beacon(`state`)+beacon(`hasTestResult`). The `hasTestResult` beacon is still visible, so we would still have the problems above. To achieve these properties, we instead construct a virtual field and use that in our beacon, i.e. beacon(`state`+`hasTestResult`). Assuming these fields are well-distributed across customer IDs and possible values, this gives us both desired properties; we can query against both attributes while hiding information from the underlying data. This is demonstrated in more detail below. Running this example requires access to a DDB table with the following primary key configuration: - Partition key is named "customer_id" with type (S) - Sort key is named "create_time" with type (S) This table must have a Global Secondary Index (GSI) configured named "stateAndHasTestResult-index": - Partition key is named "aws_dbe_b_stateAndHasTestResult" with type (S) In this example for storing customer location data, this schema is utilized for the data: - "customer_id" stores a unique customer identifier - "create_time" stores a Unix timestamp - "state" stores an encrypted 2-letter US state or territory abbreviation (https://www.faa.gov/air_traffic/publications/atpubs/cnt_html/appendix_a.html) - "hasTestResult" is not part of the schema, but is an attribute utilized in this example. It stores a boolean attribute (false/true) indicating whether this customer has a test result available. The example requires the following ordered input command line parameters: 1. DDB table name for table to put/query data from 2. Branch key ID for a branch key that was previously created in your key store. See the CreateKeyStoreKeyExample. 2. Branch key wrapping KMS key ARN for the KMS key used to create the branch key 3. Branch key DDB table name for the DDB table representing the branch key store */ public class VirtualBeaconSearchableEncryptionExample { static String GSI_NAME = "stateAndHasTestResult-index"; public static void PutItemQueryItemWithVirtualBeacon(String ddbTableName, String branchKeyId, String branchKeyWrappingKmsKeyArn, String branchKeyDdbTableName) { // 1. Construct a length-1 prefix virtual transform. // `hasTestResult` is a binary attribute, containing either `true` or `false`. // As an example to demonstrate virtual transforms, we will truncate the value // of `hasTestResult` in the virtual field to the length-1 prefix of the binary value, i.e.: // - "true" -> "t" // - "false -> "f" // This is not necessary. This is done as a demonstration of virtual transforms. // Virtual transform operations treat all attributes as strings // (i.e. the boolean value `true` is interpreted as a string "true"), // so its length-1 prefix is just "t". List<VirtualTransform> length1PrefixVirtualTransformList = new ArrayList<>(); VirtualTransform length1PrefixVirtualTransform = VirtualTransform.builder() .prefix(GetPrefix.builder() .length(1) .build()) .build(); length1PrefixVirtualTransformList.add(length1PrefixVirtualTransform); // 2. Construct the VirtualParts required for the VirtualField VirtualPart hasTestResultPart = VirtualPart.builder() .loc("hasTestResult") // Here, we apply the length-1 prefix virtual transform .trans(length1PrefixVirtualTransformList) .build(); VirtualPart statePart = VirtualPart.builder() .loc("state") // Note that we do not apply any transform to the `state` attribute, // and the virtual field will read in the attribute as-is. .build(); // 3. Construct the VirtualField from the VirtualParts // Note that the order that virtual parts are added to the virtualPartList // dictates the order in which they are concatenated to build the virtual field. // You must add virtual parts in the same order on write as you do on read. List<VirtualPart> virtualPartList = new ArrayList<>(); virtualPartList.add(statePart); virtualPartList.add(hasTestResultPart); VirtualField stateAndHasTestResultField = VirtualField.builder() .name("stateAndHasTestResult") .parts(virtualPartList) .build(); List<VirtualField> virtualFieldList = new ArrayList<>(); virtualFieldList.add(stateAndHasTestResultField); // 4. Configure our beacon. // The virtual field is assumed to hold a US 2-letter state abbreviation // (56 possible values = 50 states + 6 territories) concatenated with a binary attribute // (2 possible values: true/false hasTestResult field), we expect a population size of // 56 * 2 = 112 possible values. // We will also assume that these values are reasonably well-distributed across // customer IDs. In practice, this will not be true. We would expect // more populous states to appear more frequently in the database. // A more complex analysis would show that a stricter upper bound // is necessary to account for this by hiding information from the // underlying distribution. // // This link provides guidance for choosing a beacon length: // https://docs.aws.amazon.com/database-encryption-sdk/latest/devguide/choosing-beacon-length.html // We follow the guidance in the link above to determine reasonable bounds for beacon length: // - min: log(sqrt(112))/log(2) ~= 3.4, round down to 3 // - max: log((112/2))/log(2) ~= 5.8, round up to 6 // You will somehow need to round results to a nearby integer. // We choose to round to the nearest integer; you might consider a different rounding approach. // Rounding up will return fewer expected "false positives" in queries, // leading to fewer decrypt calls and better performance, // but it is easier to identify which beacon values encode distinct plaintexts. // Rounding down will return more expected "false positives" in queries, // leading to more decrypt calls and worse performance, // but it is harder to identify which beacon values encode distinct plaintexts. // We can choose a beacon length between 3 and 6: // - Closer to 3, we expect more "false positives" to be returned, // making it harder to identify which beacon values encode distinct plaintexts, // but leading to more decrypt calls and worse performance // - Closer to 6, we expect fewer "false positives" returned in queries, // leading to fewer decrypt calls and better performance, // but it is easier to identify which beacon values encode distinct plaintexts. // As an example, we will choose 5. // Values stored in aws_dbe_b_stateAndHasTestResult will be 5 bits long (0x00 - 0x1f) // There will be 2^5 = 32 possible HMAC values. // With a well-distributed dataset (112 values), for a particular beacon we expect // (112/32) = 3.5 combinations of abbreviation + true/false attribute // sharing that beacon value. List<StandardBeacon> standardBeaconList = new ArrayList<>(); StandardBeacon stateAndHasTestResultBeacon = StandardBeacon.builder() // This name is the same as our virtual field's name above .name("stateAndHasTestResult") .length(5) .build(); standardBeaconList.add(stateAndHasTestResultBeacon); // 5. Configure Keystore. // This example expects that you have already set up a KeyStore with a single branch key. // See the "CreateKeyStoreTableExample" and "CreateKeyStoreKeyExample" files for how to do this. // After you create a branch key, you should persist its ID for use in this example. KeyStore keyStore = KeyStore.builder() .KeyStoreConfig(KeyStoreConfig.builder() .kmsClient(KmsClient.create()) .ddbClient(DynamoDbClient.create()) .ddbTableName(branchKeyDdbTableName) .logicalKeyStoreName(branchKeyDdbTableName) .kmsConfiguration(KMSConfiguration.builder().kmsKeyArn(branchKeyWrappingKmsKeyArn).build()) .build()) .build(); // 6. Create BeaconVersion. // The BeaconVersion inside the list holds the list of beacons on the table. // The BeaconVersion also stores information about the keystore. // BeaconVersion must be provided: // - keyStore: The keystore configured in the previous step. // - keySource: A configuration for the key source. // For simple use cases, we can configure a 'singleKeySource' which // statically configures a single beaconKey. That is the approach this example takes. // For use cases where you want to use different beacon keys depending on the data // (for example if your table holds data for multiple tenants, and you want to use // a different beacon key per tenant), look into configuring a MultiKeyStore: // https://docs.aws.amazon.com/database-encryption-sdk/latest/devguide/searchable-encryption-multitenant.html // We also provide our standard beacon list and virtual fields here. List<BeaconVersion> beaconVersions = new ArrayList<>(); beaconVersions.add( BeaconVersion.builder() .virtualFields(virtualFieldList) .standardBeacons(standardBeaconList) .version(1) // MUST be 1 .keyStore(keyStore) .keySource(BeaconKeySource.builder() .single(SingleKeyStore.builder() // `keyId` references a beacon key. // For every branch key we create in the keystore, // we also create a beacon key. // This beacon key is not the same as the branch key, // but is created with the same ID as the branch key. .keyId(branchKeyId) .cacheTTL(6000) .build()) .build()) .build() ); // 7. Create a Hierarchical Keyring // This is a KMS keyring that utilizes the keystore table. // This config defines how items are encrypted and decrypted. // NOTE: You should configure this to use the same keystore as your search config. final MaterialProviders matProv = MaterialProviders.builder() .MaterialProvidersConfig(MaterialProvidersConfig.builder().build()) .build(); CreateAwsKmsHierarchicalKeyringInput keyringInput = CreateAwsKmsHierarchicalKeyringInput.builder() .branchKeyId(branchKeyId) .keyStore(keyStore) .ttlSeconds(6000l) .build(); final IKeyring kmsKeyring = matProv.CreateAwsKmsHierarchicalKeyring(keyringInput); // 8. Configure which attributes are encrypted and/or signed when writing new items. // For each attribute that may exist on the items we plan to write to our DynamoDbTable, // we must explicitly configure how they should be treated during item encryption: // - ENCRYPT_AND_SIGN: The attribute is encrypted and included in the signature // - SIGN_ONLY: The attribute not encrypted, but is still included in the signature // - DO_NOTHING: The attribute is not encrypted and not included in the signature // Any attributes that will be used in beacons must be configured as ENCRYPT_AND_SIGN. final Map<String, CryptoAction> attributeActionsOnEncrypt = new HashMap<>(); attributeActionsOnEncrypt.put("customer_id", CryptoAction.SIGN_ONLY); // Our partition attribute must be SIGN_ONLY attributeActionsOnEncrypt.put("create_time", CryptoAction.SIGN_ONLY); // Our sort attribute must be SIGN_ONLY attributeActionsOnEncrypt.put("state", CryptoAction.ENCRYPT_AND_SIGN); // Beaconized attributes must be encrypted attributeActionsOnEncrypt.put("hasTestResult", CryptoAction.ENCRYPT_AND_SIGN); // Beaconized attributes must be encrypted // 9. Create the DynamoDb Encryption configuration for the table we will be writing to. // The beaconVersions are added to the search configuration. final Map<String, DynamoDbTableEncryptionConfig> tableConfigs = new HashMap<>(); final DynamoDbTableEncryptionConfig config = DynamoDbTableEncryptionConfig.builder() .logicalTableName(ddbTableName) .partitionKeyName("customer_id") .sortKeyName("create_time") .attributeActionsOnEncrypt(attributeActionsOnEncrypt) .keyring(kmsKeyring) .search(SearchConfig.builder() .writeVersion(1) // MUST be 1 .versions(beaconVersions) .build()) .build(); tableConfigs.put(ddbTableName, config); // 10. Create config final DynamoDbTablesEncryptionConfig encryptionConfig = DynamoDbTablesEncryptionConfig.builder() .tableEncryptionConfigs(tableConfigs) .build(); // 11. Create test items // Create item with hasTestResult=true final HashMap<String, AttributeValue> itemWithHasTestResult = new HashMap<>(); itemWithHasTestResult.put("customer_id", AttributeValue.builder().s("ABC-123").build()); itemWithHasTestResult.put("create_time", AttributeValue.builder().n("1681495205").build()); itemWithHasTestResult.put("state", AttributeValue.builder().s("CA").build()); itemWithHasTestResult.put("hasTestResult", AttributeValue.builder().bool(true).build()); // Create item with hasTestResult=false final HashMap<String, AttributeValue> itemWithNoHasTestResult = new HashMap<>(); itemWithNoHasTestResult.put("customer_id", AttributeValue.builder().s("DEF-456").build()); itemWithNoHasTestResult.put("create_time", AttributeValue.builder().n("1681495205").build()); itemWithNoHasTestResult.put("state", AttributeValue.builder().s("CA").build()); itemWithNoHasTestResult.put("hasTestResult", AttributeValue.builder().bool(false).build()); // 12. If developing or debugging, verify config by checking virtual field values directly final DynamoDbEncryptionTransforms trans = DynamoDbEncryptionTransforms.builder() .DynamoDbTablesEncryptionConfig(encryptionConfig).build(); final ResolveAttributesInput resolveInput = ResolveAttributesInput.builder() .TableName(ddbTableName) .Item(itemWithHasTestResult) .Version(1) .build(); final ResolveAttributesOutput resolveOutput = trans.ResolveAttributes(resolveInput); // CompoundBeacons is empty because we have no Compound Beacons configured assert resolveOutput.CompoundBeacons().isEmpty(); // Verify that VirtualFields has the expected value Map<String, String> vf = new HashMap<>(); vf.put("stateAndHasTestResult", "CAt"); assert resolveOutput.VirtualFields().equals(vf); // 13. Create the DynamoDb Encryption Interceptor DynamoDbEncryptionInterceptor encryptionInterceptor = DynamoDbEncryptionInterceptor.builder() .config(encryptionConfig) .build(); // 14. Create a new AWS SDK DynamoDb client using the DynamoDb Encryption Interceptor above final DynamoDbClient ddb = DynamoDbClient.builder() .overrideConfiguration( ClientOverrideConfiguration.builder() .addExecutionInterceptor(encryptionInterceptor) .build()) .build(); // 15. Put two items into our table using the above client. // The two items will differ only in their `customer_id` attribute (primary key) // and their `hasTestResult` attribute. // We will query against these items to demonstrate how to use our setup above // to query against our `stateAndHasTestResult` beacon. // Before the item gets sent to DynamoDb, it will be encrypted // client-side, according to our configuration. // Since our configuration includes a beacon on a virtual field named // `stateAndHasTestResult`, the client will add an attribute // to the item with name `aws_dbe_b_stateAndHasTestResult`. // Its value will be an HMAC truncated to as many bits as the // beacon's `length` parameter; i.e. 5. final PutItemRequest itemWithHasTestResultPutRequest = PutItemRequest.builder() .tableName(ddbTableName) .item(itemWithHasTestResult) .build(); final PutItemResponse itemWithHasTestResultPutResponse = ddb.putItem(itemWithHasTestResultPutRequest); // Assert PutItem was successful assert 200 == itemWithHasTestResultPutResponse.sdkHttpResponse().statusCode(); final PutItemRequest itemWithNoHasTestResultPutRequest = PutItemRequest.builder() .tableName(ddbTableName) .item(itemWithNoHasTestResult) .build(); final PutItemResponse itemWithNoHasTestResultPutResponse = ddb.putItem(itemWithNoHasTestResultPutRequest); // Assert PutItem was successful assert 200 == itemWithNoHasTestResultPutResponse.sdkHttpResponse().statusCode(); // 16. Query by stateAndHasTestResult attribute. // Note that we are constructing the query as if we were querying on plaintext values. // However, the DDB encryption client will detect that this attribute name has a beacon configured. // The client will add the beaconized attribute name and attribute value to the query, // and transform the query to use the beaconized name and value. // Internally, the client will query for and receive all items with a matching HMAC value in the beacon field. // This may include a number of "false positives" with different ciphertext, but the same truncated HMAC. // e.g. if truncate(HMAC("CAt"), 5) == truncate(HMAC("DCf"), 5), the query will return both items. // The client will decrypt all returned items to determine which ones have the expected attribute values, // and only surface items with the correct plaintext to the user. // This procedure is internal to the client and is abstracted away from the user; // e.g. the user will only see "CAt" and never "DCf", though the actual query returned both. Map<String,String> expressionAttributesNames = new HashMap<>(); expressionAttributesNames.put("#stateAndHasTestResult", "stateAndHasTestResult"); Map<String,AttributeValue> expressionAttributeValues = new HashMap<>(); // We are querying for the item with `state`="CA" and `hasTestResult`=`true`. // Since we added virtual parts as `state` then `hasTestResult`, // we must write our query expression in the same order. // We constructed our virtual field as `state`+`hasTestResult`, // so we add the two parts in that order. // Since we also created a virtual transform that truncated `hasTestResult` // to its length-1 prefix, i.e. "true" -> "t", // we write that field as its length-1 prefix in the query. expressionAttributeValues.put(":stateAndHasTestResult", AttributeValue.builder().s("CAt").build()); QueryRequest queryRequest = QueryRequest.builder() .tableName(ddbTableName) .indexName(GSI_NAME) .keyConditionExpression("#stateAndHasTestResult = :stateAndHasTestResult") .expressionAttributeNames(expressionAttributesNames) .expressionAttributeValues(expressionAttributeValues) .build(); for (int i=0; i<10; ++i) { final QueryResponse queryResponse = ddb.query(queryRequest); List<Map<String, AttributeValue>> attributeValues = queryResponse.items(); // Validate query was returned successfully assert 200 == queryResponse.sdkHttpResponse().statusCode(); // if no results, sleep and try again if (attributeValues.size() == 0) { try {Thread.sleep(20);} catch (Exception e) {} continue; } // Validate only 1 item was returned: the item with the expected attributes assert attributeValues.size() == 1; final Map<String, AttributeValue> returnedItem = attributeValues.get(0); // Validate the item has the expected attributes assert returnedItem.get("state").s().equals("CA"); assert returnedItem.get("hasTestResult").bool().equals(true); break; } } public static void main(final String[] args) { if (args.length <= 1) { throw new IllegalArgumentException("To run this example, include ddbTableName as args[0], branchKeyId as args[1], branchKeyWrappingKmsKeyId as args[2], and branchKeyDdbTableName as args[3]"); } final String ddbTableName = args[0]; final String branchKeyId = args[1]; final String branchKeyWrappingKmsKeyArn = args[2]; final String branchKeyDdbTableName = args[3]; PutItemQueryItemWithVirtualBeacon(ddbTableName, branchKeyId, branchKeyWrappingKmsKeyArn, branchKeyDdbTableName); } }
5,265
0
Create_ds/aws-database-encryption-sdk-dynamodb-java/Examples/runtimes/java/DynamoDbEncryption/src/main/java/software/amazon/cryptography/examples
Create_ds/aws-database-encryption-sdk-dynamodb-java/Examples/runtimes/java/DynamoDbEncryption/src/main/java/software/amazon/cryptography/examples/searchableencryption/BeaconStylesSearchableEncryptionExample.java
package software.amazon.cryptography.examples.searchableencryption; import java.util.ArrayList; import java.util.List; import java.util.HashMap; import java.util.Map; import javax.swing.text.html.Option; import software.amazon.awssdk.core.client.config.ClientOverrideConfiguration; import software.amazon.awssdk.services.dynamodb.DynamoDbClient; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; import software.amazon.awssdk.services.dynamodb.model.PutItemRequest; import software.amazon.awssdk.services.dynamodb.model.PutItemResponse; import software.amazon.awssdk.services.dynamodb.model.ScanRequest; import software.amazon.awssdk.services.dynamodb.model.ScanResponse; import software.amazon.awssdk.services.kms.KmsClient; import software.amazon.cryptography.dbencryptionsdk.dynamodb.model.BeaconKeySource; import software.amazon.cryptography.dbencryptionsdk.dynamodb.model.BeaconVersion; import software.amazon.cryptography.dbencryptionsdk.dynamodb.model.CompoundBeacon; import software.amazon.cryptography.dbencryptionsdk.dynamodb.model.BeaconStyle; import software.amazon.cryptography.dbencryptionsdk.dynamodb.model.SharedSet; import software.amazon.cryptography.dbencryptionsdk.dynamodb.model.Shared; import software.amazon.cryptography.dbencryptionsdk.dynamodb.model.Constructor; import software.amazon.cryptography.dbencryptionsdk.dynamodb.model.ConstructorPart; import software.amazon.cryptography.dbencryptionsdk.dynamodb.model.DynamoDbTableEncryptionConfig; import software.amazon.cryptography.dbencryptionsdk.dynamodb.model.DynamoDbTablesEncryptionConfig; import software.amazon.cryptography.dbencryptionsdk.dynamodb.model.SearchConfig; import software.amazon.cryptography.dbencryptionsdk.dynamodb.model.EncryptedPart; import software.amazon.cryptography.dbencryptionsdk.dynamodb.model.SingleKeyStore; import software.amazon.cryptography.dbencryptionsdk.dynamodb.model.StandardBeacon; import software.amazon.cryptography.keystore.KeyStore; import software.amazon.cryptography.keystore.model.CreateKeyOutput; import software.amazon.cryptography.keystore.model.KMSConfiguration; import software.amazon.cryptography.keystore.model.KeyStoreConfig; import software.amazon.cryptography.materialproviders.IKeyring; import software.amazon.cryptography.materialproviders.MaterialProviders; import software.amazon.cryptography.materialproviders.model.CreateAwsKmsHierarchicalKeyringInput; import software.amazon.cryptography.materialproviders.model.MaterialProvidersConfig; import software.amazon.cryptography.dbencryptionsdk.structuredencryption.model.CryptoAction; import software.amazon.cryptography.dbencryptionsdk.dynamodb.DynamoDbEncryptionInterceptor; /* This example demonstrates how to use Beacons Styles on Standard Beacons on encrypted attributes, put an item with the beacon, and query against that beacon. This example follows a use case of a database that stores food information. This is an extension of the "BasicSearchableEncryptionExample" in this directory and uses the same table schema. Running this example requires access to a DDB table with the following key configuration: - Partition key is named "work_id" with type (S) - Sort key is named "inspection_time" with type (S) In this example for storing food information, this schema is utilized for the data: - "work_id" stores a unique identifier for a unit inspection work order (v4 UUID) - "inspection_date" stores an ISO 8601 date for the inspection (YYYY-MM-DD) - "fruit" stores one type of fruit - "basket" stores a set of types of fruit - "dessert" stores one type of dessert The example requires the following ordered input command line parameters: 1. DDB table name for table to put/query data from 2. Branch key ID for a branch key that was previously created in your key store. See the CreateKeyStoreKeyExample. 3. Branch key wrapping KMS key ARN for the KMS key used to create the branch key with ID provided in arg 2 4. Branch key DDB table ARN for the DDB table representing the branch key store */ public class BeaconStylesSearchableEncryptionExample { public static void PutItemQueryItemWithBeaconStyles(String ddbTableName, String branchKeyId, String branchKeyWrappingKmsKeyArn, String branchKeyDdbTableName) { // 1. Create Beacons. List<StandardBeacon> standardBeaconList = new ArrayList<>(); // The fruit beacon allows searching on the encrypted fruit attribute // We have selected 30 as an example beacon length, but you should go to // https://docs.aws.amazon.com/database-encryption-sdk/latest/devguide/choosing-beacon-length.html // when creating your beacons. StandardBeacon fruitBeacon = StandardBeacon.builder() .name("fruit") .length(30) .build(); standardBeaconList.add(fruitBeacon); // The basket beacon allows searching on the encrypted basket attribute // basket is used as a Set, and therefore needs a beacon style to reflect that. // Further, we need to be able to compare the items in basket to the fruit attribute // so we `share` this beacon with `fruit`. // Since we need both of these things, we use the SharedSet style. StandardBeacon basketBeacon = StandardBeacon.builder() .name("basket") .length(30) .style( BeaconStyle.builder() .sharedSet(SharedSet.builder().other("fruit").build()) .build() ) .build(); standardBeaconList.add(basketBeacon); // The dessert beacon allows searching on the encrypted dessert attribute // We need to be able to compare the dessert attribute to the fruit attribute // so we `share` this beacon with `fruit`. StandardBeacon dessertBeacon = StandardBeacon.builder() .name("dessert") .length(30) .style( BeaconStyle.builder() .shared(Shared.builder().other("fruit").build()) .build() ) .build(); standardBeaconList.add(dessertBeacon); // 2. Configure the Keystore // These are the same constructions as in the Basic example, which describes these in more detail. KeyStore keyStore = KeyStore.builder() .KeyStoreConfig(KeyStoreConfig.builder() .kmsClient(KmsClient.create()) .ddbClient(DynamoDbClient.create()) .ddbTableName(branchKeyDdbTableName) .logicalKeyStoreName(branchKeyDdbTableName) .kmsConfiguration(KMSConfiguration.builder().kmsKeyArn(branchKeyWrappingKmsKeyArn).build()) .build()) .build(); // 3. Create BeaconVersion. // This is similar to the Basic example List<BeaconVersion> beaconVersions = new ArrayList<>(); beaconVersions.add( BeaconVersion.builder() .standardBeacons(standardBeaconList) .version(1) // MUST be 1 .keyStore(keyStore) .keySource(BeaconKeySource.builder() .single(SingleKeyStore.builder() .keyId(branchKeyId) .cacheTTL(6000) .build()) .build()) .build() ); // 4. Create a Hierarchical Keyring // This is the same configuration as in the Basic example. final MaterialProviders matProv = MaterialProviders.builder() .MaterialProvidersConfig(MaterialProvidersConfig.builder().build()) .build(); CreateAwsKmsHierarchicalKeyringInput keyringInput = CreateAwsKmsHierarchicalKeyringInput.builder() .branchKeyId(branchKeyId) .keyStore(keyStore) .ttlSeconds(6000l) .build(); final IKeyring kmsKeyring = matProv.CreateAwsKmsHierarchicalKeyring(keyringInput); // 5. Configure which attributes are encrypted and/or signed when writing new items. final Map<String, CryptoAction> attributeActionsOnEncrypt = new HashMap<>(); attributeActionsOnEncrypt.put("work_id", CryptoAction.SIGN_ONLY); // Our partition attribute must be SIGN_ONLY attributeActionsOnEncrypt.put("inspection_date", CryptoAction.SIGN_ONLY); // Our sort attribute must be SIGN_ONLY attributeActionsOnEncrypt.put("dessert", CryptoAction.ENCRYPT_AND_SIGN); // Beaconized attributes must be encrypted attributeActionsOnEncrypt.put("fruit", CryptoAction.ENCRYPT_AND_SIGN); // Beaconized attributes must be encrypted attributeActionsOnEncrypt.put("basket", CryptoAction.ENCRYPT_AND_SIGN); // Beaconized attributes must be encrypted // 6. Create the DynamoDb Encryption configuration for the table we will be writing to. // The beaconVersions are added to the search configuration. final Map<String, DynamoDbTableEncryptionConfig> tableConfigs = new HashMap<>(); final DynamoDbTableEncryptionConfig config = DynamoDbTableEncryptionConfig.builder() .logicalTableName(ddbTableName) .partitionKeyName("work_id") .sortKeyName("inspection_date") .attributeActionsOnEncrypt(attributeActionsOnEncrypt) .keyring(kmsKeyring) .search(SearchConfig.builder() .writeVersion(1) // MUST be 1 .versions(beaconVersions) .build()) .build(); tableConfigs.put(ddbTableName, config); // 7. Create config final DynamoDbTablesEncryptionConfig encryptionConfig = DynamoDbTablesEncryptionConfig.builder() .tableEncryptionConfigs(tableConfigs) .build(); // 8. Create item one, specifically with "dessert != fruit", and "fruit in basket". final HashMap<String, AttributeValue> item1 = new HashMap<>(); item1.put("work_id", AttributeValue.builder().s("1").build()); item1.put("inspection_date", AttributeValue.builder().s("2023-06-13").build()); item1.put("dessert", AttributeValue.builder().s("cake").build()); item1.put("fruit", AttributeValue.builder().s("banana").build()); ArrayList<String> basket = new ArrayList<String>(); basket.add("banana"); basket.add("apple"); basket.add("pear"); item1.put("basket", AttributeValue.builder().ss(basket).build()); // 9. Create item two, specifically with "dessert == fruit", and "fruit not in basket". final HashMap<String, AttributeValue> item2 = new HashMap<>(); item2.put("work_id", AttributeValue.builder().s("2").build()); item2.put("inspection_date", AttributeValue.builder().s("2023-06-13").build()); item2.put("fruit", AttributeValue.builder().s("orange").build()); item2.put("dessert", AttributeValue.builder().s("orange").build()); basket = new ArrayList<String>(); basket.add("strawberry"); basket.add("blueberry"); basket.add("blackberry"); item2.put("basket", AttributeValue.builder().ss(basket).build()); // 10. Create the DynamoDb Encryption Interceptor DynamoDbEncryptionInterceptor encryptionInterceptor = DynamoDbEncryptionInterceptor.builder() .config(encryptionConfig) .build(); // 11. Create a new AWS SDK DynamoDb client using the DynamoDb Encryption Interceptor above final DynamoDbClient ddb = DynamoDbClient.builder() .overrideConfiguration( ClientOverrideConfiguration.builder() .addExecutionInterceptor(encryptionInterceptor) .build()) .build(); // 12. Add the two items PutItemRequest putRequest = PutItemRequest.builder() .tableName(ddbTableName) .item(item1) .build(); PutItemResponse putResponse = ddb.putItem(putRequest); // Validate object put successfully assert 200 == putResponse.sdkHttpResponse().statusCode(); putRequest = PutItemRequest.builder() .tableName(ddbTableName) .item(item2) .build(); putResponse = ddb.putItem(putRequest); // Validate object put successfully assert 200 == putResponse.sdkHttpResponse().statusCode(); // 13. Test the first type of Set operation : // Select records where the basket attribute holds a particular value Map<String, AttributeValue> expressionAttributeValues = new HashMap<>(); expressionAttributeValues.put(":value", AttributeValue.builder().s("banana").build()); ScanRequest scanRequest = ScanRequest.builder() .tableName(ddbTableName) .filterExpression("contains(basket, :value)") .expressionAttributeValues(expressionAttributeValues) .build(); ScanResponse scanResponse = ddb.scan(scanRequest); // Validate query was returned successfully assert 200 == scanResponse.sdkHttpResponse().statusCode(); // Validate only 1 item was returned: item1 assert scanResponse.items().size() == 1; assert scanResponse.items().get(0).equals(item1); // 14. Test the second type of Set operation : // Select records where the basket attribute holds the fruit attribute scanRequest = ScanRequest.builder() .tableName(ddbTableName) .filterExpression("contains(basket, fruit)") .build(); scanResponse = ddb.scan(scanRequest); // Validate query was returned successfully assert 200 == scanResponse.sdkHttpResponse().statusCode(); // Validate only 1 item was returned: item1 assert scanResponse.items().size() == 1; assert scanResponse.items().get(0).equals(item1); // 15. Test the third type of Set operation : // Select records where the fruit attribute exists in a particular set ArrayList<String> basket3 = new ArrayList<String>(); basket3.add("boysenberry"); basket3.add("orange"); basket3.add("grape"); expressionAttributeValues.put(":value", AttributeValue.builder().ss(basket3).build()); scanRequest = ScanRequest.builder() .tableName(ddbTableName) .filterExpression("contains(:value, fruit)") .expressionAttributeValues(expressionAttributeValues) .build(); scanResponse = ddb.scan(scanRequest); // Validate query was returned successfully assert 200 == scanResponse.sdkHttpResponse().statusCode(); // Validate only 1 item was returned: item2 assert scanResponse.items().size() == 1; assert scanResponse.items().get(0).equals(item2); // Test a Shared search. Select records where the dessert attribute matches the fruit attribute scanRequest = ScanRequest.builder() .tableName(ddbTableName) .filterExpression("dessert = fruit") .build(); scanResponse = ddb.scan(scanRequest); // Validate query was returned successfully assert 200 == scanResponse.sdkHttpResponse().statusCode(); // Validate only 1 item was returned: item2 assert scanResponse.items().size() == 1; assert scanResponse.items().get(0).equals(item2); } public static void main(final String[] args) { if (args.length <= 1) { throw new IllegalArgumentException("To run this example, include ddbTableName as args[0], branchKeyId as args[1], " + "branchKeyWrappingKmsKeyId as args[2], and branchKeyDdbTableName as args[3]"); } final String ddbTableName = args[0]; final String branchKeyId = args[1]; final String branchKeyWrappingKmsKeyId = args[2]; final String branchKeyDdbTableName = args[3]; PutItemQueryItemWithBeaconStyles(ddbTableName, branchKeyId, branchKeyWrappingKmsKeyId, branchKeyDdbTableName); } }
5,266
0
Create_ds/aws-database-encryption-sdk-dynamodb-java/Examples/runtimes/java/DynamoDbEncryption/src/main/java/software/amazon/cryptography/examples/searchableencryption
Create_ds/aws-database-encryption-sdk-dynamodb-java/Examples/runtimes/java/DynamoDbEncryption/src/main/java/software/amazon/cryptography/examples/searchableencryption/complexexample/ComplexSearchableEncryptionExample.java
package software.amazon.cryptography.examples.searchableencryption.complexexample; import software.amazon.awssdk.services.dynamodb.DynamoDbClient; public class ComplexSearchableEncryptionExample { /* * This file is used in an example to demonstrate complex queries * you can perform using beacons. * The example data used is for demonstrative purposes only, * and might not meet the distribution and correlation uniqueness * recommendations for beacons. * See our documentation for whether beacons are * right for your particular data set: * https://docs.aws.amazon.com/database-encryption-sdk/latest/devguide/searchable-encryption.html#are-beacons-right-for-me */ public static void runExample(String ddbTableName, String branchKeyId, String branchKeyWrappingKmsKeyArn, String branchKeyDdbTableName) { DynamoDbClient ddb = BeaconConfig.SetupBeaconConfig(ddbTableName, branchKeyId, branchKeyWrappingKmsKeyArn, branchKeyDdbTableName); PutRequests.putAllItemsToTable(ddbTableName, ddb); QueryRequests.runQueries(ddbTableName, ddb); } public static void main(final String[] args) { if (args.length <= 1) { throw new IllegalArgumentException("To run this example, include ddbTableName as args[0], " + "branchKeyId as args[1], branchKeyWrappingKmsKeyId as args[2], and branchKeyDdbTableName as args[3]"); } final String ddbTableName = args[0]; final String branchKeyId = args[1]; final String branchKeyWrappingKmsKeyId = args[2]; final String branchKeyDdbTableName = args[3]; runExample(ddbTableName, branchKeyId, branchKeyWrappingKmsKeyId, branchKeyDdbTableName); } }
5,267
0
Create_ds/aws-database-encryption-sdk-dynamodb-java/Examples/runtimes/java/DynamoDbEncryption/src/main/java/software/amazon/cryptography/examples/searchableencryption
Create_ds/aws-database-encryption-sdk-dynamodb-java/Examples/runtimes/java/DynamoDbEncryption/src/main/java/software/amazon/cryptography/examples/searchableencryption/complexexample/PutRequests.java
package software.amazon.cryptography.examples.searchableencryption.complexexample; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import software.amazon.awssdk.services.dynamodb.DynamoDbClient; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; import software.amazon.awssdk.services.dynamodb.model.PutItemRequest; /* * This file is used in an example to demonstrate complex queries * you can perform using beacons. * The example data used is for demonstrative purposes only, * and might not meet the distribution and correlation uniqueness * recommendations for beacons. * See our documentation for whether beacons are * right for your particular data set: * https://docs.aws.amazon.com/database-encryption-sdk/latest/devguide/searchable-encryption.html#are-beacons-right-for-me * * This class implements PutItem calls to populate a DDB table with items from our workshop. * By providing a DynamoDbClient that is configured to use searchable encryption, * this class will encrypt the data client side and add beacon attributes to the items. * This only implements a single item of each of the 6 record types from Demo.md. Adding the remaining * items would extend the test and example coverage. */ public class PutRequests { public static void putAllItemsToTable(String ddbTableName, DynamoDbClient ddb) { putAllMeetingItemsToTable(ddbTableName, ddb); putAllEmployeeItemsToTable(ddbTableName, ddb); putAllProjectItemsToTable(ddbTableName, ddb); putAllReservationItemsToTable(ddbTableName, ddb); putAllTicketItemsToTable(ddbTableName, ddb); putAllTimecardItemsToTable(ddbTableName, ddb); } // emeeting.json public static void putAllMeetingItemsToTable(String ddbTableName, DynamoDbClient ddb) { final List<AttributeValue> meeting1AttendeeList = new ArrayList<>(); meeting1AttendeeList.add(AttributeValue.builder().s("able@gmail.com").build()); meeting1AttendeeList.add(AttributeValue.builder().s("zorro@gmail.com").build()); final HashMap<String, AttributeValue> meeting1Location = new HashMap<>(); meeting1Location.put("Floor", AttributeValue.builder().s("12").build()); meeting1Location.put("Room", AttributeValue.builder().s("403").build()); final HashMap<String, AttributeValue> meeting1 = new HashMap<>(); meeting1.put("partition_key", AttributeValue.builder().s("meeting1").build()); meeting1.put("EmployeeID", AttributeValue.builder().s("emp_001").build()); meeting1.put("EmployeeEmail", AttributeValue.builder().s("able@gmail.com").build()); meeting1.put("MeetingStart", AttributeValue.builder().s("2022-07-04T13:00").build()); meeting1.put("Location", AttributeValue.builder().m(meeting1Location).build()); meeting1.put("Duration", AttributeValue.builder().s("30").build()); meeting1.put("Attendees", AttributeValue.builder().l(meeting1AttendeeList).build()); meeting1.put("Subject", AttributeValue.builder().s("Scan Beacons").build()); ddb.putItem(PutItemRequest.builder() .tableName(ddbTableName) .item(meeting1) .build() ); final List<AttributeValue> meeting2AttendeeList = new ArrayList<>(); meeting2AttendeeList.add(AttributeValue.builder().s("barney@gmail.com").build()); meeting2AttendeeList.add(AttributeValue.builder().s("zorro@gmail.com").build()); final HashMap<String, AttributeValue> meeting2Location = new HashMap<>(); meeting2Location.put("Floor", AttributeValue.builder().s("12").build()); meeting2Location.put("Room", AttributeValue.builder().s("403").build()); final HashMap<String, AttributeValue> meeting2 = new HashMap<>(); meeting2.put("partition_key", AttributeValue.builder().s("meeting2").build()); meeting2.put("EmployeeID", AttributeValue.builder().s("emp_002").build()); meeting2.put("EmployeeEmail", AttributeValue.builder().s("barney@gmail.com").build()); meeting2.put("MeetingStart", AttributeValue.builder().s("2022-07-04T13:00").build()); meeting2.put("Location", AttributeValue.builder().m(meeting2Location).build()); meeting2.put("Duration", AttributeValue.builder().s("30").build()); meeting2.put("Attendees", AttributeValue.builder().l(meeting2AttendeeList).build()); meeting2.put("Subject", AttributeValue.builder().s("Scan Beacons").build()); ddb.putItem(PutItemRequest.builder() .tableName(ddbTableName) .item(meeting2) .build() ); final List<AttributeValue> meeting3AttendeeList = new ArrayList<>(); meeting3AttendeeList.add(AttributeValue.builder().s("charlie@gmail.com").build()); meeting3AttendeeList.add(AttributeValue.builder().s("zorro@gmail.com").build()); final HashMap<String, AttributeValue> meeting3Location = new HashMap<>(); meeting3Location.put("Floor", AttributeValue.builder().s("12").build()); meeting3Location.put("Room", AttributeValue.builder().s("403").build()); final HashMap<String, AttributeValue> meeting3 = new HashMap<>(); meeting3.put("partition_key", AttributeValue.builder().s("meeting3").build()); meeting3.put("EmployeeID", AttributeValue.builder().s("emp_003").build()); meeting3.put("EmployeeEmail", AttributeValue.builder().s("charlie@gmail.com").build()); meeting3.put("MeetingStart", AttributeValue.builder().s("2022-07-04T13:00").build()); meeting3.put("Location", AttributeValue.builder().m(meeting3Location).build()); meeting3.put("Duration", AttributeValue.builder().s("30").build()); meeting3.put("Attendees", AttributeValue.builder().l(meeting3AttendeeList).build()); meeting3.put("Subject", AttributeValue.builder().s("Scan Beacons").build()); ddb.putItem(PutItemRequest.builder() .tableName(ddbTableName) .item(meeting3) .build() ); final List<AttributeValue> meeting4AttendeeList = new ArrayList<>(); meeting4AttendeeList.add(AttributeValue.builder().s("david@gmail.com").build()); meeting4AttendeeList.add(AttributeValue.builder().s("zorro@gmail.com").build()); final HashMap<String, AttributeValue> meeting4Location = new HashMap<>(); meeting4Location.put("Floor", AttributeValue.builder().s("12").build()); meeting4Location.put("Room", AttributeValue.builder().s("403").build()); final HashMap<String, AttributeValue> meeting4 = new HashMap<>(); meeting4.put("partition_key", AttributeValue.builder().s("meeting4").build()); meeting4.put("EmployeeID", AttributeValue.builder().s("emp_004").build()); meeting4.put("EmployeeEmail", AttributeValue.builder().s("david@gmail.com").build()); meeting4.put("MeetingStart", AttributeValue.builder().s("2022-07-04T13:00").build()); meeting4.put("Location", AttributeValue.builder().m(meeting4Location).build()); meeting4.put("Duration", AttributeValue.builder().s("30").build()); meeting4.put("Attendees", AttributeValue.builder().l(meeting4AttendeeList).build()); meeting4.put("Subject", AttributeValue.builder().s("Scan Beacons").build()); ddb.putItem(PutItemRequest.builder() .tableName(ddbTableName) .item(meeting4) .build() ); final List<AttributeValue> meeting5AttendeeList = new ArrayList<>(); meeting5AttendeeList.add(AttributeValue.builder().s("barney@gmail.com").build()); meeting5AttendeeList.add(AttributeValue.builder().s("zorro@gmail.com").build()); final HashMap<String, AttributeValue> meeting5Location = new HashMap<>(); meeting5Location.put("Floor", AttributeValue.builder().s("12").build()); meeting5Location.put("Room", AttributeValue.builder().s("407").build()); final HashMap<String, AttributeValue> meeting5 = new HashMap<>(); meeting5.put("partition_key", AttributeValue.builder().s("meeting5").build()); meeting5.put("EmployeeID", AttributeValue.builder().s("emp_002").build()); meeting5.put("EmployeeEmail", AttributeValue.builder().s("barney@gmail.com").build()); meeting5.put("MeetingStart", AttributeValue.builder().s("2022-07-04T14:00").build()); meeting5.put("Location", AttributeValue.builder().m(meeting5Location).build()); meeting5.put("Duration", AttributeValue.builder().s("30").build()); meeting5.put("Attendees", AttributeValue.builder().l(meeting5AttendeeList).build()); meeting5.put("Subject", AttributeValue.builder().s("DB ESDK").build()); ddb.putItem(PutItemRequest.builder() .tableName(ddbTableName) .item(meeting5) .build() ); final List<AttributeValue> meeting6AttendeeList = new ArrayList<>(); meeting6AttendeeList.add(AttributeValue.builder().s("charlie@gmail.com").build()); meeting6AttendeeList.add(AttributeValue.builder().s("zorro@gmail.com").build()); final HashMap<String, AttributeValue> meeting6Location = new HashMap<>(); meeting6Location.put("Floor", AttributeValue.builder().s("12").build()); meeting6Location.put("Room", AttributeValue.builder().s("407").build()); final HashMap<String, AttributeValue> meeting6 = new HashMap<>(); meeting6.put("partition_key", AttributeValue.builder().s("meeting6").build()); meeting6.put("EmployeeID", AttributeValue.builder().s("emp_003").build()); meeting6.put("EmployeeEmail", AttributeValue.builder().s("charlie@gmail.com").build()); meeting6.put("MeetingStart", AttributeValue.builder().s("2022-07-04T14:00").build()); meeting6.put("Location", AttributeValue.builder().m(meeting6Location).build()); meeting6.put("Duration", AttributeValue.builder().s("30").build()); meeting6.put("Attendees", AttributeValue.builder().l(meeting6AttendeeList).build()); meeting6.put("Subject", AttributeValue.builder().s("DB ESDK").build()); ddb.putItem(PutItemRequest.builder() .tableName(ddbTableName) .item(meeting6) .build() ); } // employee.json public static void putAllEmployeeItemsToTable(String ddbTableName, DynamoDbClient ddb) { final HashMap<String, AttributeValue> employee1Location = new HashMap<>(); employee1Location.put("Building", AttributeValue.builder().s("44").build()); employee1Location.put("Floor", AttributeValue.builder().s("12").build()); employee1Location.put("Desk", AttributeValue.builder().s("3").build()); employee1Location.put("City", AttributeValue.builder().s("Seattle").build()); final HashMap<String, AttributeValue> employee1 = new HashMap<>(); employee1.put("partition_key", AttributeValue.builder().s("employee1").build()); employee1.put("EmployeeID", AttributeValue.builder().s("emp_001").build()); employee1.put("EmployeeEmail", AttributeValue.builder().s("able@gmail.com").build()); employee1.put("ManagerEmail", AttributeValue.builder().s("zorro@gmail.com").build()); employee1.put("EmployeeName", AttributeValue.builder().s("Able Jones").build()); employee1.put("EmployeeTitle", AttributeValue.builder().s("SDE9").build()); employee1.put("Location", AttributeValue.builder().m(employee1Location).build()); ddb.putItem(PutItemRequest.builder() .tableName(ddbTableName) .item(employee1) .build() ); final HashMap<String, AttributeValue> employee2Location = new HashMap<>(); employee2Location.put("Building", AttributeValue.builder().s("44").build()); employee2Location.put("Floor", AttributeValue.builder().s("12").build()); employee2Location.put("Desk", AttributeValue.builder().s("4").build()); employee2Location.put("City", AttributeValue.builder().s("Seattle").build()); final HashMap<String, AttributeValue> employee2 = new HashMap<>(); employee2.put("partition_key", AttributeValue.builder().s("employee2").build()); employee2.put("EmployeeID", AttributeValue.builder().s("emp_002").build()); employee2.put("EmployeeEmail", AttributeValue.builder().s("barney@gmail.com").build()); employee2.put("ManagerEmail", AttributeValue.builder().s("zorro@gmail.com").build()); employee2.put("EmployeeName", AttributeValue.builder().s("Barney Jones").build()); employee2.put("EmployeeTitle", AttributeValue.builder().s("SDE8").build()); employee2.put("Location", AttributeValue.builder().m(employee2Location).build()); ddb.putItem(PutItemRequest.builder() .tableName(ddbTableName) .item(employee2) .build() ); final HashMap<String, AttributeValue> employee3Location = new HashMap<>(); employee3Location.put("Building", AttributeValue.builder().s("44").build()); employee3Location.put("Floor", AttributeValue.builder().s("4").build()); employee3Location.put("Desk", AttributeValue.builder().s("5").build()); employee3Location.put("City", AttributeValue.builder().s("Seattle").build()); final HashMap<String, AttributeValue> employee3 = new HashMap<>(); employee3.put("partition_key", AttributeValue.builder().s("employee3").build()); employee3.put("EmployeeID", AttributeValue.builder().s("emp_003").build()); employee3.put("EmployeeEmail", AttributeValue.builder().s("charlie@gmail.com").build()); employee3.put("ManagerEmail", AttributeValue.builder().s("zorro@gmail.com").build()); employee3.put("EmployeeName", AttributeValue.builder().s("Charlie Jones").build()); employee3.put("EmployeeTitle", AttributeValue.builder().s("SDE7").build()); employee3.put("Location", AttributeValue.builder().m(employee3Location).build()); ddb.putItem(PutItemRequest.builder() .tableName(ddbTableName) .item(employee3) .build() ); final HashMap<String, AttributeValue> employee4Location = new HashMap<>(); employee4Location.put("Building", AttributeValue.builder().s("22").build()); employee4Location.put("Floor", AttributeValue.builder().s("1").build()); employee4Location.put("Desk", AttributeValue.builder().s("3").build()); employee4Location.put("City", AttributeValue.builder().s("NYC").build()); final HashMap<String, AttributeValue> employee4 = new HashMap<>(); employee4.put("partition_key", AttributeValue.builder().s("employee4").build()); employee4.put("EmployeeID", AttributeValue.builder().s("emp_004").build()); employee4.put("EmployeeEmail", AttributeValue.builder().s("david@gmail.com").build()); employee4.put("ManagerEmail", AttributeValue.builder().s("zorro@gmail.com").build()); employee4.put("EmployeeName", AttributeValue.builder().s("David Jones").build()); employee4.put("EmployeeTitle", AttributeValue.builder().s("SDE6").build()); employee4.put("Location", AttributeValue.builder().m(employee4Location).build()); ddb.putItem(PutItemRequest.builder() .tableName(ddbTableName) .item(employee4) .build() ); } // project.json public static void putAllProjectItemsToTable(String ddbTableName, DynamoDbClient ddb) { final HashMap<String, AttributeValue> project1 = new HashMap<>(); project1.put("partition_key", AttributeValue.builder().s("project1").build()); project1.put("ProjectName", AttributeValue.builder().s("project_001").build()); project1.put("ProjectStatus", AttributeValue.builder().s("Pending").build()); project1.put("ProjectStart", AttributeValue.builder().s("2022-11-01").build()); project1.put("Description", AttributeValue.builder().s("Turbo Crypto").build()); project1.put("ProjectTarget", AttributeValue.builder().s("2024-01-01").build()); ddb.putItem(PutItemRequest.builder() .tableName(ddbTableName) .item(project1) .build() ); final HashMap<String, AttributeValue> project2 = new HashMap<>(); project2.put("partition_key", AttributeValue.builder().s("project2").build()); project2.put("ProjectName", AttributeValue.builder().s("project_002").build()); project2.put("ProjectStatus", AttributeValue.builder().s("Active").build()); project2.put("ProjectStart", AttributeValue.builder().s("2022-07-04").build()); project2.put("Description", AttributeValue.builder().s("Scan Beacons").build()); project2.put("ProjectTarget", AttributeValue.builder().s("2024-01-01").build()); ddb.putItem(PutItemRequest.builder() .tableName(ddbTableName) .item(project2) .build() ); final HashMap<String, AttributeValue> project3 = new HashMap<>(); project3.put("partition_key", AttributeValue.builder().s("project3").build()); project3.put("ProjectName", AttributeValue.builder().s("project_003").build()); project3.put("ProjectStatus", AttributeValue.builder().s("Active").build()); project3.put("ProjectStart", AttributeValue.builder().s("2022-08-05").build()); project3.put("Description", AttributeValue.builder().s("DB ESDK").build()); project3.put("ProjectTarget", AttributeValue.builder().s("2023-02-27").build()); ddb.putItem(PutItemRequest.builder() .tableName(ddbTableName) .item(project3) .build() ); final HashMap<String, AttributeValue> project4 = new HashMap<>(); project4.put("partition_key", AttributeValue.builder().s("project4").build()); project4.put("ProjectName", AttributeValue.builder().s("project_004").build()); project4.put("ProjectStatus", AttributeValue.builder().s("Done").build()); project4.put("ProjectStart", AttributeValue.builder().s("2020-03-03").build()); project4.put("Description", AttributeValue.builder().s("S3EC").build()); project4.put("ProjectTarget", AttributeValue.builder().s("2021-09-05").build()); ddb.putItem(PutItemRequest.builder() .tableName(ddbTableName) .item(project4) .build() ); } // reservation.json public static void putAllReservationItemsToTable(String ddbTableName, DynamoDbClient ddb) { final List<AttributeValue> reservation1AttendeeList = new ArrayList<>(); reservation1AttendeeList.add(AttributeValue.builder().s("able@gmail.com").build()); reservation1AttendeeList.add(AttributeValue.builder().s("barney@gmail.com").build()); final HashMap<String, AttributeValue> reservation1Location = new HashMap<>(); reservation1Location.put("Building", AttributeValue.builder().s("SEA33").build()); reservation1Location.put("Floor", AttributeValue.builder().s("12").build()); reservation1Location.put("Room", AttributeValue.builder().s("403").build()); final HashMap<String, AttributeValue> reservation1 = new HashMap<>(); reservation1.put("partition_key", AttributeValue.builder().s("reservation1").build()); reservation1.put("Location", AttributeValue.builder().m(reservation1Location).build()); reservation1.put("MeetingStart", AttributeValue.builder().s("2022-07-04T13:00").build()); reservation1.put("OrganizerEmail", AttributeValue.builder().s("able@gmail.com").build()); reservation1.put("Duration", AttributeValue.builder().s("30").build()); reservation1.put("Attendees", AttributeValue.builder().l(reservation1AttendeeList).build()); reservation1.put("Subject", AttributeValue.builder().s("Scan beacons").build()); ddb.putItem(PutItemRequest.builder() .tableName(ddbTableName) .item(reservation1) .build() ); final List<AttributeValue> reservation2AttendeeList = new ArrayList<>(); reservation2AttendeeList.add(AttributeValue.builder().s("able@gmail.com").build()); reservation2AttendeeList.add(AttributeValue.builder().s("barney@gmail.com").build()); final HashMap<String, AttributeValue> reservation2Location = new HashMap<>(); reservation2Location.put("Building", AttributeValue.builder().s("SEA33").build()); reservation2Location.put("Floor", AttributeValue.builder().s("12").build()); reservation2Location.put("Room", AttributeValue.builder().s("407").build()); final HashMap<String, AttributeValue> reservation2 = new HashMap<>(); reservation2.put("partition_key", AttributeValue.builder().s("reservation2").build()); reservation2.put("Location", AttributeValue.builder().m(reservation2Location).build()); reservation2.put("MeetingStart", AttributeValue.builder().s("2022-07-04T14:00").build()); reservation2.put("OrganizerEmail", AttributeValue.builder().s("barney@gmail.com").build()); reservation2.put("Duration", AttributeValue.builder().s("30").build()); reservation2.put("Attendees", AttributeValue.builder().l(reservation2AttendeeList).build()); reservation2.put("Subject", AttributeValue.builder().s("DB ESDK").build()); ddb.putItem(PutItemRequest.builder() .tableName(ddbTableName) .item(reservation2) .build() ); } // ticket.json public static void putAllTicketItemsToTable(String ddbTableName, DynamoDbClient ddb) { final HashMap<String, AttributeValue> ticket1 = new HashMap<>(); ticket1.put("partition_key", AttributeValue.builder().s("ticket1").build()); ticket1.put("TicketNumber", AttributeValue.builder().s("ticket_001").build()); ticket1.put("TicketModTime", AttributeValue.builder().s("2022-10-07T14:32:25").build()); ticket1.put("CreatorEmail", AttributeValue.builder().s("zorro@gmail.com").build()); ticket1.put("AssigneeEmail", AttributeValue.builder().s("able@gmail.com").build()); ticket1.put("Severity", AttributeValue.builder().s("3").build()); ticket1.put("Subject", AttributeValue.builder().s("Bad bug").build()); ticket1.put("Message", AttributeValue.builder().s("This bug looks pretty bad").build()); ddb.putItem(PutItemRequest.builder() .tableName(ddbTableName) .item(ticket1) .build() ); final HashMap<String, AttributeValue> ticket2 = new HashMap<>(); ticket2.put("partition_key", AttributeValue.builder().s("ticket2").build()); ticket2.put("TicketNumber", AttributeValue.builder().s("ticket_001").build()); ticket2.put("TicketModTime", AttributeValue.builder().s("2022-10-07T14:32:25").build()); ticket2.put("CreatorEmail", AttributeValue.builder().s("able@gmail.com").build()); ticket2.put("AssigneeEmail", AttributeValue.builder().s("charlie@gmail.com").build()); ticket2.put("Severity", AttributeValue.builder().s("3").build()); ticket2.put("Subject", AttributeValue.builder().s("Bad bug").build()); ticket2.put("Message", AttributeValue.builder().s("Charlie should handle this").build()); ddb.putItem(PutItemRequest.builder() .tableName(ddbTableName) .item(ticket2) .build() ); final HashMap<String, AttributeValue> ticket3 = new HashMap<>(); ticket3.put("partition_key", AttributeValue.builder().s("ticket3").build()); ticket3.put("TicketNumber", AttributeValue.builder().s("ticket_002").build()); ticket3.put("TicketModTime", AttributeValue.builder().s("2022-10-06T14:32:25").build()); ticket3.put("CreatorEmail", AttributeValue.builder().s("zorro@gmail.com").build()); ticket3.put("AssigneeEmail", AttributeValue.builder().s("charlie@gmail.com").build()); ticket3.put("Severity", AttributeValue.builder().s("3").build()); ticket3.put("Subject", AttributeValue.builder().s("Easy Bug").build()); ticket3.put("Message", AttributeValue.builder().s("This seems simple enough").build()); ddb.putItem(PutItemRequest.builder() .tableName(ddbTableName) .item(ticket3) .build() ); final HashMap<String, AttributeValue> ticket4 = new HashMap<>(); ticket4.put("partition_key", AttributeValue.builder().s("ticket4").build()); ticket4.put("TicketNumber", AttributeValue.builder().s("ticket_002").build()); ticket4.put("TicketModTime", AttributeValue.builder().s("2022-10-08T14:32:25").build()); ticket4.put("CreatorEmail", AttributeValue.builder().s("charlie@gmail.com").build()); ticket4.put("AssigneeEmail", AttributeValue.builder().s("able@gmail.com").build()); ticket4.put("Severity", AttributeValue.builder().s("3").build()); ticket4.put("Subject", AttributeValue.builder().s("Easy Bug").build()); ticket4.put("Message", AttributeValue.builder().s("that's in able's code").build()); ddb.putItem(PutItemRequest.builder() .tableName(ddbTableName) .item(ticket4) .build() ); } // timecard.json public static void putAllTimecardItemsToTable(String ddbTableName, DynamoDbClient ddb) { final HashMap<String, AttributeValue> timecard1 = new HashMap<>(); timecard1.put("partition_key", AttributeValue.builder().s("timecard1").build()); timecard1.put("ProjectName", AttributeValue.builder().s("project_002").build()); timecard1.put("TimeCardStart", AttributeValue.builder().s("2022-09-12").build()); timecard1.put("EmployeeEmail", AttributeValue.builder().s("able@gmail.com").build()); timecard1.put("Hours", AttributeValue.builder().s("40").build()); timecard1.put("Role", AttributeValue.builder().s("SDE3").build()); ddb.putItem(PutItemRequest.builder() .tableName(ddbTableName) .item(timecard1) .build() ); final HashMap<String, AttributeValue> timecard2 = new HashMap<>(); timecard2.put("partition_key", AttributeValue.builder().s("timecard2").build()); timecard2.put("ProjectName", AttributeValue.builder().s("project_002").build()); timecard2.put("TimeCardStart", AttributeValue.builder().s("2022-09-12").build()); timecard2.put("EmployeeEmail", AttributeValue.builder().s("barney@gmail.com").build()); timecard2.put("Hours", AttributeValue.builder().s("20").build()); timecard2.put("Role", AttributeValue.builder().s("PM").build()); ddb.putItem(PutItemRequest.builder() .tableName(ddbTableName) .item(timecard2) .build() ); final HashMap<String, AttributeValue> timecard3 = new HashMap<>(); timecard3.put("partition_key", AttributeValue.builder().s("timecard3").build()); timecard3.put("ProjectName", AttributeValue.builder().s("project_003").build()); timecard3.put("TimeCardStart", AttributeValue.builder().s("2022-09-12").build()); timecard3.put("EmployeeEmail", AttributeValue.builder().s("charlie@gmail.com").build()); timecard3.put("Hours", AttributeValue.builder().s("40").build()); timecard3.put("Role", AttributeValue.builder().s("SDE3").build()); ddb.putItem(PutItemRequest.builder() .tableName(ddbTableName) .item(timecard3) .build() ); final HashMap<String, AttributeValue> timecard4 = new HashMap<>(); timecard4.put("partition_key", AttributeValue.builder().s("timecard4").build()); timecard4.put("ProjectName", AttributeValue.builder().s("project_003").build()); timecard4.put("TimeCardStart", AttributeValue.builder().s("2022-09-12").build()); timecard4.put("EmployeeEmail", AttributeValue.builder().s("barney@gmail.com").build()); timecard4.put("Hours", AttributeValue.builder().s("20").build()); timecard4.put("Role", AttributeValue.builder().s("PM").build()); ddb.putItem(PutItemRequest.builder() .tableName(ddbTableName) .item(timecard4) .build() ); } }
5,268
0
Create_ds/aws-database-encryption-sdk-dynamodb-java/Examples/runtimes/java/DynamoDbEncryption/src/main/java/software/amazon/cryptography/examples/searchableencryption
Create_ds/aws-database-encryption-sdk-dynamodb-java/Examples/runtimes/java/DynamoDbEncryption/src/main/java/software/amazon/cryptography/examples/searchableencryption/complexexample/BeaconConfig.java
package software.amazon.cryptography.examples.searchableencryption.complexexample; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import software.amazon.awssdk.core.client.config.ClientOverrideConfiguration; import software.amazon.awssdk.services.dynamodb.DynamoDbClient; import software.amazon.awssdk.services.kms.KmsClient; import software.amazon.cryptography.dbencryptionsdk.dynamodb.model.BeaconKeySource; import software.amazon.cryptography.dbencryptionsdk.dynamodb.model.BeaconVersion; import software.amazon.cryptography.dbencryptionsdk.dynamodb.model.CompoundBeacon; import software.amazon.cryptography.dbencryptionsdk.dynamodb.model.Constructor; import software.amazon.cryptography.dbencryptionsdk.dynamodb.model.ConstructorPart; import software.amazon.cryptography.dbencryptionsdk.dynamodb.model.DynamoDbTableEncryptionConfig; import software.amazon.cryptography.dbencryptionsdk.dynamodb.model.DynamoDbTablesEncryptionConfig; import software.amazon.cryptography.dbencryptionsdk.dynamodb.model.SignedPart; import software.amazon.cryptography.dbencryptionsdk.dynamodb.model.SearchConfig; import software.amazon.cryptography.dbencryptionsdk.dynamodb.model.EncryptedPart; import software.amazon.cryptography.dbencryptionsdk.dynamodb.model.SingleKeyStore; import software.amazon.cryptography.dbencryptionsdk.dynamodb.model.StandardBeacon; import software.amazon.cryptography.keystore.KeyStore; import software.amazon.cryptography.keystore.model.CreateKeyOutput; import software.amazon.cryptography.keystore.model.KMSConfiguration; import software.amazon.cryptography.keystore.model.KeyStoreConfig; import software.amazon.cryptography.materialproviders.IKeyring; import software.amazon.cryptography.materialproviders.MaterialProviders; import software.amazon.cryptography.materialproviders.model.CreateAwsKmsHierarchicalKeyringInput; import software.amazon.cryptography.materialproviders.model.MaterialProvidersConfig; import software.amazon.cryptography.dbencryptionsdk.structuredencryption.model.CryptoAction; import software.amazon.cryptography.dbencryptionsdk.dynamodb.DynamoDbEncryptionInterceptor; public class BeaconConfig { /* * This file is used in an example to demonstrate complex queries * you can perform using beacons. * The example data used is for demonstrative purposes only, * and might not meet the distribution and correlation uniqueness * recommendations for beacons. * See our documentation for whether beacons are * right for your particular data set: * https://docs.aws.amazon.com/database-encryption-sdk/latest/devguide/searchable-encryption.html#are-beacons-right-for-me * * This file sets up all the searchable encryption configuration required to execute the examples from * our workshop using the encryption client. */ public static DynamoDbClient SetupBeaconConfig(String ddbTableName, String branchKeyId, String branchKeyWrappingKmsKeyArn, String branchKeyDdbTableName) { // 1. Create Keystore and branch key. // These are the same constructions as in the Basic examples, which describe this in more detail. KeyStore keyStore = KeyStore.builder() .KeyStoreConfig(KeyStoreConfig.builder() .kmsClient(KmsClient.create()) .ddbClient(DynamoDbClient.create()) .ddbTableName(branchKeyDdbTableName) .logicalKeyStoreName(branchKeyDdbTableName) .kmsConfiguration(KMSConfiguration.builder().kmsKeyArn(branchKeyWrappingKmsKeyArn).build()) .build()) .build(); // 2. Create standard beacons // For this example, we use a standard beacon length of 4. // The BasicSearchableEncryptionExample gives a more thorough consideration of beacon length. // For production applications, one should always exercise rigor when deciding beacon length, including // examining population size and considering performance. StandardBeacon employeeIDStandardBeacon = StandardBeacon.builder() .name("EmployeeID") .length(4) .build(); StandardBeacon ticketNumberStandardBeacon = StandardBeacon.builder() .name("TicketNumber") .length(4) .build(); StandardBeacon projectNameStandardBeacon = StandardBeacon.builder() .name("ProjectName") .length(4) .build(); StandardBeacon employeeEmailStandardBeacon = StandardBeacon.builder() .name("EmployeeEmail") .length(4) .build(); StandardBeacon creatorEmailStandardBeacon = StandardBeacon.builder() .name("CreatorEmail") .length(4) .build(); StandardBeacon projectStatusStandardBeacon = StandardBeacon.builder() .name("ProjectStatus") .length(4) .build(); StandardBeacon organizerEmailStandardBeacon = StandardBeacon.builder() .name("OrganizerEmail") .length(4) .build(); StandardBeacon managerEmailStandardBeacon = StandardBeacon.builder() .name("ManagerEmail") .length(4) .build(); StandardBeacon assigneeEmailStandardBeacon = StandardBeacon.builder() .name("AssigneeEmail") .length(4) .build(); StandardBeacon cityStandardBeacon = StandardBeacon.builder() .name("City") .loc("Location.City") .length(4) .build(); StandardBeacon severityStandardBeacon = StandardBeacon.builder() .name("Severity") .length(4) .build(); StandardBeacon buildingStandardBeacon = StandardBeacon.builder() .name("Building") .loc("Location.Building") .length(4) .build(); StandardBeacon floorStandardBeacon = StandardBeacon.builder() .name("Floor") .loc("Location.Floor") .length(4) .build(); StandardBeacon roomStandardBeacon = StandardBeacon.builder() .name("Room") .loc("Location.Room") .length(4) .build(); StandardBeacon deskStandardBeacon = StandardBeacon.builder() .name("Desk") .loc("Location.Desk") .length(4) .build(); List<StandardBeacon> standardBeaconList = new ArrayList<>(); standardBeaconList.add(employeeIDStandardBeacon); standardBeaconList.add(ticketNumberStandardBeacon); standardBeaconList.add(projectNameStandardBeacon); standardBeaconList.add(employeeEmailStandardBeacon); standardBeaconList.add(creatorEmailStandardBeacon); standardBeaconList.add(projectStatusStandardBeacon); standardBeaconList.add(organizerEmailStandardBeacon); standardBeaconList.add(managerEmailStandardBeacon); standardBeaconList.add(assigneeEmailStandardBeacon); standardBeaconList.add(cityStandardBeacon); standardBeaconList.add(severityStandardBeacon); standardBeaconList.add(buildingStandardBeacon); standardBeaconList.add(floorStandardBeacon); standardBeaconList.add(roomStandardBeacon); standardBeaconList.add(deskStandardBeacon); // 3. Define encrypted parts // Note that some of the prefixes are modified from the suggested prefixes in Demo.md. // This is because all prefixes must be unique in a configuration. // Encrypted parts are described in more detail in the CompoundBeaconSearcbaleEncryptionExample. EncryptedPart employeeIDEncryptedPart = EncryptedPart.builder() .name("EmployeeID") .prefix("E-") .build(); EncryptedPart ticketNumberEncryptedPart = EncryptedPart.builder() .name("TicketNumber") .prefix("T-") .build(); EncryptedPart projectNameEncryptedPart = EncryptedPart.builder() .name("ProjectName") .prefix("P-") .build(); EncryptedPart employeeEmailEncryptedPart = EncryptedPart.builder() .name("EmployeeEmail") .prefix("EE-") .build(); EncryptedPart creatorEmailEncryptedPart = EncryptedPart.builder() .name("CreatorEmail") .prefix("CE-") .build(); EncryptedPart projectStatusEncryptedPart = EncryptedPart.builder() .name("ProjectStatus") .prefix("PSts-") .build(); EncryptedPart organizerEmailEncryptedPart = EncryptedPart.builder() .name("OrganizerEmail") .prefix("OE-") .build(); EncryptedPart managerEmailEncryptedPart = EncryptedPart.builder() .name("ManagerEmail") .prefix("ME-") .build(); EncryptedPart assigneeEmailEncryptedPart = EncryptedPart.builder() .name("AssigneeEmail") .prefix("AE-") .build(); EncryptedPart cityEncryptedPart = EncryptedPart.builder() .name("City") .prefix("C-") .build(); EncryptedPart severityEncryptedPart = EncryptedPart.builder() .name("Severity") .prefix("S-") .build(); EncryptedPart buildingEncryptedPart = EncryptedPart.builder() .name("Building") .prefix("B-") .build(); EncryptedPart floorEncryptedPart = EncryptedPart.builder() .name("Floor") .prefix("F-") .build(); EncryptedPart roomEncryptedPart = EncryptedPart.builder() .name("Room") .prefix("R-") .build(); EncryptedPart deskEncryptedPart = EncryptedPart.builder() .name("Desk") .prefix("D-") .build(); // 4. Define signed parts. // These are unencrypted attributes we would like to use in beacon queries. // In this example, all of these represent dates or times. // Keeping these attributes unencrypted allows us to use them in comparison-based queries. If a signed // part is the first part in a compound beacon, then that part can be used in comparison for sorting. SignedPart ticketModTimeSignedPart = SignedPart.builder() .name("TicketModTime") .prefix("M-") .build(); SignedPart meetingStartSignedPart = SignedPart.builder() .name("MeetingStart") .prefix("MS-") .build(); SignedPart timeCardStartSignedPart = SignedPart.builder() .name("TimeCardStart") .prefix("TC-") .build(); SignedPart projectStartSignedPart = SignedPart.builder() .name("ProjectStart") .prefix("PS-") .build(); // 5. Create lists of encrypted and signed parts for each GSI key List<EncryptedPart> pk0EncryptedPartList = new ArrayList<>(); pk0EncryptedPartList.add(employeeIDEncryptedPart); pk0EncryptedPartList.add(ticketNumberEncryptedPart); pk0EncryptedPartList.add(projectNameEncryptedPart); pk0EncryptedPartList.add(buildingEncryptedPart); List<EncryptedPart> sk0EncryptedPartList = new ArrayList<>(); sk0EncryptedPartList.add(employeeIDEncryptedPart); sk0EncryptedPartList.add(floorEncryptedPart); sk0EncryptedPartList.add(roomEncryptedPart); sk0EncryptedPartList.add(projectNameEncryptedPart); sk0EncryptedPartList.add(employeeEmailEncryptedPart); List<SignedPart> sk0SignedPartList = new ArrayList<>(); sk0SignedPartList.add(timeCardStartSignedPart); sk0SignedPartList.add(ticketModTimeSignedPart); sk0SignedPartList.add(meetingStartSignedPart); List<EncryptedPart> pk1EncryptedPartList = new ArrayList<>(); pk1EncryptedPartList.add(creatorEmailEncryptedPart); pk1EncryptedPartList.add(projectStatusEncryptedPart); pk1EncryptedPartList.add(organizerEmailEncryptedPart); pk1EncryptedPartList.add(employeeEmailEncryptedPart); List<EncryptedPart> sk1EncryptedPartList = new ArrayList<>(); sk1EncryptedPartList.add(floorEncryptedPart); sk1EncryptedPartList.add(roomEncryptedPart); sk1EncryptedPartList.add(employeeIDEncryptedPart); List<SignedPart> sk1SignedPartList = new ArrayList<>(); sk1SignedPartList.add(timeCardStartSignedPart); sk1SignedPartList.add(ticketModTimeSignedPart); sk1SignedPartList.add(meetingStartSignedPart); sk1SignedPartList.add(projectStartSignedPart); List<EncryptedPart> pk2EncryptedPartList = new ArrayList<>(); pk2EncryptedPartList.add(managerEmailEncryptedPart); pk2EncryptedPartList.add(assigneeEmailEncryptedPart); List<EncryptedPart> pk3EncryptedPartList = new ArrayList<>(); pk3EncryptedPartList.add(cityEncryptedPart); pk3EncryptedPartList.add(severityEncryptedPart); List<EncryptedPart> sk3EncryptedPartList = new ArrayList<>(); sk3EncryptedPartList.add(buildingEncryptedPart); sk3EncryptedPartList.add(floorEncryptedPart); sk3EncryptedPartList.add(deskEncryptedPart); List<SignedPart> sk3SignedPartList = new ArrayList<>(); sk3SignedPartList.add(ticketModTimeSignedPart); // 6. Create constructor parts. // Constructor parts are used to assemble constructors (constructors described more in next step). // For each attribute that will be used in a constructor, there must be a corresponding constructor part. // A constructor part must receive: // - name: Name of a standard beacon // - required: Whether this attribute must be present in the item to match a constructor // In this example, we will define each constructor part once and re-use it across multiple constructors. // The parts below are defined by working backwards from the constructors in "PK Constructors", // "SK constructors", etc. sections in Demo.md. ConstructorPart employeeIdConstructorPart = ConstructorPart.builder() // This name comes from the "EmployeeID" standard beacon. .name("EmployeeID") .required(true) .build(); ConstructorPart ticketNumberConstructorPart = ConstructorPart.builder() .name("TicketNumber") .required(true) .build(); ConstructorPart projectNameConstructorPart = ConstructorPart.builder() .name("ProjectName") .required(true) .build(); ConstructorPart ticketModTimeConstructorPart = ConstructorPart.builder() .name("TicketModTime") .required(true) .build(); ConstructorPart meetingStartConstructorPart = ConstructorPart.builder() .name("MeetingStart") .required(true) .build(); ConstructorPart timeCardStartConstructorPart = ConstructorPart.builder() .name("TimeCardStart") .required(true) .build(); ConstructorPart employeeEmailConstructorPart = ConstructorPart.builder() .name("EmployeeEmail") .required(true) .build(); ConstructorPart creatorEmailConstructorPart = ConstructorPart.builder() .name("CreatorEmail") .required(true) .build(); ConstructorPart projectStatusConstructorPart = ConstructorPart.builder() .name("ProjectStatus") .required(true) .build(); ConstructorPart organizerEmailConstructorPart = ConstructorPart.builder() .name("OrganizerEmail") .required(true) .build(); ConstructorPart projectStartConstructorPart = ConstructorPart.builder() .name("ProjectStart") .required(true) .build(); ConstructorPart managerEmailConstructorPart = ConstructorPart.builder() .name("ManagerEmail") .required(true) .build(); ConstructorPart assigneeEmailConstructorPart = ConstructorPart.builder() .name("AssigneeEmail") .required(true) .build(); ConstructorPart cityConstructorPart = ConstructorPart.builder() .name("City") .required(true) .build(); ConstructorPart severityConstructorPart = ConstructorPart.builder() .name("Severity") .required(true) .build(); ConstructorPart buildingConstructorPart = ConstructorPart.builder() .name("Building") .required(true) .build(); ConstructorPart floorConstructorPart = ConstructorPart.builder() .name("Floor") .required(true) .build(); ConstructorPart roomConstructorPart = ConstructorPart.builder() .name("Room") .required(true) .build(); ConstructorPart deskConstructorPart = ConstructorPart.builder() .name("Desk") .required(true) .build(); // 7. Define constructors // Constructors define how encrypted and signed parts are assembled into compound beacons. // The constructors below are based off of the "PK Constructors", "SK constructors", etc. sections in Demo.md. // The employee ID constructor only requires an employee ID. // If an item has an attribute with name "EmployeeID", it will match this constructor. // If this is the first matching constructor in the constructor list (constructor list described more below), // the compound beacon will use this constructor, and the compound beacon will be written as `E-X`. List<ConstructorPart> employeeIdConstructorPartList = new ArrayList<>(); employeeIdConstructorPartList.add(employeeIdConstructorPart); Constructor employeeIdConstructor = Constructor.builder() .parts(employeeIdConstructorPartList) .build(); List<ConstructorPart> ticketNumberConstructorPartList = new ArrayList<>(); ticketNumberConstructorPartList.add(ticketNumberConstructorPart); Constructor ticketNumberConstructor = Constructor.builder() .parts(ticketNumberConstructorPartList) .build(); List<ConstructorPart> projectNameConstructorPartList = new ArrayList<>(); projectNameConstructorPartList.add(projectNameConstructorPart); Constructor projectNameConstructor = Constructor.builder() .parts(projectNameConstructorPartList) .build(); List<ConstructorPart> ticketModTimeConstructorPartList = new ArrayList(); ticketModTimeConstructorPartList.add(ticketModTimeConstructorPart); Constructor ticketModTimeConstructor = Constructor.builder() .parts(ticketModTimeConstructorPartList) .build(); List<ConstructorPart> buildingConstructorPartList = new ArrayList(); buildingConstructorPartList.add(buildingConstructorPart); Constructor buildingConstructor = Constructor.builder() .parts(buildingConstructorPartList) .build(); // This constructor requires all of "MeetingStart", "Location.Floor", and "Location.Room" attributes. // If an item has all of these attributes, it will match this constructor. // If this is the first matching constructor in the constructor list (constructor list described more below), // the compound beacon will use this constructor, and the compound beacon will be written as `MS-X~F-Y~R-Z`. // In a constructor with multiple constructor parts, the order the constructor parts are added to // the constructor part list defines how the compound beacon is written. // We can rearrange the beacon parts by changing the order the constructors were added to the list. List<ConstructorPart> meetingStartFloorRoomConstructorPartList = new ArrayList(); meetingStartFloorRoomConstructorPartList.add(meetingStartConstructorPart); meetingStartFloorRoomConstructorPartList.add(floorConstructorPart); meetingStartFloorRoomConstructorPartList.add(roomConstructorPart); Constructor meetingStartFloorRoomConstructor = Constructor.builder() .parts(meetingStartFloorRoomConstructorPartList) .build(); List<ConstructorPart> timeCardStartEmployeeEmailConstructorPartList = new ArrayList(); timeCardStartEmployeeEmailConstructorPartList.add(timeCardStartConstructorPart); timeCardStartEmployeeEmailConstructorPartList.add(employeeEmailConstructorPart); Constructor timeCardStartEmployeeEmailConstructor = Constructor.builder() .parts(timeCardStartEmployeeEmailConstructorPartList) .build(); List<ConstructorPart> timeCardStartConstructorPartList = new ArrayList(); timeCardStartConstructorPartList.add(timeCardStartConstructorPart); Constructor timeCardStartConstructor = Constructor.builder() .parts(timeCardStartConstructorPartList) .build(); List<ConstructorPart> creatorEmailConstructorPartList = new ArrayList(); creatorEmailConstructorPartList.add(creatorEmailConstructorPart); Constructor creatorEmailConstructor = Constructor.builder() .parts(creatorEmailConstructorPartList) .build(); List<ConstructorPart> projectStatusConstructorPartList = new ArrayList(); projectStatusConstructorPartList.add(projectStatusConstructorPart); Constructor projectStatusConstructor = Constructor.builder() .parts(projectStatusConstructorPartList) .build(); List<ConstructorPart> employeeEmailConstructorPartList = new ArrayList(); employeeEmailConstructorPartList.add(employeeEmailConstructorPart); Constructor employeeEmailConstructor = Constructor.builder() .parts(employeeEmailConstructorPartList) .build(); List<ConstructorPart> organizerEmailConstructorPartList = new ArrayList(); organizerEmailConstructorPartList.add(organizerEmailConstructorPart); Constructor organizerEmailConstructor = Constructor.builder() .parts(organizerEmailConstructorPartList) .build(); List<ConstructorPart> projectStartConstructorPartList = new ArrayList(); projectStartConstructorPartList.add(projectStartConstructorPart); Constructor projectStartConstructor = Constructor.builder() .parts(projectStartConstructorPartList) .build(); List<ConstructorPart> managerEmailConstructorPartList = new ArrayList(); managerEmailConstructorPartList.add(managerEmailConstructorPart); Constructor managerEmailConstructor = Constructor.builder() .parts(managerEmailConstructorPartList) .build(); List<ConstructorPart> assigneeEmailConstructorPartList = new ArrayList(); assigneeEmailConstructorPartList.add(assigneeEmailConstructorPart); Constructor assigneeEmailConstructor = Constructor.builder() .parts(assigneeEmailConstructorPartList) .build(); List<ConstructorPart> cityConstructorPartList = new ArrayList(); cityConstructorPartList.add(cityConstructorPart); Constructor cityConstructor = Constructor.builder() .parts(cityConstructorPartList) .build(); List<ConstructorPart> severityConstructorPartList = new ArrayList(); severityConstructorPartList.add(severityConstructorPart); Constructor severityConstructor = Constructor.builder() .parts(severityConstructorPartList) .build(); List<ConstructorPart> buildingFloorDeskConstructorPartList = new ArrayList(); buildingFloorDeskConstructorPartList.add(buildingConstructorPart); buildingFloorDeskConstructorPartList.add(floorConstructorPart); buildingFloorDeskConstructorPartList.add(deskConstructorPart); Constructor buildingFloorDeskConstructor = Constructor.builder() .parts(buildingFloorDeskConstructorPartList) .build(); // 5. Add constructors to the compound beacon constructor list in desired construction order. // In a compound beacon with multiple constructors, the order the constructors are added to // the constructor list determines their priority. // The first constructor added to a constructor list will be the first constructor that is executed. // The client will evaluate constructors until one matches, and will use the first one that matches. // If no constructors match, an attribute value is not written for that beacon. // A general strategy is to add constructors with unique conditions at the beginning of the list, // and add constructors with general conditions at the end of the list. This would allow a given // item would trigger the constructor most specific to its attributes. List<Constructor> pk0ConstructorList = new ArrayList<>(); pk0ConstructorList.add(employeeIdConstructor); pk0ConstructorList.add(buildingConstructor); pk0ConstructorList.add(ticketNumberConstructor); pk0ConstructorList.add(projectNameConstructor); List<Constructor> sk0ConstructorList = new ArrayList<>(); sk0ConstructorList.add(ticketModTimeConstructor); sk0ConstructorList.add(meetingStartFloorRoomConstructor); sk0ConstructorList.add(timeCardStartEmployeeEmailConstructor); sk0ConstructorList.add(projectNameConstructor); sk0ConstructorList.add(employeeIdConstructor); List<Constructor> pk1ConstructorList = new ArrayList<>(); pk1ConstructorList.add(creatorEmailConstructor); pk1ConstructorList.add(employeeEmailConstructor); pk1ConstructorList.add(projectStatusConstructor); pk1ConstructorList.add(organizerEmailConstructor); List<Constructor> sk1ConstructorList = new ArrayList<>(); sk1ConstructorList.add(meetingStartFloorRoomConstructor); sk1ConstructorList.add(timeCardStartConstructor); sk1ConstructorList.add(ticketModTimeConstructor); sk1ConstructorList.add(projectStartConstructor); sk1ConstructorList.add(employeeIdConstructor); List<Constructor> pk2ConstructorList = new ArrayList<>(); pk2ConstructorList.add(managerEmailConstructor); pk2ConstructorList.add(assigneeEmailConstructor); List<Constructor> pk3ConstructorList = new ArrayList<>(); pk3ConstructorList.add(cityConstructor); pk3ConstructorList.add(severityConstructor); List<Constructor> sk3ConstructorList = new ArrayList<>(); sk3ConstructorList.add(buildingFloorDeskConstructor); sk3ConstructorList.add(ticketModTimeConstructor); // 9. Define compound beacons // Compound beacon construction is defined in more detail in CompoundBeaconSearchableEncryptionExample. // Note that the split character must be a character that is not used in any attribute value. CompoundBeacon pk0CompoundBeacon = CompoundBeacon.builder() .name("PK") .split("~") .encrypted(pk0EncryptedPartList) .constructors(pk0ConstructorList) .build(); CompoundBeacon sk0CompoundBeacon = CompoundBeacon.builder() .name("SK") .split("~") .encrypted(sk0EncryptedPartList) .signed(sk0SignedPartList) .constructors(sk0ConstructorList) .build(); CompoundBeacon pk1CompoundBeacon = CompoundBeacon.builder() .name("PK1") .split("~") .encrypted(pk1EncryptedPartList) .constructors(pk1ConstructorList) .build(); CompoundBeacon sk1CompoundBeacon = CompoundBeacon.builder() .name("SK1") .split("~") .encrypted(sk1EncryptedPartList) .signed(sk1SignedPartList) .constructors(sk1ConstructorList) .build(); CompoundBeacon pk2CompoundBeacon = CompoundBeacon.builder() .name("PK2") .split("~") .encrypted(pk2EncryptedPartList) .constructors(pk2ConstructorList) .build(); CompoundBeacon pk3CompoundBeacon = CompoundBeacon.builder() .name("PK3") .split("~") .encrypted(pk3EncryptedPartList) .constructors(pk3ConstructorList) .build(); CompoundBeacon sk3CompoundBeacon = CompoundBeacon.builder() .name("SK3") .split("~") .encrypted(sk3EncryptedPartList) .signed(sk3SignedPartList) .constructors(sk3ConstructorList) .build(); List<CompoundBeacon> compoundBeaconList = new ArrayList<>(); compoundBeaconList.add(pk0CompoundBeacon); compoundBeaconList.add(sk0CompoundBeacon); compoundBeaconList.add(pk1CompoundBeacon); compoundBeaconList.add(sk1CompoundBeacon); compoundBeaconList.add(pk2CompoundBeacon); compoundBeaconList.add(pk3CompoundBeacon); compoundBeaconList.add(sk3CompoundBeacon); // 10. Create BeaconVersion. List<BeaconVersion> beaconVersions = new ArrayList<>(); beaconVersions.add( BeaconVersion.builder() .standardBeacons(standardBeaconList) .compoundBeacons(compoundBeaconList) .version(1) // MUST be 1 .keyStore(keyStore) .keySource(BeaconKeySource.builder() .single(SingleKeyStore.builder() .keyId(branchKeyId) .cacheTTL(6000) .build()) .build()) .build() ); // 11. Create a Hierarchical Keyring final MaterialProviders matProv = MaterialProviders.builder() .MaterialProvidersConfig(MaterialProvidersConfig.builder().build()) .build(); CreateAwsKmsHierarchicalKeyringInput keyringInput = CreateAwsKmsHierarchicalKeyringInput.builder() .branchKeyId(branchKeyId) .keyStore(keyStore) .ttlSeconds(6000l) .build(); final IKeyring kmsKeyring = matProv.CreateAwsKmsHierarchicalKeyring(keyringInput); // 12. Define crypto actions final Map<String, CryptoAction> attributeActionsOnEncrypt = new HashMap<>(); // Our partition key must be configured as SIGN_ONLY attributeActionsOnEncrypt.put("partition_key", CryptoAction.SIGN_ONLY); // Attributes used in beacons must be configured as ENCRYPT_AND_SIGN attributeActionsOnEncrypt.put("EmployeeID", CryptoAction.ENCRYPT_AND_SIGN); attributeActionsOnEncrypt.put("TicketNumber", CryptoAction.ENCRYPT_AND_SIGN); attributeActionsOnEncrypt.put("ProjectName", CryptoAction.ENCRYPT_AND_SIGN); attributeActionsOnEncrypt.put("EmployeeName", CryptoAction.ENCRYPT_AND_SIGN); attributeActionsOnEncrypt.put("EmployeeEmail", CryptoAction.ENCRYPT_AND_SIGN); attributeActionsOnEncrypt.put("CreatorEmail", CryptoAction.ENCRYPT_AND_SIGN); attributeActionsOnEncrypt.put("ProjectStatus", CryptoAction.ENCRYPT_AND_SIGN); attributeActionsOnEncrypt.put("OrganizerEmail", CryptoAction.ENCRYPT_AND_SIGN); attributeActionsOnEncrypt.put("ManagerEmail", CryptoAction.ENCRYPT_AND_SIGN); attributeActionsOnEncrypt.put("AssigneeEmail", CryptoAction.ENCRYPT_AND_SIGN); attributeActionsOnEncrypt.put("City", CryptoAction.ENCRYPT_AND_SIGN); attributeActionsOnEncrypt.put("Severity", CryptoAction.ENCRYPT_AND_SIGN); attributeActionsOnEncrypt.put("Location", CryptoAction.ENCRYPT_AND_SIGN); // These are not beaconized attributes, but are sensitive data that must be encrypted attributeActionsOnEncrypt.put("Attendees", CryptoAction.ENCRYPT_AND_SIGN); attributeActionsOnEncrypt.put("Subject", CryptoAction.ENCRYPT_AND_SIGN); // signed parts and unencrypted attributes can be configured as SIGN_ONLY or DO_NOTHING // For this example, we will set these to SIGN_ONLY to ensure authenticity attributeActionsOnEncrypt.put("TicketModTime", CryptoAction.SIGN_ONLY); attributeActionsOnEncrypt.put("MeetingStart", CryptoAction.SIGN_ONLY); attributeActionsOnEncrypt.put("TimeCardStart", CryptoAction.SIGN_ONLY); attributeActionsOnEncrypt.put("EmployeeTitle", CryptoAction.SIGN_ONLY); attributeActionsOnEncrypt.put("Description", CryptoAction.SIGN_ONLY); attributeActionsOnEncrypt.put("ProjectTarget", CryptoAction.SIGN_ONLY); attributeActionsOnEncrypt.put("Hours", CryptoAction.SIGN_ONLY); attributeActionsOnEncrypt.put("Role", CryptoAction.SIGN_ONLY); attributeActionsOnEncrypt.put("Message", CryptoAction.SIGN_ONLY); attributeActionsOnEncrypt.put("ProjectStart", CryptoAction.SIGN_ONLY); attributeActionsOnEncrypt.put("Duration", CryptoAction.SIGN_ONLY); // 13. Set up table config final Map<String, DynamoDbTableEncryptionConfig> tableConfigs = new HashMap<>(); final DynamoDbTableEncryptionConfig config = DynamoDbTableEncryptionConfig.builder() .logicalTableName(ddbTableName) .partitionKeyName("partition_key") .attributeActionsOnEncrypt(attributeActionsOnEncrypt) .keyring(kmsKeyring) .search(SearchConfig.builder() .writeVersion(1) // MUST be 1 .versions(beaconVersions) .build()) .build(); tableConfigs.put(ddbTableName, config); // 14. Create the DynamoDb Encryption Interceptor DynamoDbEncryptionInterceptor encryptionInterceptor = DynamoDbEncryptionInterceptor.builder() .config(DynamoDbTablesEncryptionConfig.builder() .tableEncryptionConfigs(tableConfigs) .build()) .build(); // 15. Create a new AWS SDK DynamoDb client using the DynamoDb Encryption Interceptor above final DynamoDbClient ddb = DynamoDbClient.builder() .overrideConfiguration( ClientOverrideConfiguration.builder() .addExecutionInterceptor(encryptionInterceptor) .build()) .build(); return ddb; } }
5,269
0
Create_ds/aws-database-encryption-sdk-dynamodb-java/Examples/runtimes/java/DynamoDbEncryption/src/main/java/software/amazon/cryptography/examples/searchableencryption
Create_ds/aws-database-encryption-sdk-dynamodb-java/Examples/runtimes/java/DynamoDbEncryption/src/main/java/software/amazon/cryptography/examples/searchableencryption/complexexample/QueryRequests.java
package software.amazon.cryptography.examples.searchableencryption.complexexample; import java.util.HashMap; import java.util.Map; import software.amazon.awssdk.services.dynamodb.DynamoDbClient; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; import software.amazon.awssdk.services.dynamodb.model.QueryRequest; import software.amazon.awssdk.services.dynamodb.model.QueryResponse; /* * This file is used in an example to demonstrate complex queries * you can perform using beacons. * The example data used is for demonstrative purposes only, * and might not meet the distribution and correlation uniqueness * recommendations for beacons. * See our documentation for whether beacons are * right for your particular data set: * https://docs.aws.amazon.com/database-encryption-sdk/latest/devguide/searchable-encryption.html#are-beacons-right-for-me * * This class implements query access patterns from our workshop. * The queries in this file are more complicated than in other searchable encryption examples, * and should demonstrate how one can structure queries on beacons in a broader variety of applications. */ public class QueryRequests { public static void runQueries(String ddbTableName, DynamoDbClient ddb) { runQuery1(ddbTableName, ddb); runQuery2(ddbTableName, ddb); runQuery3(ddbTableName, ddb); runQuery4(ddbTableName, ddb); runQuery5(ddbTableName, ddb); runQuery6(ddbTableName, ddb); runQuery7(ddbTableName, ddb); runQuery8(ddbTableName, ddb); runQuery9(ddbTableName, ddb); runQuery10(ddbTableName, ddb); runQuery11(ddbTableName, ddb); runQuery12(ddbTableName, ddb); runQuery13(ddbTableName, ddb); runQuery14(ddbTableName, ddb); runQuery15(ddbTableName, ddb); runQuery16(ddbTableName, ddb); runQuery17(ddbTableName, ddb); runQuery18(ddbTableName, ddb); runQuery19(ddbTableName, ddb); runQuery20(ddbTableName, ddb); runQuery21(ddbTableName, ddb); runQuery22(ddbTableName, ddb); runQuery23(ddbTableName, ddb); } public static void runQuery1(String ddbTableName, DynamoDbClient ddb) { // Query 1: Get meetings by date and email // Key condition: PK1=email SK1 between(date1, date2) // Filter condition: duration > 0 final Map<String, String> query1AttributeNames = new HashMap<>(); query1AttributeNames.put("#pk1", "PK1"); query1AttributeNames.put("#sk1", "SK1"); query1AttributeNames.put("#duration", "Duration"); final Map<String, AttributeValue> query1AttributeValues = new HashMap<>(); query1AttributeValues.put(":e", AttributeValue.builder().s("EE-able@gmail.com").build()); query1AttributeValues.put(":date1", AttributeValue.builder().s("MS-2022-07-02").build()); query1AttributeValues.put(":date2", AttributeValue.builder().s("MS-2022-07-08").build()); query1AttributeValues.put(":zero", AttributeValue.builder().s("0").build()); final QueryRequest query1Request = QueryRequest.builder() .tableName(ddbTableName) .indexName("GSI-1") .keyConditionExpression("#pk1 = :e AND #sk1 BETWEEN :date1 AND :date2") .filterExpression("#duration > :zero") .expressionAttributeNames(query1AttributeNames) .expressionAttributeValues(query1AttributeValues) .build(); final QueryResponse query1Response = ddb.query(query1Request); // Validate query was returned successfully assert 200 == query1Response.sdkHttpResponse().statusCode(); // Assert 1 item was returned: `meeting1` assert query1Response.items().size() == 1; // Known value test: Assert some properties on one of the items boolean foundKnownValueItemQuery1 = false; for (Map<String, AttributeValue> item : query1Response.items()) { if (item.get("partition_key").s().equals("meeting1")) { foundKnownValueItemQuery1 = true; assert item.get("Subject").s().equals("Scan Beacons"); assert item.get("Location").m().get("Floor").s().equals("12"); assert item.get("Attendees").l() .contains(AttributeValue.builder().s("zorro@gmail.com").build()); } } assert foundKnownValueItemQuery1; } public static void runQuery2(String ddbTableName, DynamoDbClient ddb) { // Query 2: Get meetings by date and employeeID // Key condition: PK=employeeID SK between(date1, date2) // Filter condition: duration > 0 Map<String, String> query2AttributeNames = new HashMap<>(); query2AttributeNames.put("#pk", "PK"); query2AttributeNames.put("#sk", "SK"); query2AttributeNames.put("#duration", "Duration"); Map<String, AttributeValue> query2AttributeValues = new HashMap<>(); query2AttributeValues.put(":employee", AttributeValue.builder().s("E-emp_001").build()); query2AttributeValues.put(":date1", AttributeValue.builder().s("MS-2022-07-02").build()); query2AttributeValues.put(":date2", AttributeValue.builder().s("MS-2022-07-08").build()); query2AttributeValues.put(":zero", AttributeValue.builder().s("0").build()); QueryRequest query2Request = QueryRequest.builder() .tableName(ddbTableName) .indexName("GSI-0") .keyConditionExpression("#pk = :employee AND #sk BETWEEN :date1 AND :date2") .filterExpression("#duration > :zero") .expressionAttributeNames(query2AttributeNames) .expressionAttributeValues(query2AttributeValues) .build(); QueryResponse query2Response = ddb.query(query2Request); // Validate query was returned successfully assert 200 == query2Response.sdkHttpResponse().statusCode(); // Assert 1 item was returned: `meeting1` assert query2Response.items().size() == 1; // Known value test: Assert some properties on one of the items boolean foundKnownValueItemQuery2 = false; for (Map<String, AttributeValue> item : query2Response.items()) { if (item.get("partition_key").s().equals("meeting1")) { foundKnownValueItemQuery2 = true; assert item.get("Subject").s().equals("Scan Beacons"); assert item.get("Location").m().get("Floor").s().equals("12"); assert item.get("Attendees").l() .contains(AttributeValue.builder().s("zorro@gmail.com").build()); } } assert foundKnownValueItemQuery2; } public static void runQuery3(String ddbTableName, DynamoDbClient ddb) { // Query 3: Get meetings by date and building/floor/room // Key condition: PK=employeeID SK between(date1, date2) // Filter condition: SK contains building.floor.room (see NOTE) // NOTE: This query is modified from Demo.md. // Demo.md calls for a filter condition "SK contains building.floor.room" // However, one cannot use primary keys (partition nor sort) in a filter expression. // Instead, this query filters on the individual beacon attributes: building, floor, and room. Map<String,String> query3AttributeNames = new HashMap<>(); query3AttributeNames.put("#pk", "PK"); query3AttributeNames.put("#sk", "SK"); query3AttributeNames.put("#building", "Building"); query3AttributeNames.put("#floor", "Floor"); query3AttributeNames.put("#room", "Room"); Map<String,AttributeValue> query3AttributeValues = new HashMap<>(); query3AttributeValues.put(":buildingbeacon", AttributeValue.builder().s("B-SEA33").build()); query3AttributeValues.put(":building", AttributeValue.builder().s("SEA33").build()); query3AttributeValues.put(":floor", AttributeValue.builder().s("12").build()); query3AttributeValues.put(":room", AttributeValue.builder().s("403").build()); query3AttributeValues.put(":date1", AttributeValue.builder().s("MS-2022-07-02").build()); query3AttributeValues.put(":date2", AttributeValue.builder().s("MS-2022-07-08").build()); QueryRequest query3Request = QueryRequest.builder() .tableName(ddbTableName) .indexName("GSI-0") .keyConditionExpression("#pk = :buildingbeacon AND #sk BETWEEN :date1 AND :date2") .filterExpression("#building = :building AND #floor = :floor AND #room = :room") .expressionAttributeNames(query3AttributeNames) .expressionAttributeValues(query3AttributeValues) .build(); QueryResponse query3Response = ddb.query(query3Request); // Validate query was returned successfully assert 200 == query3Response.sdkHttpResponse().statusCode(); // Assert 1 item was returned: `reservation1` assert query3Response.items().size() == 1; // Known value test: Assert some properties on one of the items boolean foundKnownValueItemQuery3 = false; for (Map<String, AttributeValue> item : query3Response.items()) { if (item.get("partition_key").s().equals("reservation1")) { foundKnownValueItemQuery3 = true; assert item.get("Subject").s().equals("Scan beacons"); assert item.get("Location").m().get("Building").s().equals("SEA33"); assert item.get("Attendees").l().contains(AttributeValue.builder().s("barney@gmail.com").build()); } } assert foundKnownValueItemQuery3; } public static void runQuery4(String ddbTableName, DynamoDbClient ddb) { // Query 4: Get employee data by email // Key condition: PK1=email SK1=employee ID Map<String, String> query4AttributeNames = new HashMap<>(); query4AttributeNames.put("#pk1", "PK1"); query4AttributeNames.put("#sk1", "SK1"); Map<String, AttributeValue> query4AttributeValues = new HashMap<>(); query4AttributeValues.put(":email", AttributeValue.builder().s("EE-able@gmail.com").build()); query4AttributeValues.put(":employee", AttributeValue.builder().s("E-emp_001").build()); QueryRequest query4Request = QueryRequest.builder() .tableName(ddbTableName) .indexName("GSI-1") .keyConditionExpression("#pk1 = :email AND #sk1 = :employee") .expressionAttributeNames(query4AttributeNames) .expressionAttributeValues(query4AttributeValues) .build(); QueryResponse query4Response = ddb.query(query4Request); // Validate query was returned successfully assert 200 == query4Response.sdkHttpResponse().statusCode(); // Assert 1 item was returned: `employee1` assert query4Response.items().size() == 1; // Known value test: Assert some properties on one of the items boolean foundKnownValueItemQuery4 = false; for (Map<String, AttributeValue> item : query4Response.items()) { if (item.get("partition_key").s().equals("employee1")) { foundKnownValueItemQuery4 = true; assert item.get("EmployeeID").s().equals("emp_001"); assert item.get("Location").m().get("Desk").s().equals("3"); } } assert foundKnownValueItemQuery4; } public static void runQuery5(String ddbTableName, DynamoDbClient ddb) { // Query 5: Get meetings by email // Key condition: PK1=email SK1 > 30 days ago Map<String, String> query5AttributeNames = new HashMap<>(); query5AttributeNames.put("#pk1", "PK1"); query5AttributeNames.put("#sk1", "SK1"); Map<String, AttributeValue> query5AttributeValues = new HashMap<>(); query5AttributeValues.put(":email", AttributeValue.builder().s("EE-able@gmail.com").build()); query5AttributeValues.put(":thirtydaysago", AttributeValue.builder().s("MS-2023-03-20").build()); query5AttributeValues.put(":prefix", AttributeValue.builder().s("MS-").build()); QueryRequest query5Request = QueryRequest.builder() .tableName(ddbTableName) .indexName("GSI-1") .keyConditionExpression("#pk1 = :email AND #sk1 BETWEEN :prefix AND :thirtydaysago") .expressionAttributeNames(query5AttributeNames) .expressionAttributeValues(query5AttributeValues) .build(); QueryResponse query5Response = ddb.query(query5Request); // Validate query was returned successfully assert 200 == query5Response.sdkHttpResponse().statusCode(); // Assert 1 item was returned: `meeting1` assert query5Response.items().size() == 1; // Known value test: Assert some properties on one of the items boolean foundKnownValueItemQuery5 = false; for (Map<String, AttributeValue> item : query5Response.items()) { if (item.get("partition_key").s().equals("meeting1")) { foundKnownValueItemQuery5 = true; assert item.get("Subject").s().equals("Scan Beacons"); assert item.get("Location").m().get("Floor").s().equals("12"); assert item.get("Attendees").l() .contains(AttributeValue.builder().s("zorro@gmail.com").build()); } } assert foundKnownValueItemQuery5; } public static void runQuery6(String ddbTableName, DynamoDbClient ddb) { // Query 6: Get tickets by email // Key condition: PK1=email SK1 > 30 days ago Map<String, String> query6AttributeNames = new HashMap<>(); query6AttributeNames.put("#pk1", "PK1"); query6AttributeNames.put("#sk1", "SK1"); Map<String, AttributeValue> query6AttributeValues = new HashMap<>(); query6AttributeValues.put(":creatoremail", AttributeValue.builder().s("CE-zorro@gmail.com").build()); query6AttributeValues.put(":thirtydaysago", AttributeValue.builder().s("MS-2023-03-20").build()); QueryRequest query6Request = QueryRequest.builder() .tableName(ddbTableName) .indexName("GSI-1") .keyConditionExpression("#pk1 = :creatoremail AND #sk1 < :thirtydaysago") .expressionAttributeNames(query6AttributeNames) .expressionAttributeValues(query6AttributeValues) .build(); QueryResponse query6Response = ddb.query(query6Request); // Validate query was returned successfully assert 200 == query6Response.sdkHttpResponse().statusCode(); // Assert 2 items returned: // Expected to be `ticket1` and `ticket3` assert query6Response.items().size() == 2; // Known value test: Assert some properties on one of the items boolean foundKnownValueItemQuery6 = false; for (Map<String, AttributeValue> item : query6Response.items()) { if (item.get("partition_key").s().equals("ticket1")) { foundKnownValueItemQuery6 = true; assert item.get("TicketNumber").s().equals("ticket_001"); } } assert foundKnownValueItemQuery6; } public static void runQuery7(String ddbTableName, DynamoDbClient ddb) { // Query 7: Get reservations by email // Key condition: PK1=organizeremail SK1 > 30 days ago Map<String, String> query7AttributeNames = new HashMap<>(); query7AttributeNames.put("#pk1", "PK1"); query7AttributeNames.put("#sk1", "SK1"); Map<String, AttributeValue> query7AttributeValues = new HashMap<>(); query7AttributeValues.put(":organizeremail", AttributeValue.builder().s("OE-able@gmail.com").build()); query7AttributeValues.put(":thirtydaysago", AttributeValue.builder().s("MS-2023-03-20").build()); QueryRequest query7Request = QueryRequest.builder() .tableName(ddbTableName) .indexName("GSI-1") .keyConditionExpression("#pk1 = :organizeremail AND #sk1 < :thirtydaysago") .expressionAttributeNames(query7AttributeNames) .expressionAttributeValues(query7AttributeValues) .build(); QueryResponse query7Response = ddb.query(query7Request); // Validate query was returned successfully assert 200 == query7Response.sdkHttpResponse().statusCode(); // Assert 1 item was returned: `reservation1` assert query7Response.items().size() == 1; // Known value test: Assert some properties on one of the items boolean foundKnownValueItemQuery7 = false; for (Map<String, AttributeValue> item : query7Response.items()) { if (item.get("partition_key").s().equals("reservation1")) { foundKnownValueItemQuery7 = true; assert item.get("Subject").s().equals("Scan beacons"); assert item.get("Location").m().get("Floor").s().equals("12"); assert item.get("Attendees").l() .contains(AttributeValue.builder().s("barney@gmail.com").build()); } } assert foundKnownValueItemQuery7; } public static void runQuery8(String ddbTableName, DynamoDbClient ddb) { // Query 8: Get time cards by email // Key condition: PK1=employeeemail SK1 > 30 days ago Map<String,String> query8AttributeNames = new HashMap<>(); query8AttributeNames.put("#pk1", "PK1"); query8AttributeNames.put("#sk1", "SK1"); Map<String,AttributeValue> query8AttributeValues = new HashMap<>(); query8AttributeValues.put(":email", AttributeValue.builder().s("EE-able@gmail.com").build()); query8AttributeValues.put(":prefix", AttributeValue.builder().s("TC-").build()); query8AttributeValues.put(":thirtydaysago", AttributeValue.builder().s("TC-2023-03-20").build()); QueryRequest query8Request = QueryRequest.builder() .tableName(ddbTableName) .indexName("GSI-1") .keyConditionExpression("#pk1 = :email AND #sk1 BETWEEN :prefix AND :thirtydaysago") .expressionAttributeNames(query8AttributeNames) .expressionAttributeValues(query8AttributeValues) .build(); QueryResponse query8Response = ddb.query(query8Request); // Validate query was returned successfully assert 200 == query8Response.sdkHttpResponse().statusCode(); // Assert 1 item was returned: `timecard1` assert query8Response.items().size() == 1; // Known value test: Assert some properties on one of the items boolean foundKnownValueItemQuery8 = false; for (Map<String, AttributeValue> item : query8Response.items()) { if (item.get("partition_key").s().equals("timecard1")) { foundKnownValueItemQuery8 = true; assert item.get("ProjectName").s().equals("project_002"); } } assert foundKnownValueItemQuery8; } public static void runQuery9(String ddbTableName, DynamoDbClient ddb) { // Query 9: Get employee info by employee ID // Key condition: PK1=employeeID SK starts with "E-" Map<String,String> query9AttributeNames = new HashMap<>(); query9AttributeNames.put("#pk", "PK"); query9AttributeNames.put("#sk", "SK"); Map<String,AttributeValue> query9AttributeValues = new HashMap<>(); query9AttributeValues.put(":employee", AttributeValue.builder().s("E-emp_001").build()); query9AttributeValues.put(":prefix", AttributeValue.builder().s("E-").build()); QueryRequest query9Request = QueryRequest.builder() .tableName(ddbTableName) .indexName("GSI-0") .keyConditionExpression("#pk = :employee AND begins_with(#sk, :prefix)") .expressionAttributeNames(query9AttributeNames) .expressionAttributeValues(query9AttributeValues) .build(); QueryResponse query9Response = ddb.query(query9Request); // Validate query was returned successfully assert 200 == query9Response.sdkHttpResponse().statusCode(); // Assert 1 item was returned: `employee1` assert query9Response.items().size() == 1; // Known value test: Assert some properties on one of the items boolean foundKnownValueItemQuery9 = false; for (Map<String, AttributeValue> item : query9Response.items()) { if (item.get("partition_key").s().equals("employee1")) { foundKnownValueItemQuery9 = true; assert item.get("EmployeeID").s().equals("emp_001"); } } assert foundKnownValueItemQuery9; } public static void runQuery10(String ddbTableName, DynamoDbClient ddb) { // Query 10: Get employee info by email // Key condition: PK1=email // Filter condition: SK starts with "E-" Map<String,String> query10AttributeNames = new HashMap<>(); query10AttributeNames.put("#pk1", "PK1"); query10AttributeNames.put("#sk1", "SK1"); Map<String,AttributeValue> query10AttributeValues = new HashMap<>(); query10AttributeValues.put(":email", AttributeValue.builder().s("EE-able@gmail.com").build()); query10AttributeValues.put(":prefix", AttributeValue.builder().s("E-").build()); QueryRequest query10Request = QueryRequest.builder() .tableName(ddbTableName) .indexName("GSI-1") .keyConditionExpression("#pk1 = :email AND begins_with(#sk1, :prefix)") .expressionAttributeNames(query10AttributeNames) .expressionAttributeValues(query10AttributeValues) .build(); QueryResponse query10Response = ddb.query(query10Request); // Validate query was returned successfully assert 200 == query10Response.sdkHttpResponse().statusCode(); // Assert 1 item was returned: `employee1` assert query10Response.items().size() == 1; // Known value test: Assert some properties on one of the items boolean foundKnownValueItemQuery10 = false; for (Map<String, AttributeValue> item : query10Response.items()) { if (item.get("partition_key").s().equals("employee1")) { foundKnownValueItemQuery10 = true; assert item.get("EmployeeID").s().equals("emp_001"); } } assert foundKnownValueItemQuery10; } public static void runQuery11(String ddbTableName, DynamoDbClient ddb) { // Query 11: Get ticket history by ticket number // Key condition: PK=TicketNumber Map<String,String> query11AttributeNames = new HashMap<>(); query11AttributeNames.put("#pk", "PK"); Map<String,AttributeValue> query11AttributeValues = new HashMap<>(); query11AttributeValues.put(":ticket", AttributeValue.builder().s("T-ticket_001").build()); QueryRequest query11Request = QueryRequest.builder() .tableName(ddbTableName) .indexName("GSI-0") .keyConditionExpression("#pk = :ticket") .expressionAttributeNames(query11AttributeNames) .expressionAttributeValues(query11AttributeValues) .build(); QueryResponse query11Response = ddb.query(query11Request); // Validate query was returned successfully assert 200 == query11Response.sdkHttpResponse().statusCode(); // Assert 2 items returned: // Expected to be `ticket1` and `ticket2` assert query11Response.items().size() == 2; // Known value test: Assert some properties on one of the items boolean foundKnownValueItemQuery11 = false; for (Map<String, AttributeValue> item : query11Response.items()) { if (item.get("partition_key").s().equals("ticket1")) { foundKnownValueItemQuery11 = true; assert item.get("TicketNumber").s().equals("ticket_001"); } } assert foundKnownValueItemQuery11; } public static void runQuery12(String ddbTableName, DynamoDbClient ddb) { // Query 12: Get Ticket History by employee email // Key condition: PK1=CreatorEmail // Filter condition: PK=TicketNumber Map<String,String> query12AttributeNames = new HashMap<>(); query12AttributeNames.put("#pk1", "PK1"); query12AttributeNames.put("#pk", "PK"); Map<String,AttributeValue> query12AttributeValues = new HashMap<>(); query12AttributeValues.put(":email", AttributeValue.builder().s("CE-zorro@gmail.com").build()); query12AttributeValues.put(":ticket", AttributeValue.builder().s("T-ticket_001").build()); QueryRequest query12Request = QueryRequest.builder() .tableName(ddbTableName) .indexName("GSI-1") .keyConditionExpression("#pk1 = :email") .filterExpression("#pk = :ticket") .expressionAttributeNames(query12AttributeNames) .expressionAttributeValues(query12AttributeValues) .build(); QueryResponse query12Response = ddb.query(query12Request); // Validate query was returned successfully assert 200 == query12Response.sdkHttpResponse().statusCode(); // Assert 1 item was returned: `ticket1` assert query12Response.items().size() == 1; // Known value test: Assert some properties on one of the items boolean foundKnownValueItemQuery12 = false; for (Map<String, AttributeValue> item : query12Response.items()) { if (item.get("partition_key").s().equals("ticket1")) { foundKnownValueItemQuery12 = true; assert item.get("TicketNumber").s().equals("ticket_001"); } } assert foundKnownValueItemQuery12; } public static void runQuery13(String ddbTableName, DynamoDbClient ddb) { // Query 13: Get ticket history by assignee email // Key condition: PK=AssigneeEmail // Filter condition: PK=ticketNumber Map<String,String> query13AttributeNames = new HashMap<>(); query13AttributeNames.put("#pk2", "PK2"); query13AttributeNames.put("#pk", "PK"); Map<String,AttributeValue> query13AttributeValues = new HashMap<>(); query13AttributeValues.put(":assigneeemail", AttributeValue.builder().s("AE-able@gmail.com").build()); query13AttributeValues.put(":ticket", AttributeValue.builder().s("T-ticket_001").build()); QueryRequest query13Request = QueryRequest.builder() .tableName(ddbTableName) .indexName("GSI-2") .keyConditionExpression("#pk2 = :assigneeemail") .filterExpression("#pk = :ticket") .expressionAttributeNames(query13AttributeNames) .expressionAttributeValues(query13AttributeValues) .build(); QueryResponse query13Response = ddb.query(query13Request); // Validate query was returned successfully assert 200 == query13Response.sdkHttpResponse().statusCode(); // Assert 1 item was returned: `ticket1` assert query13Response.items().size() == 1; // Known value test: Assert some properties on one of the items boolean foundKnownValueItemQuery13 = false; for (Map<String, AttributeValue> item : query13Response.items()) { if (item.get("partition_key").s().equals("ticket1")) { foundKnownValueItemQuery13 = true; assert item.get("Subject").s().equals("Bad bug"); } } assert foundKnownValueItemQuery13; } public static void runQuery14(String ddbTableName, DynamoDbClient ddb) { // Query 14: Get employees by city.building.floor.desk // Key condition: PK3=city SK3 begins_with(building.floor.desk) Map<String,String> query14AttributeNames = new HashMap<>(); query14AttributeNames.put("#pk3", "PK3"); query14AttributeNames.put("#sk3", "SK3"); Map<String,AttributeValue> query14AttributeValues = new HashMap<>(); query14AttributeValues.put(":city", AttributeValue.builder().s("C-Seattle").build()); query14AttributeValues.put(":location", AttributeValue.builder().s("B-44~F-12~D-3").build()); QueryRequest query14Request = QueryRequest.builder() .tableName(ddbTableName) .indexName("GSI-3") .keyConditionExpression("#pk3 = :city AND begins_with(#sk3, :location)") .expressionAttributeNames(query14AttributeNames) .expressionAttributeValues(query14AttributeValues) .build(); QueryResponse query14Response = ddb.query(query14Request); // Validate query was returned successfully assert 200 == query14Response.sdkHttpResponse().statusCode(); // Assert 1 item was returned: `employee1` assert query14Response.items().size() == 1; // Known value test: Assert some properties on one of the items boolean foundKnownValueItemQuery14 = false; for (Map<String, AttributeValue> item : query14Response.items()) { if (item.get("partition_key").s().equals("employee1")) { foundKnownValueItemQuery14 = true; assert item.get("EmployeeID").s().equals("emp_001"); assert item.get("Location").m().get("Desk").s().equals("3"); } } assert foundKnownValueItemQuery14; } public static void runQuery15(String ddbTableName, DynamoDbClient ddb) { // Query 15: Get employees by manager email // Key condition: PK2 = ManagerEmail Map<String,String> query15AttributeNames = new HashMap<>(); query15AttributeNames.put("#pk2", "PK2"); Map<String,AttributeValue> query15AttributeValues = new HashMap<>(); query15AttributeValues.put(":manageremail", AttributeValue.builder().s("ME-zorro@gmail.com").build()); QueryRequest query15Request = QueryRequest.builder() .tableName(ddbTableName) .indexName("GSI-2") .keyConditionExpression("#pk2 = :manageremail") .expressionAttributeNames(query15AttributeNames) .expressionAttributeValues(query15AttributeValues) .build(); QueryResponse query15Response = ddb.query(query15Request); // Validate query was returned successfully assert 200 == query15Response.sdkHttpResponse().statusCode(); // Assert 4 items returned: // Expected to be `employee1`, `employee2`, `employee3`, and `employee4` assert query15Response.items().size() == 4; // Known value test: Assert some properties on one of the items boolean foundKnownValueItemQuery15 = false; for (Map<String, AttributeValue> item : query15Response.items()) { if (item.get("partition_key").s().equals("employee1")) { foundKnownValueItemQuery15 = true; assert item.get("EmployeeID").s().equals("emp_001"); assert item.get("Location").m().get("Desk").s().equals("3"); } } assert foundKnownValueItemQuery15; } public static void runQuery16(String ddbTableName, DynamoDbClient ddb) { // Query 16: Get assigned tickets by assignee email // Key condition: PK2 = AssigneeEmail Map<String,String> query16AttributeNames = new HashMap<>(); query16AttributeNames.put("#pk2", "PK2"); Map<String,AttributeValue> query16AttributeValues = new HashMap<>(); query16AttributeValues.put(":assigneeemail", AttributeValue.builder().s("AE-able@gmail.com").build()); QueryRequest query16Request = QueryRequest.builder() .tableName(ddbTableName) .indexName("GSI-2") .keyConditionExpression("#pk2 = :assigneeemail") .expressionAttributeNames(query16AttributeNames) .expressionAttributeValues(query16AttributeValues) .build(); QueryResponse query16Response = ddb.query(query16Request); // Validate query was returned successfully assert 200 == query16Response.sdkHttpResponse().statusCode(); // Assert 2 items returned: // Expected to be `ticket1` and `ticket4` assert query16Response.items().size() == 2; // Known value test: Assert some properties on one of the items boolean foundKnownValueItemQuery16 = false; for (Map<String, AttributeValue> item : query16Response.items()) { if (item.get("partition_key").s().equals("ticket1")) { foundKnownValueItemQuery16 = true; assert item.get("TicketNumber").s().equals("ticket_001"); } } assert foundKnownValueItemQuery16; } public static void runQuery17(String ddbTableName, DynamoDbClient ddb) { // Query 17: Get tickets updated within the last 24 hours // Key condition: PK3 = Severity, SK3 > 24 hours ago // (For the sake of this example, we will assume // the date is 2022-10-08T09:30:00, such that "24 hours ago" // is 2022-10-07T09:30:00, and that our sample ticket record // with TicketModTime=2022-10-07T14:32:25 will be returned.) Map<String,String> query17AttributeNames = new HashMap<>(); query17AttributeNames.put("#pk3", "PK3"); query17AttributeNames.put("#sk3", "SK3"); Map<String,AttributeValue> query17AttributeValues = new HashMap<>(); query17AttributeValues.put(":severity", AttributeValue.builder().s("S-3").build()); query17AttributeValues.put(":yesterday", AttributeValue.builder().s("M-2022-10-07T09:30:00").build()); QueryRequest query17Request = QueryRequest.builder() .tableName(ddbTableName) .indexName("GSI-3") .keyConditionExpression("#pk3 = :severity AND #sk3 > :yesterday") .expressionAttributeNames(query17AttributeNames) .expressionAttributeValues(query17AttributeValues) .build(); QueryResponse query17Response = ddb.query(query17Request); // Validate query was returned successfully assert 200 == query17Response.sdkHttpResponse().statusCode(); // Assert 3 items returned: // Expected to be `ticket1`, `ticket2`, and `ticket4` assert query17Response.items().size() == 3; // Known value test: Assert some properties on one of the items boolean foundKnownValueItemQuery17 = false; for (Map<String, AttributeValue> item : query17Response.items()) { if (item.get("partition_key").s().equals("ticket1")) { foundKnownValueItemQuery17 = true; assert item.get("TicketNumber").s().equals("ticket_001"); } } assert foundKnownValueItemQuery17; } public static void runQuery18(String ddbTableName, DynamoDbClient ddb) { // Query 18: Get projects by status, start and target date // Key condition: PK1 = Status, SK1 > StartDate // Filter condition: TargetDelivery < TargetDate Map<String,String> query18AttributeNames = new HashMap<>(); query18AttributeNames.put("#pk1", "PK1"); query18AttributeNames.put("#sk1", "SK1"); query18AttributeNames.put("#target", "ProjectTarget"); Map<String,AttributeValue> query18AttributeValues = new HashMap<>(); query18AttributeValues.put(":status", AttributeValue.builder().s("PSts-Pending").build()); query18AttributeValues.put(":startdate", AttributeValue.builder().s("PS-2022-01-01").build()); query18AttributeValues.put(":target", AttributeValue.builder().s("2025-01-01").build()); QueryRequest query18Request = QueryRequest.builder() .tableName(ddbTableName) .indexName("GSI-1") .keyConditionExpression("#pk1 = :status AND #sk1 > :startdate") .filterExpression("#target < :target") .expressionAttributeNames(query18AttributeNames) .expressionAttributeValues(query18AttributeValues) .build(); QueryResponse query18Response = ddb.query(query18Request); // Validate query was returned successfully assert 200 == query18Response.sdkHttpResponse().statusCode(); // Assert 1 item was returned: `project1` assert query18Response.items().size() == 1; // Known value test: Assert some properties on one of the items boolean foundKnownValueItemQuery18 = false; for (Map<String, AttributeValue> item : query18Response.items()) { if (item.get("partition_key").s().equals("project1")) { foundKnownValueItemQuery18 = true; assert item.get("ProjectName").s().equals("project_001"); } } assert foundKnownValueItemQuery18; } public static void runQuery19(String ddbTableName, DynamoDbClient ddb) { // Query 19: Get projects by name // Key condition: PK = ProjectName, SK = ProjectName Map<String,String> query19AttributeNames = new HashMap<>(); query19AttributeNames.put("#pk", "PK"); query19AttributeNames.put("#sk", "SK"); Map<String,AttributeValue> query19AttributeValues = new HashMap<>(); query19AttributeValues.put(":projectname", AttributeValue.builder().s("P-project_001").build()); QueryRequest query19Request = QueryRequest.builder() .tableName(ddbTableName) .indexName("GSI-0") .keyConditionExpression("#pk = :projectname AND #sk = :projectname") .expressionAttributeNames(query19AttributeNames) .expressionAttributeValues(query19AttributeValues) .build(); QueryResponse query19Response = ddb.query(query19Request); // Validate query was returned successfully assert 200 == query19Response.sdkHttpResponse().statusCode(); // Assert 1 item was returned: `project1` assert query19Response.items().size() == 1; // Known value test: Assert some properties on one of the items boolean foundKnownValueItemQuery19 = false; for (Map<String, AttributeValue> item : query19Response.items()) { if (item.get("partition_key").s().equals("project1")) { foundKnownValueItemQuery19 = true; assert item.get("ProjectName").s().equals("project_001"); } } assert foundKnownValueItemQuery19; } public static void runQuery20(String ddbTableName, DynamoDbClient ddb) { // Query 20: Get Project History by date range (against timecard record) // Key condition: PK = ProjectName, SK between(date1, date2) Map<String,String> query20AttributeNames = new HashMap<>(); query20AttributeNames.put("#pk", "PK"); query20AttributeNames.put("#sk", "SK"); Map<String,AttributeValue> query20AttributeValues = new HashMap<>(); query20AttributeValues.put(":projectname", AttributeValue.builder().s("P-project_002").build()); query20AttributeValues.put(":date1", AttributeValue.builder().s("TC-2022-01-01").build()); query20AttributeValues.put(":date2", AttributeValue.builder().s("TC-2023-01-01").build()); QueryRequest query20Request = QueryRequest.builder() .tableName(ddbTableName) .indexName("GSI-0") .keyConditionExpression("#pk = :projectname AND #sk BETWEEN :date1 AND :date2") .expressionAttributeNames(query20AttributeNames) .expressionAttributeValues(query20AttributeValues) .build(); QueryResponse query20Response = ddb.query(query20Request); // Validate query was returned successfully assert 200 == query20Response.sdkHttpResponse().statusCode(); // Assert 2 items returned: // Expected to be `timecard1` and `timecard2` assert query20Response.items().size() == 2; // Known value test: Assert some properties on one of the items boolean foundKnownValueItemQuery20 = false; for (Map<String, AttributeValue> item : query20Response.items()) { if (item.get("partition_key").s().equals("timecard1")) { foundKnownValueItemQuery20 = true; assert item.get("ProjectName").s().equals("project_002"); } } assert foundKnownValueItemQuery20; } public static void runQuery21(String ddbTableName, DynamoDbClient ddb) { // Query 21: Get Project History by role // Key condition: PK = ProjectName // Filter condition: role=rolename Map<String,String> query21AttributeNames = new HashMap<>(); query21AttributeNames.put("#pk", "PK"); query21AttributeNames.put("#role", "Role"); Map<String,AttributeValue> query21AttributeValues = new HashMap<>(); query21AttributeValues.put(":projectname", AttributeValue.builder().s("P-project_002").build()); query21AttributeValues.put(":role", AttributeValue.builder().s("SDE3").build()); QueryRequest query21Request = QueryRequest.builder() .tableName(ddbTableName) .indexName("GSI-0") .keyConditionExpression("#pk = :projectname") .filterExpression("#role = :role") .expressionAttributeNames(query21AttributeNames) .expressionAttributeValues(query21AttributeValues) .build(); QueryResponse query21Response = ddb.query(query21Request); // Validate query was returned successfully assert 200 == query21Response.sdkHttpResponse().statusCode(); // Assert 1 item was returned: `timecard1` assert query21Response.items().size() == 1; // Known value test: Assert some properties on one of the items boolean foundKnownValueItemQuery21 = false; for (Map<String, AttributeValue> item : query21Response.items()) { if (item.get("partition_key").s().equals("timecard1")) { foundKnownValueItemQuery21 = true; assert item.get("ProjectName").s().equals("project_002"); } } assert foundKnownValueItemQuery21; } public static void runQuery22(String ddbTableName, DynamoDbClient ddb) { // Query 22: Get reservations by building ID // Key condition: PK = Building ID Map<String,String> query22AttributeNames = new HashMap<>(); query22AttributeNames.put("#pk", "PK"); Map<String,AttributeValue> query22AttributeValues = new HashMap<>(); query22AttributeValues.put(":building", AttributeValue.builder().s("B-SEA33").build()); QueryRequest query22Request = QueryRequest.builder() .tableName(ddbTableName) .indexName("GSI-0") .keyConditionExpression("#pk = :building") .expressionAttributeNames(query22AttributeNames) .expressionAttributeValues(query22AttributeValues) .build(); QueryResponse query22Response = ddb.query(query22Request); // Validate query was returned successfully assert 200 == query22Response.sdkHttpResponse().statusCode(); // Assert 2 items returned: // Expected to be `reservation1` and `reservation2` assert query22Response.items().size() == 2; // Known value test: Assert some properties on one of the items boolean foundKnownValueItemQuery22 = false; for (Map<String, AttributeValue> item : query22Response.items()) { if (item.get("partition_key").s().equals("reservation1")) { foundKnownValueItemQuery22 = true; assert item.get("Subject").s().equals("Scan beacons"); } } assert foundKnownValueItemQuery22; } public static void runQuery23(String ddbTableName, DynamoDbClient ddb) { // Query 23: Get reservations by building ID and time range // Key condition: PK = Building ID, SK between(date1, date2) // Filter condition: Duration > 0 Map<String,String> query23AttributeNames = new HashMap<>(); query23AttributeNames.put("#pk", "PK"); query23AttributeNames.put("#sk", "SK"); query23AttributeNames.put("#duration", "Duration"); Map<String,AttributeValue> query23AttributeValues = new HashMap<>(); query23AttributeValues.put(":building", AttributeValue.builder().s("B-SEA33").build()); query23AttributeValues.put(":date1", AttributeValue.builder().s("MS-2022-07-01").build()); query23AttributeValues.put(":date2", AttributeValue.builder().s("MS-2022-07-08").build()); query23AttributeValues.put(":zero", AttributeValue.builder().s("0").build()); QueryRequest query23Request = QueryRequest.builder() .tableName(ddbTableName) .indexName("GSI-0") .keyConditionExpression("#pk = :building AND #sk BETWEEN :date1 AND :date2") .filterExpression("#duration > :zero") .expressionAttributeNames(query23AttributeNames) .expressionAttributeValues(query23AttributeValues) .build(); QueryResponse query23Response = ddb.query(query23Request); // Validate query was returned successfully assert 200 == query23Response.sdkHttpResponse().statusCode(); // Assert 2 items returned: // Expected to be `reservation1` and `reservation2` assert query23Response.items().size() == 2; // Known value test: Assert some properties on one of the items boolean foundKnownValueItemQuery23 = false; for (Map<String, AttributeValue> item : query23Response.items()) { if (item.get("partition_key").s().equals("reservation1")) { foundKnownValueItemQuery23 = true; assert item.get("Subject").s().equals("Scan beacons"); } } assert foundKnownValueItemQuery23; } }
5,270
0
Create_ds/aws-database-encryption-sdk-dynamodb-java/Examples/runtimes/java/Migration/DDBECToAWSDBE/src/test/java/software/amazon/cryptography/examples/migration
Create_ds/aws-database-encryption-sdk-dynamodb-java/Examples/runtimes/java/Migration/DDBECToAWSDBE/src/test/java/software/amazon/cryptography/examples/migration/ddbec/TestUtils.java
package software.amazon.cryptography.examples.migration.ddbec; public class TestUtils { // This is a public KMS Key that MUST only be used for testing, and MUST NOT be used for any production data public static String TEST_KMS_KEY_ID = "arn:aws:kms:us-west-2:658956600833:key/b3537ef1-d8dc-4780-9f5a-55776cbb2f7f"; // Our tests require access to DDB Table with this name public static final String TEST_DDB_TABLE_NAME = "DynamoDbEncryptionInterceptorTestTable"; }
5,271
0
Create_ds/aws-database-encryption-sdk-dynamodb-java/Examples/runtimes/java/Migration/DDBECToAWSDBE/src/test/java/software/amazon/cryptography/examples/migration
Create_ds/aws-database-encryption-sdk-dynamodb-java/Examples/runtimes/java/Migration/DDBECToAWSDBE/src/test/java/software/amazon/cryptography/examples/migration/ddbec/TestMigrationExampleStep0.java
package software.amazon.cryptography.examples.migration.ddbec; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMappingException; import org.testng.annotations.Test; import software.amazon.cryptography.examples.migration.awsdbe.MigrationExampleStep1; import software.amazon.cryptography.examples.migration.awsdbe.MigrationExampleStep2; import software.amazon.cryptography.examples.migration.awsdbe.MigrationExampleStep3; import static org.testng.Assert.assertThrows; public class TestMigrationExampleStep0 { @Test public void TestMigrationStep0() { // Successfully executes Step 0 MigrationExampleStep0.MigrationStep0(TestUtils.TEST_KMS_KEY_ID, TestUtils.TEST_DDB_TABLE_NAME, 0); // Given: Step 1 has succeeded MigrationExampleStep1.MigrationStep1(TestUtils.TEST_KMS_KEY_ID, TestUtils.TEST_DDB_TABLE_NAME, 1); // When: Execute Step 0 with sortReadValue=1, Then: Success (i.e. can read values in old format) MigrationExampleStep0.MigrationStep0(TestUtils.TEST_KMS_KEY_ID, TestUtils.TEST_DDB_TABLE_NAME, 1); // Given: Step 2 has succeeded MigrationExampleStep2.MigrationStep2(TestUtils.TEST_KMS_KEY_ID, TestUtils.TEST_DDB_TABLE_NAME, 2); // When: Execute Step 0 with sortReadValue=2, Then: throws DynamoDBMappingException (i.e. cannot read values in new format) assertThrows(DynamoDBMappingException.class, () -> { MigrationExampleStep0.MigrationStep0(TestUtils.TEST_KMS_KEY_ID, TestUtils.TEST_DDB_TABLE_NAME, 2); }); // Given: Step 3 has succeeded MigrationExampleStep3.MigrationStep3(TestUtils.TEST_KMS_KEY_ID, TestUtils.TEST_DDB_TABLE_NAME, 3); // When: Execute Step 0 with sortReadValue=3, Then: throws DynamoDBMappingException (i.e. cannot read values in new format) assertThrows(DynamoDBMappingException.class, () -> { MigrationExampleStep0.MigrationStep0(TestUtils.TEST_KMS_KEY_ID, TestUtils.TEST_DDB_TABLE_NAME, 3); }); } }
5,272
0
Create_ds/aws-database-encryption-sdk-dynamodb-java/Examples/runtimes/java/Migration/DDBECToAWSDBE/src/test/java/software/amazon/cryptography/examples/migration
Create_ds/aws-database-encryption-sdk-dynamodb-java/Examples/runtimes/java/Migration/DDBECToAWSDBE/src/test/java/software/amazon/cryptography/examples/migration/awsdbe/TestMigrationExampleStep1.java
package software.amazon.cryptography.examples.migration.awsdbe; import software.amazon.cryptography.examples.migration.ddbec.MigrationExampleStep0; import org.testng.annotations.Test; public class TestMigrationExampleStep1 { @Test public void TestMigrationStep1() { // Successfully executes step 1 MigrationExampleStep1.MigrationStep1(TestUtils.TEST_KMS_KEY_ID, TestUtils.TEST_DDB_TABLE_NAME, 1); // Given: Step 0 has succeeded MigrationExampleStep0.MigrationStep0(TestUtils.TEST_KMS_KEY_ID, TestUtils.TEST_DDB_TABLE_NAME, 0); // When: Execute Step 1 with sortReadValue=0, Then: Success (i.e. can read values in old format) MigrationExampleStep1.MigrationStep1(TestUtils.TEST_KMS_KEY_ID, TestUtils.TEST_DDB_TABLE_NAME, 0); // Given: Step 2 has succeeded MigrationExampleStep2.MigrationStep2(TestUtils.TEST_KMS_KEY_ID, TestUtils.TEST_DDB_TABLE_NAME, 2); // When: Execute Step 1 with sortReadValue=2, Then: Success (i.e. can read values in new format) MigrationExampleStep1.MigrationStep1(TestUtils.TEST_KMS_KEY_ID, TestUtils.TEST_DDB_TABLE_NAME, 2); // Given: Step 3 has succeeded MigrationExampleStep3.MigrationStep3(TestUtils.TEST_KMS_KEY_ID, TestUtils.TEST_DDB_TABLE_NAME, 3); // When: Execute Step 1 with sortReadValue=3, Then: Success (i.e. can read values in new format) MigrationExampleStep1.MigrationStep1(TestUtils.TEST_KMS_KEY_ID, TestUtils.TEST_DDB_TABLE_NAME, 3); } }
5,273
0
Create_ds/aws-database-encryption-sdk-dynamodb-java/Examples/runtimes/java/Migration/DDBECToAWSDBE/src/test/java/software/amazon/cryptography/examples/migration
Create_ds/aws-database-encryption-sdk-dynamodb-java/Examples/runtimes/java/Migration/DDBECToAWSDBE/src/test/java/software/amazon/cryptography/examples/migration/awsdbe/TestUtils.java
package software.amazon.cryptography.examples.migration.awsdbe; public class TestUtils { // This is a public KMS Key that MUST only be used for testing, and MUST NOT be used for any production data public static String TEST_KMS_KEY_ID = "arn:aws:kms:us-west-2:658956600833:key/b3537ef1-d8dc-4780-9f5a-55776cbb2f7f"; // Our tests require access to DDB Table with this name public static final String TEST_DDB_TABLE_NAME = "DynamoDbEncryptionInterceptorTestTable"; }
5,274
0
Create_ds/aws-database-encryption-sdk-dynamodb-java/Examples/runtimes/java/Migration/DDBECToAWSDBE/src/test/java/software/amazon/cryptography/examples/migration
Create_ds/aws-database-encryption-sdk-dynamodb-java/Examples/runtimes/java/Migration/DDBECToAWSDBE/src/test/java/software/amazon/cryptography/examples/migration/awsdbe/TestMigrationExampleStep3.java
package software.amazon.cryptography.examples.migration.awsdbe; import software.amazon.cryptography.examples.migration.ddbec.MigrationExampleStep0; import org.testng.annotations.Test; import software.amazon.awssdk.core.exception.SdkClientException; import static org.testng.Assert.assertThrows; public class TestMigrationExampleStep3 { @Test public void TestMigrationStep3() { // Successfully executes Step 3 MigrationExampleStep3.MigrationStep3(TestUtils.TEST_KMS_KEY_ID, TestUtils.TEST_DDB_TABLE_NAME, 3); // Given: Step 0 has succeeded MigrationExampleStep0.MigrationStep0(TestUtils.TEST_KMS_KEY_ID, TestUtils.TEST_DDB_TABLE_NAME, 0); // When: Execute Step 3 with sortReadValue=0, Then: throws SdkClientException (i.e. cannot read values in old format) assertThrows(SdkClientException.class, () -> { MigrationExampleStep3.MigrationStep3(TestUtils.TEST_KMS_KEY_ID, TestUtils.TEST_DDB_TABLE_NAME, 0); }); // Given: Step 1 has succeeded MigrationExampleStep1.MigrationStep1( software.amazon.cryptography.examples.migration.ddbec.TestUtils.TEST_KMS_KEY_ID, software.amazon.cryptography.examples.migration.ddbec.TestUtils.TEST_DDB_TABLE_NAME, 1); // When: Execute Step 3 with sortReadValue=1, Then: throws SdkClientException (i.e. cannot read values in old format) assertThrows(SdkClientException.class, () -> { MigrationExampleStep3.MigrationStep3(TestUtils.TEST_KMS_KEY_ID, TestUtils.TEST_DDB_TABLE_NAME, 1); }); // Given: Step 2 has succeeded MigrationExampleStep2.MigrationStep2( software.amazon.cryptography.examples.migration.ddbec.TestUtils.TEST_KMS_KEY_ID, software.amazon.cryptography.examples.migration.ddbec.TestUtils.TEST_DDB_TABLE_NAME, 2); // When: Execute Step 3 with sortReadValue=2, Then: Success (i.e. can read values in new format) MigrationExampleStep3.MigrationStep3(TestUtils.TEST_KMS_KEY_ID, TestUtils.TEST_DDB_TABLE_NAME, 2); } }
5,275
0
Create_ds/aws-database-encryption-sdk-dynamodb-java/Examples/runtimes/java/Migration/DDBECToAWSDBE/src/test/java/software/amazon/cryptography/examples/migration
Create_ds/aws-database-encryption-sdk-dynamodb-java/Examples/runtimes/java/Migration/DDBECToAWSDBE/src/test/java/software/amazon/cryptography/examples/migration/awsdbe/TestMigrationExampleStep2.java
package software.amazon.cryptography.examples.migration.awsdbe; import software.amazon.cryptography.examples.migration.ddbec.MigrationExampleStep0; import org.testng.annotations.Test; public class TestMigrationExampleStep2 { @Test public void TestMigrationStep2() { // Successfully executes step 2 MigrationExampleStep2.MigrationStep2(TestUtils.TEST_KMS_KEY_ID, TestUtils.TEST_DDB_TABLE_NAME, 2); // Given: Step 0 has succeeded MigrationExampleStep0.MigrationStep0(TestUtils.TEST_KMS_KEY_ID, TestUtils.TEST_DDB_TABLE_NAME, 0); // When: Execute Step 2 with sortReadValue=0, Then: Success (i.e. can read values in old format) MigrationExampleStep2.MigrationStep2(TestUtils.TEST_KMS_KEY_ID, TestUtils.TEST_DDB_TABLE_NAME, 0); // Given: Step 1 has succeeded MigrationExampleStep1.MigrationStep1(TestUtils.TEST_KMS_KEY_ID, TestUtils.TEST_DDB_TABLE_NAME, 1); // When: Execute Step 2 with sortReadValue=1, Then: Success (i.e. can read values in old format) MigrationExampleStep2.MigrationStep2(TestUtils.TEST_KMS_KEY_ID, TestUtils.TEST_DDB_TABLE_NAME, 1); // Given: Step 3 has succeeded MigrationExampleStep3.MigrationStep3(TestUtils.TEST_KMS_KEY_ID, TestUtils.TEST_DDB_TABLE_NAME, 3); // When: Execute Step 3 with sortReadValue=3, Then: Success (i.e. can read values in new format) MigrationExampleStep2.MigrationStep2(TestUtils.TEST_KMS_KEY_ID, TestUtils.TEST_DDB_TABLE_NAME, 3); } }
5,276
0
Create_ds/aws-database-encryption-sdk-dynamodb-java/Examples/runtimes/java/Migration/DDBECToAWSDBE/src/main/java/software/amazon/cryptography/examples/migration
Create_ds/aws-database-encryption-sdk-dynamodb-java/Examples/runtimes/java/Migration/DDBECToAWSDBE/src/main/java/software/amazon/cryptography/examples/migration/ddbec/SimpleClass.java
package software.amazon.cryptography.examples.migration.ddbec; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBAttribute; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBHashKey; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBRangeKey; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBTable; import com.amazonaws.services.dynamodbv2.datamodeling.encryption.DoNotEncrypt; import com.amazonaws.services.dynamodbv2.datamodeling.encryption.DoNotTouch; /** * This class is used by the Migration Examples */ @DynamoDBTable(tableName = "my-ddb-table") public class SimpleClass { private String partitionKey; private int sortKey; private String attribute1; private String attribute2; private String attribute3; @DynamoDBHashKey(attributeName="partition_key") public String getPartitionKey() { return this.partitionKey; } public void setPartitionKey(String partitionKey) { this.partitionKey = partitionKey; } @DynamoDBRangeKey(attributeName="sort_key") public int getSortKey() { return this.sortKey; } public void setSortKey(int sortKey) { this.sortKey = sortKey; } @DynamoDBAttribute(attributeName="attribute1") public String getAttribute1() { return this.attribute1; } public void setAttribute1(String attribute1) { this.attribute1 = attribute1; } @DoNotEncrypt @DynamoDBAttribute(attributeName="attribute2") public String getAttribute2() { return this.attribute2; } public void setAttribute2(String attribute2) { this.attribute2 = attribute2; } @DoNotTouch @DynamoDBAttribute(attributeName="attribute3") public String getAttribute3() { return this.attribute3; } public void setAttribute3(String attribute3) { this.attribute3 = attribute3; } }
5,277
0
Create_ds/aws-database-encryption-sdk-dynamodb-java/Examples/runtimes/java/Migration/DDBECToAWSDBE/src/main/java/software/amazon/cryptography/examples/migration
Create_ds/aws-database-encryption-sdk-dynamodb-java/Examples/runtimes/java/Migration/DDBECToAWSDBE/src/main/java/software/amazon/cryptography/examples/migration/ddbec/MigrationExampleStep0.java
package software.amazon.cryptography.examples.migration.ddbec; import com.amazonaws.services.dynamodbv2.AmazonDynamoDB; import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClientBuilder; import com.amazonaws.services.dynamodbv2.datamodeling.AttributeEncryptor; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapperConfig; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapperConfig.TableNameOverride; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapperConfig.SaveBehavior; import com.amazonaws.services.dynamodbv2.datamodeling.encryption.DynamoDBEncryptor; import com.amazonaws.services.dynamodbv2.datamodeling.encryption.providers.DirectKmsMaterialProvider; import com.amazonaws.services.kms.AWSKMS; import com.amazonaws.services.kms.AWSKMSClientBuilder; /* Migration Step 0: This is an example demonstrating use with the DynamoDb Encryption Client, and is the starting state for our migration to the AWS Database Encryption SDK for DynamoDb. In this example we configure a DynamoDBMapper configured to encrypt and decrypt items. The encryption and decryption of data is configured to use a KMS Key as the root of trust. Running this example requires access to the DDB Table whose name is provided in CLI arguments. This table must be configured with the following primary key configuration: - Partition key is named "partition_key" with type (S) - Sort key is named "sort_key" with type (S) */ public class MigrationExampleStep0 { public static void MigrationStep0(String kmsKeyId, String ddbTableName, int sortReadValue) { // 1. Create the MaterialProvider that protects your data keys. For this example, // we create a DirectKmsMaterialProvider which protects data keys using a single kmsKey. final AWSKMS kmsClient = AWSKMSClientBuilder.defaultClient(); final DirectKmsMaterialProvider cmp = new DirectKmsMaterialProvider(kmsClient, kmsKeyId); // 2. Create the DynamoDBEncryptor using the Material Provider created above final DynamoDBEncryptor encryptor = DynamoDBEncryptor.getInstance(cmp); // 3. Create a DynamoDbMapper with a AttributeEncryptor configured with the above encryptor. // You MUST configure this mapper with a save behavior of PUT or CLOBBER; // omitting this can result in data-corruption. AmazonDynamoDB ddbClient = AmazonDynamoDBClientBuilder.defaultClient(); DynamoDBMapperConfig mapperConfig = DynamoDBMapperConfig.builder() .withSaveBehavior(SaveBehavior.PUT) .withTableNameOverride(TableNameOverride.withTableNameReplacement(ddbTableName)) .build(); DynamoDBMapper mapper = new DynamoDBMapper(ddbClient, mapperConfig, new AttributeEncryptor(encryptor)); // 4. Put an example item into our DynamoDb table. // This item will be encrypted client-side before it is sent to DynamoDb. SimpleClass item = new SimpleClass(); item.setPartitionKey("MigrationExample"); item.setSortKey(0); item.setAttribute1("encrypt and sign me!"); item.setAttribute2("sign me!"); item.setAttribute3("ignore me!"); mapper.save(item); // 5. Get this item back from DynamoDb. // The item will be decrypted client-side, and the original item returned. SimpleClass decryptedItem = mapper.load(SimpleClass.class, "MigrationExample", sortReadValue); // Demonstrate we get the expected item back assert decryptedItem.getPartitionKey().equals("MigrationExample"); assert decryptedItem.getAttribute1().equals("encrypt and sign me!"); } public static void main(final String[] args) { if (args.length < 2) { throw new IllegalArgumentException("To run this example, include the kmsKeyId, ddbTableName, and sortReadValue as args."); } final String kmsKeyId = args[0]; final String ddbTableName = args[1]; // You can manipulate this value to demonstrate reading records written in other steps final int sortReadValue = Integer.parseInt(args[2]); MigrationStep0(kmsKeyId, ddbTableName, sortReadValue); } }
5,278
0
Create_ds/aws-database-encryption-sdk-dynamodb-java/Examples/runtimes/java/Migration/DDBECToAWSDBE/src/main/java/software/amazon/cryptography/examples/migration
Create_ds/aws-database-encryption-sdk-dynamodb-java/Examples/runtimes/java/Migration/DDBECToAWSDBE/src/main/java/software/amazon/cryptography/examples/migration/awsdbe/SimpleClass.java
package software.amazon.cryptography.examples.migration.awsdbe; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbAttribute; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbBean; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbPartitionKey; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbSortKey; import software.amazon.cryptography.dbencryptionsdk.dynamodb.enhancedclient.DynamoDbEncryptionDoNothing; import software.amazon.cryptography.dbencryptionsdk.dynamodb.enhancedclient.DynamoDbEncryptionSignOnly; /** * This class is used by the Enhanced Client Tests */ @DynamoDbBean public class SimpleClass { private String partitionKey; private int sortKey; private String attribute1; private String attribute2; private String attribute3; @DynamoDbPartitionKey @DynamoDbAttribute(value = "partition_key") public String getPartitionKey() { return this.partitionKey; } public void setPartitionKey(String partitionKey) { this.partitionKey = partitionKey; } @DynamoDbSortKey @DynamoDbAttribute(value = "sort_key") public int getSortKey() { return this.sortKey; } public void setSortKey(int sortKey) { this.sortKey = sortKey; } @DynamoDbAttribute(value = "attribute1") public String getAttribute1() { return this.attribute1; } public void setAttribute1(String attribute1) { this.attribute1 = attribute1; } @DynamoDbEncryptionSignOnly @DynamoDbAttribute(value = "attribute2") public String getAttribute2() { return this.attribute2; } public void setAttribute2(String attribute2) { this.attribute2 = attribute2; } @DynamoDbEncryptionDoNothing @DynamoDbAttribute(value = "attribute3") public String getAttribute3() { return this.attribute3; } public void setAttribute3(String attribute3) { this.attribute3 = attribute3; } }
5,279
0
Create_ds/aws-database-encryption-sdk-dynamodb-java/Examples/runtimes/java/Migration/DDBECToAWSDBE/src/main/java/software/amazon/cryptography/examples/migration
Create_ds/aws-database-encryption-sdk-dynamodb-java/Examples/runtimes/java/Migration/DDBECToAWSDBE/src/main/java/software/amazon/cryptography/examples/migration/awsdbe/MigrationExampleStep3.java
package software.amazon.cryptography.examples.migration.awsdbe; import software.amazon.awssdk.core.client.config.ClientOverrideConfiguration; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClient; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbTable; import software.amazon.awssdk.enhanced.dynamodb.Key; import software.amazon.awssdk.enhanced.dynamodb.TableSchema; import software.amazon.awssdk.enhanced.dynamodb.model.GetItemEnhancedRequest; import software.amazon.awssdk.services.dynamodb.DynamoDbClient; import software.amazon.cryptography.materialproviders.IKeyring; import software.amazon.cryptography.materialproviders.MaterialProviders; import software.amazon.cryptography.materialproviders.model.CreateAwsKmsMrkMultiKeyringInput; import software.amazon.cryptography.materialproviders.model.MaterialProvidersConfig; import software.amazon.cryptography.dbencryptionsdk.dynamodb.DynamoDbEncryptionInterceptor; import software.amazon.cryptography.dbencryptionsdk.dynamodb.enhancedclient.CreateDynamoDbEncryptionInterceptorInput; import software.amazon.cryptography.dbencryptionsdk.dynamodb.enhancedclient.DynamoDbEnhancedClientEncryption; import software.amazon.cryptography.dbencryptionsdk.dynamodb.enhancedclient.DynamoDbEnhancedTableEncryptionConfig; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; /* Migration Step 3: This is an example demonstrating how to update your configuration to stop accepting reading items encrypted using the old format. In order to proceed with this step, you will need to re-encrypt all old items in your table. Once you complete Step 3, you can be sure that all items being read by your system ensure the security properties configured for the new format. Running this example requires access to the DDB Table whose name is provided in CLI arguments. This table must be configured with the following primary key configuration: - Partition key is named "partition_key" with type (S) - Sort key is named "sort_key" with type (S) */ public class MigrationExampleStep3 { public static void MigrationStep3(String kmsKeyId, String ddbTableName, int sortReadValue) { // 1. Continue to configure your Keyring, Table Schema, // and allowedUnsignedAttributes as you did in Step 1. // However, now you can remove the configuration for the old DynamoDBEncryptor // and the legacy attribute actions. final MaterialProviders matProv = MaterialProviders.builder() .MaterialProvidersConfig(MaterialProvidersConfig.builder().build()) .build(); final CreateAwsKmsMrkMultiKeyringInput keyringInput = CreateAwsKmsMrkMultiKeyringInput.builder() .generator(kmsKeyId) .build(); final IKeyring kmsKeyring = matProv.CreateAwsKmsMrkMultiKeyring(keyringInput); final TableSchema<SimpleClass> schemaOnEncrypt = TableSchema.fromBean(SimpleClass.class); final List<String> allowedUnsignedAttributes = Arrays.asList("attribute3"); // 3. Create the DynamoDb Encryption Interceptor with the above configuration. // Do not configure any legacy behavior. final Map<String, DynamoDbEnhancedTableEncryptionConfig> tableConfigs = new HashMap<>(); tableConfigs.put(ddbTableName, DynamoDbEnhancedTableEncryptionConfig.builder() .logicalTableName(ddbTableName) .keyring(kmsKeyring) .allowedUnsignedAttributes(allowedUnsignedAttributes) .schemaOnEncrypt(schemaOnEncrypt) .build()); final DynamoDbEncryptionInterceptor interceptor = DynamoDbEnhancedClientEncryption.CreateDynamoDbEncryptionInterceptor( CreateDynamoDbEncryptionInterceptorInput.builder() .tableEncryptionConfigs(tableConfigs) .build() ); // 4. Create a new AWS SDK DynamoDb client using the DynamoDb Encryption Interceptor above final DynamoDbClient ddb = DynamoDbClient.builder() .overrideConfiguration( ClientOverrideConfiguration.builder() .addExecutionInterceptor(interceptor) .build()) .build(); // 5. Create the DynamoDbEnhancedClient using the AWS SDK Client created above, // and create a Table with your modelled class final DynamoDbEnhancedClient enhancedClient = DynamoDbEnhancedClient.builder() .dynamoDbClient(ddb) .build(); final DynamoDbTable<SimpleClass> table = enhancedClient.table(ddbTableName, schemaOnEncrypt); // 6. Put an item into your table using the DynamoDb Enhanced Client. // This item will be encrypted in the latest format, using the // configuration from your modelled class to decide // which attribute to encrypt and/or sign. final SimpleClass item = new SimpleClass(); item.setPartitionKey("MigrationExample"); item.setSortKey(3); item.setAttribute1("encrypt and sign me!"); item.setAttribute2("sign me!"); item.setAttribute3("ignore me!"); table.putItem(item); // 7. Get an item back from the table using the DynamoDb Enhanced Client. // If this is an item written in the old format (e.g. any item written // during Step 0 or 1), then we fail to return the item. // If this is an item written in the new format (e.g. any item written // during Step 2 or after), then we will attempt to decrypt the item using // the non-legacy behavior. final Key key = Key.builder() .partitionValue("MigrationExample").sortValue(sortReadValue) .build(); final SimpleClass decryptedItem = table.getItem( (GetItemEnhancedRequest.Builder requestBuilder) -> requestBuilder.key(key)); // Demonstrate we get the expected item back assert decryptedItem.getPartitionKey().equals("MigrationExample"); assert decryptedItem.getAttribute1().equals("encrypt and sign me!"); } public static void main(final String[] args) { if (args.length < 3) { throw new IllegalArgumentException("To run this example, include the kmsKeyId, ddbTableName, and sortReadValue as args."); } final String kmsKeyId = args[0]; final String ddbTableName = args[1]; // You can manipulate this value to demonstrate reading records written in other steps final int sortReadValue = Integer.parseInt(args[2]); MigrationStep3(kmsKeyId, ddbTableName, sortReadValue); } }
5,280
0
Create_ds/aws-database-encryption-sdk-dynamodb-java/Examples/runtimes/java/Migration/DDBECToAWSDBE/src/main/java/software/amazon/cryptography/examples/migration
Create_ds/aws-database-encryption-sdk-dynamodb-java/Examples/runtimes/java/Migration/DDBECToAWSDBE/src/main/java/software/amazon/cryptography/examples/migration/awsdbe/MigrationExampleStep2.java
package software.amazon.cryptography.examples.migration.awsdbe; import com.amazonaws.services.dynamodbv2.datamodeling.encryption.DynamoDBEncryptor; import com.amazonaws.services.dynamodbv2.datamodeling.encryption.providers.DirectKmsMaterialProvider; import com.amazonaws.services.kms.AWSKMS; import com.amazonaws.services.kms.AWSKMSClientBuilder; import software.amazon.awssdk.core.client.config.ClientOverrideConfiguration; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClient; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbTable; import software.amazon.awssdk.enhanced.dynamodb.Key; import software.amazon.awssdk.enhanced.dynamodb.TableSchema; import software.amazon.awssdk.enhanced.dynamodb.model.GetItemEnhancedRequest; import software.amazon.awssdk.services.dynamodb.DynamoDbClient; 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.CreateAwsKmsMrkMultiKeyringInput; import software.amazon.cryptography.materialproviders.model.MaterialProvidersConfig; import software.amazon.cryptography.dbencryptionsdk.structuredencryption.model.CryptoAction; import software.amazon.cryptography.dbencryptionsdk.dynamodb.DynamoDbEncryptionInterceptor; import software.amazon.cryptography.dbencryptionsdk.dynamodb.enhancedclient.CreateDynamoDbEncryptionInterceptorInput; import software.amazon.cryptography.dbencryptionsdk.dynamodb.enhancedclient.DynamoDbEnhancedClientEncryption; import software.amazon.cryptography.dbencryptionsdk.dynamodb.enhancedclient.DynamoDbEnhancedTableEncryptionConfig; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; /* Migration Step 2: This is an example demonstrating how to update your configuration to start writing items using the latest encryption format, but still continue to read any items written using the old encryption format. Once you deploy this change to your system, you will have a dataset containing items in both the old and new format. Because the changes in Step 1 have been deployed to all our readers, we can be sure that our entire system is ready to read this new data. Running this example requires access to the DDB Table whose name is provided in CLI arguments. This table must be configured with the following primary key configuration: - Partition key is named "partition_key" with type (S) - Sort key is named "sort_key" with type (S) */ public class MigrationExampleStep2 { public static void MigrationStep2(String kmsKeyId, String ddbTableName, int sortReadValue) { // 1. Continue to configure your Keyring, Table Schema, legacy attribute actions, // and allowedUnsignedAttributes, and old DynamoDBEncryptor as you did in Step 1. final MaterialProviders matProv = MaterialProviders.builder() .MaterialProvidersConfig(MaterialProvidersConfig.builder().build()) .build(); final CreateAwsKmsMrkMultiKeyringInput keyringInput = CreateAwsKmsMrkMultiKeyringInput.builder() .generator(kmsKeyId) .build(); final IKeyring kmsKeyring = matProv.CreateAwsKmsMrkMultiKeyring(keyringInput); final TableSchema<SimpleClass> schemaOnEncrypt = TableSchema.fromBean(SimpleClass.class); final List<String> allowedUnsignedAttributes = Arrays.asList("attribute3"); final Map<String, CryptoAction> legacyActions = new HashMap<>(); legacyActions.put("partition_key", CryptoAction.SIGN_ONLY); legacyActions.put("sort_key", CryptoAction.SIGN_ONLY); legacyActions.put("attribute1", CryptoAction.ENCRYPT_AND_SIGN); legacyActions.put("attribute2", CryptoAction.SIGN_ONLY); legacyActions.put("attribute3", CryptoAction.DO_NOTHING); final AWSKMS kmsClient = AWSKMSClientBuilder.defaultClient(); final DirectKmsMaterialProvider cmp = new DirectKmsMaterialProvider(kmsClient, kmsKeyId); final DynamoDBEncryptor oldEncryptor = DynamoDBEncryptor.getInstance(cmp); // 2. When configuring our legacy behavior, use `FORBID_LEGACY_ENCRYPT_ALLOW_LEGACY_DECRYPT`. // With this policy, you will continue to read items in both formats, // but will only write new items using the new format. final LegacyOverride legacyOverride = LegacyOverride .builder() .encryptor(oldEncryptor) .policy(LegacyPolicy.FORBID_LEGACY_ENCRYPT_ALLOW_LEGACY_DECRYPT) .attributeActionsOnEncrypt(legacyActions) .build(); // 3. Create the DynamoDb Encryption Interceptor with the above configuration. final Map<String, DynamoDbEnhancedTableEncryptionConfig> tableConfigs = new HashMap<>(); tableConfigs.put(ddbTableName, DynamoDbEnhancedTableEncryptionConfig.builder() .logicalTableName(ddbTableName) .keyring(kmsKeyring) .allowedUnsignedAttributes(allowedUnsignedAttributes) .schemaOnEncrypt(schemaOnEncrypt) .legacyOverride(legacyOverride) .build()); final DynamoDbEncryptionInterceptor interceptor = DynamoDbEnhancedClientEncryption.CreateDynamoDbEncryptionInterceptor( CreateDynamoDbEncryptionInterceptorInput.builder() .tableEncryptionConfigs(tableConfigs) .build() ); // 4. Create a new AWS SDK DynamoDb client using the DynamoDb Encryption Interceptor above final DynamoDbClient ddb = DynamoDbClient.builder() .overrideConfiguration( ClientOverrideConfiguration.builder() .addExecutionInterceptor(interceptor) .build()) .build(); // 5. Create the DynamoDbEnhancedClient using the AWS SDK Client created above, // and create a Table with your modelled class final DynamoDbEnhancedClient enhancedClient = DynamoDbEnhancedClient.builder() .dynamoDbClient(ddb) .build(); final DynamoDbTable<SimpleClass> table = enhancedClient.table(ddbTableName, schemaOnEncrypt); // 6. Put an item into your table using the DynamoDb Enhanced Client. // This item will be encrypted in the latest format, using the // configuration from your modelled class to decide // which attribute to encrypt and/or sign. final SimpleClass item = new SimpleClass(); item.setPartitionKey("MigrationExample"); item.setSortKey(2); item.setAttribute1("encrypt and sign me!"); item.setAttribute2("sign me!"); item.setAttribute3("ignore me!"); table.putItem(item); // 7. Get an item back from the table using the DynamoDb Enhanced Client. // If this is an item written in the old format (e.g. any item written // during Step 0 or 1), then we will attempt to decrypt the item // using the legacy behavior. // If this is an item written in the new format (e.g. any item written // during Step 2 or after), then we will attempt to decrypt the item using // the non-legacy behavior. final Key key = Key.builder() .partitionValue("MigrationExample").sortValue(sortReadValue) .build(); final SimpleClass decryptedItem = table.getItem( (GetItemEnhancedRequest.Builder requestBuilder) -> requestBuilder.key(key)); // Demonstrate we get the expected item back assert decryptedItem.getPartitionKey().equals("MigrationExample"); assert decryptedItem.getAttribute1().equals("encrypt and sign me!"); } public static void main(final String[] args) { if (args.length < 3) { throw new IllegalArgumentException("To run this example, include the kmsKeyId, ddbTableName, and sortReadValue as args."); } final String kmsKeyId = args[0]; final String ddbTableName = args[1]; // You can manipulate this value to demonstrate reading records written in other steps final int sortReadValue = Integer.parseInt(args[2]); MigrationStep2(kmsKeyId, ddbTableName, sortReadValue); } }
5,281
0
Create_ds/aws-database-encryption-sdk-dynamodb-java/Examples/runtimes/java/Migration/DDBECToAWSDBE/src/main/java/software/amazon/cryptography/examples/migration
Create_ds/aws-database-encryption-sdk-dynamodb-java/Examples/runtimes/java/Migration/DDBECToAWSDBE/src/main/java/software/amazon/cryptography/examples/migration/awsdbe/MigrationExampleStep1.java
package software.amazon.cryptography.examples.migration.awsdbe; import com.amazonaws.services.dynamodbv2.datamodeling.encryption.DynamoDBEncryptor; import com.amazonaws.services.dynamodbv2.datamodeling.encryption.providers.DirectKmsMaterialProvider; import com.amazonaws.services.kms.AWSKMS; import com.amazonaws.services.kms.AWSKMSClientBuilder; import software.amazon.awssdk.core.client.config.ClientOverrideConfiguration; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClient; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbTable; import software.amazon.awssdk.enhanced.dynamodb.Key; import software.amazon.awssdk.enhanced.dynamodb.TableSchema; import software.amazon.awssdk.enhanced.dynamodb.model.GetItemEnhancedRequest; import software.amazon.awssdk.services.dynamodb.DynamoDbClient; 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.CreateAwsKmsMrkMultiKeyringInput; import software.amazon.cryptography.materialproviders.model.MaterialProvidersConfig; import software.amazon.cryptography.dbencryptionsdk.structuredencryption.model.CryptoAction; import software.amazon.cryptography.dbencryptionsdk.dynamodb.DynamoDbEncryptionInterceptor; import software.amazon.cryptography.dbencryptionsdk.dynamodb.enhancedclient.CreateDynamoDbEncryptionInterceptorInput; import software.amazon.cryptography.dbencryptionsdk.dynamodb.enhancedclient.DynamoDbEnhancedClientEncryption; import software.amazon.cryptography.dbencryptionsdk.dynamodb.enhancedclient.DynamoDbEnhancedTableEncryptionConfig; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; /* Migration Step 1: This is an example demonstrating how to start using the AWS Database Encryption SDK with a pre-existing table used with DynamoDB Encryption Client. In this example, you configure a DynamoDb Encryption Interceptor to do the following: - Read items encrypted in the old format - Continue to encrypt items in the old format on write - Read items encrypted in the new format While this step configures your client to be ready to start reading items encrypted, we do not yet expect to be reading any items in the new format. Before you move on to step 2, ensure that these changes have successfully been deployed to all of your readers. Running this example requires access to the DDB Table whose name is provided in CLI arguments. This table must be configured with the following primary key configuration: - Partition key is named "partition_key" with type (S) - Sort key is named "sort_key" with type (S) */ public class MigrationExampleStep1 { public static void MigrationStep1(String kmsKeyId, String ddbTableName, int sortReadValue) { // 1. Create a Keyring. This Keyring will be responsible for protecting the data keys that protect your data. // For this migration, we will continue to encrypt and decrypt data using the kmsKeyId // used in Step 0 by configuring an AWS KMS Keyring with that same kmsKeyId. // We will use the `CreateMrkMultiKeyring` method to create this keyring, // as it will correctly handle both single region and Multi-Region KMS Keys. // Note that we are now using the AWS SDK for Java v2 KMS client. final MaterialProviders matProv = MaterialProviders.builder() .MaterialProvidersConfig(MaterialProvidersConfig.builder().build()) .build(); final CreateAwsKmsMrkMultiKeyringInput keyringInput = CreateAwsKmsMrkMultiKeyringInput.builder() .generator(kmsKeyId) .build(); final IKeyring kmsKeyring = matProv.CreateAwsKmsMrkMultiKeyring(keyringInput); // 2. Create a Table Schema over your annotated class. // See SimpleClass.java in this directory for the update to use the new DynamoDb Enhanced Client annotations. // All primary key attributes will be signed but not encrypted (SIGN_ONLY) // and by default all non-primary key attributes will be encrypted and signed (ENCRYPT_AND_SIGN). // If you want a particular non-primary key attribute to be signed but not encrypted, // use the `DynamoDbEncryptionSignOnly` annotation. // If you want a particular attribute to be neither signed nor encrypted (DO_NOTHING), // use the `DynamoDbEncryptionDoNothing` annotation. final TableSchema<SimpleClass> schemaOnEncrypt = TableSchema.fromBean(SimpleClass.class); // 3. Configure which attributes we expect to be excluded in the signature // when reading items. This value represents all unsigned attributes // across our entire dataset. If you ever want to add new unsigned attributes // in the future, you must make an update to this field to all your readers // before deploying any change to start writing that new data. It is not safe // to remove attributes from this field. final List<String> allowedUnsignedAttributes = Arrays.asList("attribute3"); // 4. Configure the attributeActionsOnEncrypt that are configured on our modelled class in Step 0 // in an explicit map. final Map<String, CryptoAction> legacyActions = new HashMap<>(); legacyActions.put("partition_key", CryptoAction.SIGN_ONLY); legacyActions.put("sort_key", CryptoAction.SIGN_ONLY); legacyActions.put("attribute1", CryptoAction.ENCRYPT_AND_SIGN); legacyActions.put("attribute2", CryptoAction.SIGN_ONLY); legacyActions.put("attribute3", CryptoAction.DO_NOTHING); // 5. Configure the same DynamoDBEncryptor that we did in Step 0. final AWSKMS kmsClient = AWSKMSClientBuilder.defaultClient(); final DirectKmsMaterialProvider cmp = new DirectKmsMaterialProvider(kmsClient, kmsKeyId); final DynamoDBEncryptor oldEncryptor = DynamoDBEncryptor.getInstance(cmp); // 6. Configure our legacy behavior, inputting the DynamoDBEncryptor and attribute actions // created above. For Legacy Policy, use `FORCE_LEGACY_ENCRYPT_ALLOW_LEGACY_DECRYPT`. // With this policy, you will continue to read and write items using the old format, // but will be able to start reading new items in the new format as soon as they appear. final LegacyOverride legacyOverride = LegacyOverride .builder() .encryptor(oldEncryptor) .policy(LegacyPolicy.FORCE_LEGACY_ENCRYPT_ALLOW_LEGACY_DECRYPT) .attributeActionsOnEncrypt(legacyActions) .build(); // 7. Create the DynamoDb Encryption Interceptor with the above configuration. final Map<String, DynamoDbEnhancedTableEncryptionConfig> tableConfigs = new HashMap<>(); tableConfigs.put(ddbTableName, DynamoDbEnhancedTableEncryptionConfig.builder() .logicalTableName(ddbTableName) .keyring(kmsKeyring) .allowedUnsignedAttributes(allowedUnsignedAttributes) .schemaOnEncrypt(schemaOnEncrypt) .legacyOverride(legacyOverride) .build()); final DynamoDbEncryptionInterceptor interceptor = DynamoDbEnhancedClientEncryption.CreateDynamoDbEncryptionInterceptor( CreateDynamoDbEncryptionInterceptorInput.builder() .tableEncryptionConfigs(tableConfigs) .build() ); // 8. Create a new AWS SDK DynamoDb client using the DynamoDb Encryption Interceptor above final DynamoDbClient ddb = DynamoDbClient.builder() .overrideConfiguration( ClientOverrideConfiguration.builder() .addExecutionInterceptor(interceptor) .build()) .build(); // 9. Create the DynamoDbEnhancedClient using the AWS SDK Client created above, // and create a Table with your modelled class final DynamoDbEnhancedClient enhancedClient = DynamoDbEnhancedClient.builder() .dynamoDbClient(ddb) .build(); final DynamoDbTable<SimpleClass> table = enhancedClient.table(ddbTableName, schemaOnEncrypt); // 10. Put an item into your table using the DynamoDb Enhanced Client. // This item will be encrypted in the legacy format, using the // old DynamoDBEncryptor and the legacy attribute actions. // In this step, we do not expect items to be encrypted any differently // from before. final SimpleClass item = new SimpleClass(); item.setPartitionKey("MigrationExample"); item.setSortKey(1); item.setAttribute1("encrypt and sign me!"); item.setAttribute2("sign me!"); item.setAttribute3("ignore me!"); table.putItem(item); // 11. Get an item back from the table using the DynamoDb Enhanced Client. // If this is an item written in the old format (e.g. any item written // during Step 0 or 1), then we will attempt to decrypt the item // using the legacy behavior. // If this is an item written in the new format (e.g. any item written // during Step 2 or after), then we will attempt to decrypt the item using // the non-legacy behavior. final Key key = Key.builder() .partitionValue("MigrationExample").sortValue(sortReadValue) .build(); final SimpleClass decryptedItem = table.getItem( (GetItemEnhancedRequest.Builder requestBuilder) -> requestBuilder.key(key)); // Demonstrate we get the expected item back assert decryptedItem.getPartitionKey().equals("MigrationExample"); assert decryptedItem.getAttribute1().equals("encrypt and sign me!"); } public static void main(final String[] args) { if (args.length < 3) { throw new IllegalArgumentException("To run this example, include the kmsKeyId, ddbTableName, and sortReadValue as args."); } final String kmsKeyId = args[0]; final String ddbTableName = args[1]; // You can manipulate this value to demonstrate reading records written in other steps final int sortReadValue = Integer.parseInt(args[2]); MigrationStep1(kmsKeyId, ddbTableName, sortReadValue); } }
5,282
0
Create_ds/aws-database-encryption-sdk-dynamodb-java/Examples/runtimes/java/Migration/PlaintextToAWSDBE/src/test/java/software/amazon/cryptography/examples/migration
Create_ds/aws-database-encryption-sdk-dynamodb-java/Examples/runtimes/java/Migration/PlaintextToAWSDBE/src/test/java/software/amazon/cryptography/examples/migration/plaintext/TestUtils.java
package software.amazon.cryptography.examples.migration.plaintext; public class TestUtils { // This is a public KMS Key that MUST only be used for testing, and MUST NOT be used for any production data public static String TEST_KMS_KEY_ID = "arn:aws:kms:us-west-2:658956600833:key/b3537ef1-d8dc-4780-9f5a-55776cbb2f7f"; // Our tests require access to DDB Table with this name public static final String TEST_DDB_TABLE_NAME = "DynamoDbEncryptionInterceptorTestTable"; }
5,283
0
Create_ds/aws-database-encryption-sdk-dynamodb-java/Examples/runtimes/java/Migration/PlaintextToAWSDBE/src/test/java/software/amazon/cryptography/examples/migration
Create_ds/aws-database-encryption-sdk-dynamodb-java/Examples/runtimes/java/Migration/PlaintextToAWSDBE/src/test/java/software/amazon/cryptography/examples/migration/plaintext/TestMigrationExampleStep0.java
package software.amazon.cryptography.examples.migration.plaintext; import org.testng.annotations.Test; import software.amazon.cryptography.examples.awsdbe.MigrationExampleStep1; import software.amazon.cryptography.examples.awsdbe.MigrationExampleStep2; import software.amazon.cryptography.examples.awsdbe.MigrationExampleStep3; import software.amazon.cryptography.examples.plaintext.MigrationExampleStep0; import static org.testng.Assert.assertThrows; public class TestMigrationExampleStep0 { @Test public void TestMigrationStep0() { // Successfully executes step 0 MigrationExampleStep0.MigrationStep0(TestUtils.TEST_DDB_TABLE_NAME, 0); // Given: Step 1 has succeeded MigrationExampleStep1.MigrationStep1(TestUtils.TEST_KMS_KEY_ID, TestUtils.TEST_DDB_TABLE_NAME, 1); // When: Execute Step 0 with sortReadValue=1, Then: Success (i.e. can read plaintext values) MigrationExampleStep0.MigrationStep0(TestUtils.TEST_DDB_TABLE_NAME, 1); // Given: Step 2 has succeeded MigrationExampleStep2.MigrationStep2(TestUtils.TEST_KMS_KEY_ID, TestUtils.TEST_DDB_TABLE_NAME, 2); // When: Execute Step 0 with sortReadValue=2, Then: throws AssertionError (i.e. cannot read encrypted values) assertThrows(AssertionError.class, () -> { MigrationExampleStep0.MigrationStep0(TestUtils.TEST_DDB_TABLE_NAME, 2); }); // Given: Step 3 has succeeded MigrationExampleStep3.MigrationStep3(TestUtils.TEST_KMS_KEY_ID, TestUtils.TEST_DDB_TABLE_NAME, 3); // When: Execute Step 0 with sortReadValue=3, Then: throws AssertionError (i.e. cannot read encrypted values) assertThrows(AssertionError.class, () -> { MigrationExampleStep0.MigrationStep0(TestUtils.TEST_DDB_TABLE_NAME, 3); }); } }
5,284
0
Create_ds/aws-database-encryption-sdk-dynamodb-java/Examples/runtimes/java/Migration/PlaintextToAWSDBE/src/test/java/software/amazon/cryptography/examples/migration
Create_ds/aws-database-encryption-sdk-dynamodb-java/Examples/runtimes/java/Migration/PlaintextToAWSDBE/src/test/java/software/amazon/cryptography/examples/migration/awsdbe/TestMigrationExampleStep1.java
package software.amazon.cryptography.examples.migration.awsdbe; import org.testng.annotations.Test; import software.amazon.cryptography.examples.plaintext.MigrationExampleStep0; import software.amazon.cryptography.examples.awsdbe.MigrationExampleStep1; import software.amazon.cryptography.examples.awsdbe.MigrationExampleStep2; import software.amazon.cryptography.examples.awsdbe.MigrationExampleStep3; public class TestMigrationExampleStep1 { @Test public void TestMigrationStep1() { // Successfully executes Step 1 MigrationExampleStep1.MigrationStep1(TestUtils.TEST_KMS_KEY_ID, TestUtils.TEST_DDB_TABLE_NAME, 1); // Given: Step 0 has succeeded MigrationExampleStep0.MigrationStep0(TestUtils.TEST_DDB_TABLE_NAME, 0); // When: Execute Step 1 with sortReadValue=0, Then: Success (i.e. can read plaintext values) MigrationExampleStep1.MigrationStep1(TestUtils.TEST_KMS_KEY_ID, TestUtils.TEST_DDB_TABLE_NAME, 0); // Given: Step 2 has succeeded MigrationExampleStep2.MigrationStep2(TestUtils.TEST_KMS_KEY_ID, TestUtils.TEST_DDB_TABLE_NAME, 2); // When: Execute Step 1 with sortReadValue=2, Then: Success (i.e. can read encrypted values) MigrationExampleStep1.MigrationStep1(TestUtils.TEST_KMS_KEY_ID, TestUtils.TEST_DDB_TABLE_NAME, 2); // Given: Step 3 has succeeded MigrationExampleStep3.MigrationStep3(TestUtils.TEST_KMS_KEY_ID, TestUtils.TEST_DDB_TABLE_NAME, 3); // When: Execute Step 1 with sortReadValue=3, Then: Success (i.e. can read encrypted values) MigrationExampleStep1.MigrationStep1(TestUtils.TEST_KMS_KEY_ID, TestUtils.TEST_DDB_TABLE_NAME, 3); } }
5,285
0
Create_ds/aws-database-encryption-sdk-dynamodb-java/Examples/runtimes/java/Migration/PlaintextToAWSDBE/src/test/java/software/amazon/cryptography/examples/migration
Create_ds/aws-database-encryption-sdk-dynamodb-java/Examples/runtimes/java/Migration/PlaintextToAWSDBE/src/test/java/software/amazon/cryptography/examples/migration/awsdbe/TestUtils.java
package software.amazon.cryptography.examples.migration.awsdbe; public class TestUtils { // This is a public KMS Key that MUST only be used for testing, and MUST NOT be used for any production data public static String TEST_KMS_KEY_ID = "arn:aws:kms:us-west-2:658956600833:key/b3537ef1-d8dc-4780-9f5a-55776cbb2f7f"; // Our tests require access to DDB Table with this name public static final String TEST_DDB_TABLE_NAME = "DynamoDbEncryptionInterceptorTestTable"; }
5,286
0
Create_ds/aws-database-encryption-sdk-dynamodb-java/Examples/runtimes/java/Migration/PlaintextToAWSDBE/src/test/java/software/amazon/cryptography/examples/migration
Create_ds/aws-database-encryption-sdk-dynamodb-java/Examples/runtimes/java/Migration/PlaintextToAWSDBE/src/test/java/software/amazon/cryptography/examples/migration/awsdbe/TestMigrationExampleStep3.java
package software.amazon.cryptography.examples.migration.awsdbe; import static org.testng.Assert.assertThrows; import org.testng.annotations.Test; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.cryptography.examples.migration.plaintext.TestUtils; import software.amazon.cryptography.examples.awsdbe.MigrationExampleStep1; import software.amazon.cryptography.examples.awsdbe.MigrationExampleStep2; import software.amazon.cryptography.examples.awsdbe.MigrationExampleStep3; import software.amazon.cryptography.examples.plaintext.MigrationExampleStep0; public class TestMigrationExampleStep3 { @Test public void TestMigrationStep0() { // Successfully executes step 3 MigrationExampleStep3.MigrationStep3( software.amazon.cryptography.examples.migration.plaintext.TestUtils.TEST_KMS_KEY_ID, software.amazon.cryptography.examples.migration.plaintext.TestUtils.TEST_DDB_TABLE_NAME, 3); // Given: Step 0 has succeeded MigrationExampleStep0.MigrationStep0( software.amazon.cryptography.examples.migration.plaintext.TestUtils.TEST_DDB_TABLE_NAME, 0); // When: Execute Step 3 with sortReadValue=0, Then: throws SdkClientException (i.e. cannot read plaintext values) assertThrows(SdkClientException.class, () -> { MigrationExampleStep3.MigrationStep3( software.amazon.cryptography.examples.migration.plaintext.TestUtils.TEST_KMS_KEY_ID, software.amazon.cryptography.examples.migration.plaintext.TestUtils.TEST_DDB_TABLE_NAME, 0); }); // Given: Step 1 has succeeded MigrationExampleStep1.MigrationStep1( software.amazon.cryptography.examples.migration.plaintext.TestUtils.TEST_KMS_KEY_ID, software.amazon.cryptography.examples.migration.plaintext.TestUtils.TEST_DDB_TABLE_NAME, 1); // When: Execute Step 3 with sortReadValue=1, Then: throws SdkClientException (i.e. cannot read plaintext values) assertThrows(SdkClientException.class, () -> { MigrationExampleStep3.MigrationStep3( software.amazon.cryptography.examples.migration.plaintext.TestUtils.TEST_KMS_KEY_ID, software.amazon.cryptography.examples.migration.plaintext.TestUtils.TEST_DDB_TABLE_NAME, 1); }); // Given: Step 2 has succeeded MigrationExampleStep2.MigrationStep2( software.amazon.cryptography.examples.migration.plaintext.TestUtils.TEST_KMS_KEY_ID, software.amazon.cryptography.examples.migration.plaintext.TestUtils.TEST_DDB_TABLE_NAME, 2); // When: Execute Step 3 with sortReadValue=2, Then: Success (i.e. can read encrypted values) MigrationExampleStep3.MigrationStep3( software.amazon.cryptography.examples.migration.plaintext.TestUtils.TEST_KMS_KEY_ID, TestUtils.TEST_DDB_TABLE_NAME, 2); } }
5,287
0
Create_ds/aws-database-encryption-sdk-dynamodb-java/Examples/runtimes/java/Migration/PlaintextToAWSDBE/src/test/java/software/amazon/cryptography/examples/migration
Create_ds/aws-database-encryption-sdk-dynamodb-java/Examples/runtimes/java/Migration/PlaintextToAWSDBE/src/test/java/software/amazon/cryptography/examples/migration/awsdbe/TestMigrationExampleStep2.java
package software.amazon.cryptography.examples.migration.awsdbe; import org.testng.annotations.Test; import software.amazon.cryptography.examples.awsdbe.MigrationExampleStep1; import software.amazon.cryptography.examples.awsdbe.MigrationExampleStep2; import software.amazon.cryptography.examples.awsdbe.MigrationExampleStep3; import software.amazon.cryptography.examples.plaintext.MigrationExampleStep0; public class TestMigrationExampleStep2 { @Test public void TestMigrationStep2() { // Successfully executes Step 2 MigrationExampleStep2.MigrationStep2(TestUtils.TEST_KMS_KEY_ID, TestUtils.TEST_DDB_TABLE_NAME, 2); // Given: Step 0 has succeeded MigrationExampleStep0.MigrationStep0(TestUtils.TEST_DDB_TABLE_NAME, 0); // When: Execute Step 2 with sortReadValue=0, Then: Success (i.e. can read plaintext values) MigrationExampleStep2.MigrationStep2(TestUtils.TEST_KMS_KEY_ID, TestUtils.TEST_DDB_TABLE_NAME, 0); // Given: Step 1 has succeeded MigrationExampleStep1.MigrationStep1(TestUtils.TEST_KMS_KEY_ID, TestUtils.TEST_DDB_TABLE_NAME, 1); // When: Execute Step 2 with sortReadValue=1, Then: Success (i.e. can read encrypted values) MigrationExampleStep2.MigrationStep2(TestUtils.TEST_KMS_KEY_ID, TestUtils.TEST_DDB_TABLE_NAME, 1); // Given: Step 3 has succeeded MigrationExampleStep3.MigrationStep3(TestUtils.TEST_KMS_KEY_ID, TestUtils.TEST_DDB_TABLE_NAME, 3); // When: Execute Step 2 with sortReadValue=3, Then: Success (i.e. can read encrypted values) MigrationExampleStep2.MigrationStep2(TestUtils.TEST_KMS_KEY_ID, TestUtils.TEST_DDB_TABLE_NAME, 3); } }
5,288
0
Create_ds/aws-database-encryption-sdk-dynamodb-java/Examples/runtimes/java/Migration/PlaintextToAWSDBE/src/test/java/software/amazon/cryptography/examples/migration/awsdbe
Create_ds/aws-database-encryption-sdk-dynamodb-java/Examples/runtimes/java/Migration/PlaintextToAWSDBE/src/test/java/software/amazon/cryptography/examples/migration/awsdbe/encrypttable/TestEncryptExistingTable.java
package software.amazon.cryptography.examples.migration.awsdbe.encrypttable; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import org.testng.annotations.Test; import software.amazon.awssdk.core.client.config.ClientOverrideConfiguration; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClient; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbTable; import software.amazon.awssdk.enhanced.dynamodb.Expression; import software.amazon.awssdk.enhanced.dynamodb.TableSchema; import software.amazon.awssdk.enhanced.dynamodb.model.PageIterable; import software.amazon.awssdk.enhanced.dynamodb.model.ScanEnhancedRequest; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.dynamodb.DynamoDbClient; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; import software.amazon.cryptography.dbencryptionsdk.dynamodb.DynamoDbEncryptionInterceptor; import software.amazon.cryptography.dbencryptionsdk.dynamodb.enhancedclient.CreateDynamoDbEncryptionInterceptorInput; import software.amazon.cryptography.dbencryptionsdk.dynamodb.enhancedclient.DynamoDbEnhancedClientEncryption; import software.amazon.cryptography.dbencryptionsdk.dynamodb.enhancedclient.DynamoDbEnhancedTableEncryptionConfig; import software.amazon.cryptography.dbencryptionsdk.dynamodb.model.PlaintextOverride; import software.amazon.cryptography.examples.awsdbe.MigrationExampleStep1; import software.amazon.cryptography.examples.awsdbe.MigrationExampleStep2; import software.amazon.cryptography.examples.awsdbe.SimpleClass; import software.amazon.cryptography.examples.migration.awsdbe.TestUtils; import software.amazon.cryptography.examples.plaintext.MigrationExampleStep0; import software.amazon.cryptography.materialproviders.IKeyring; import software.amazon.cryptography.materialproviders.MaterialProviders; import software.amazon.cryptography.materialproviders.model.CreateAwsKmsMrkMultiKeyringInput; import software.amazon.cryptography.materialproviders.model.MaterialProvidersConfig; /* DO NOT USE THE CODE IN THIS FILE FOR ANY PRODUCTION PURPOSE. THIS CODE IS NOT AN EXAMPLE OF ENCRYPTING AN EXISTING PLAINTEXT TABLE, AND IS NOT A SUPPORTED OR SUGGESTED APPROACH TO ENCRYPT A TABLE. This test contains a naive approach to encrypting all plaintext items in a table. This test configures a DynamoDbEnhancedClient to read plaintext items and write encrypted items. Then, it scans a table for all plaintext items. For each item in the scan, it Puts the item back to the table. The client will transparently encrypt the item when it is Put. Encrypting an existing table using a scan will not be feasible for any production applications with a reasonable scale (>1 MB). This file is included to test the library; it is not included as an example to encrypt an existing table and should not be used by any users. Users should analyze their own tables to find an approach to encrypt a table that works for them. */ public class TestEncryptExistingTable { public static void EncryptExistingTable(String kmsKeyId, String ddbTableName) { // 1. Continue to configure your Keyring, Table Schema, // and allowedUnsignedAttributes as you did in Step 1. MaterialProviders matProv = MaterialProviders.builder() .MaterialProvidersConfig(MaterialProvidersConfig.builder().build()) .build(); final CreateAwsKmsMrkMultiKeyringInput keyringInput = CreateAwsKmsMrkMultiKeyringInput.builder() .generator(kmsKeyId) .build(); final IKeyring kmsKeyring = matProv.CreateAwsKmsMrkMultiKeyring(keyringInput); final TableSchema<SimpleClass> tableSchema = TableSchema.fromBean(SimpleClass.class); final List<String> unsignedAttributes = Arrays.asList("attribute3"); // 2. Create encryption configuration for table, // using the same plaintext override as Step 2 // (`FORBID_PLAINTEXT_WRITE_ALLOW_PLAINTEXT_READ`). Map<String, DynamoDbEnhancedTableEncryptionConfig> tableConfigs = new HashMap<>(); tableConfigs.put(ddbTableName, DynamoDbEnhancedTableEncryptionConfig.builder() .logicalTableName(ddbTableName) .keyring(kmsKeyring) .schemaOnEncrypt(tableSchema) .allowedUnsignedAttributes(unsignedAttributes) .plaintextOverride(PlaintextOverride.FORBID_PLAINTEXT_WRITE_ALLOW_PLAINTEXT_READ) .build()); // 3. Create DynamoDbEncryptionInterceptor using the above config DynamoDbEncryptionInterceptor interceptor = DynamoDbEnhancedClientEncryption.CreateDynamoDbEncryptionInterceptor( CreateDynamoDbEncryptionInterceptorInput.builder() .tableEncryptionConfigs(tableConfigs) .build()); // 4. Create the EnhancedClient using the interceptor, and create a table from the schema DynamoDbClient ddb = DynamoDbClient.builder() .region(Region.US_WEST_2) .overrideConfiguration( ClientOverrideConfiguration.builder() .addExecutionInterceptor(interceptor) .build()) .build(); DynamoDbEnhancedClient enhancedClient = DynamoDbEnhancedClient.builder() .dynamoDbClient(ddb) .build(); final DynamoDbTable<SimpleClass> table = enhancedClient.table(ddbTableName, tableSchema); // 5. Scan the table for items with no `aws_dbe_head` attribute. // Any record with the `aws_dbe_head` attribute is an encrypted record. // Any record without the attribute is a plaintext record. // To limit the number of affected records, we also // add a condition to our filter expression that the `partition_key` // partition key attribute is specific to our test, i.e. // equals "PlaintextMigrationTest". We do this because our // table contains multiple types of records, and we are only encrypting // some in this test. Map<String,String> expressionAttributesNames = new HashMap<>(); expressionAttributesNames.put("#header", "aws_dbe_head"); expressionAttributesNames.put("#pk", "partition_key"); Map<String, AttributeValue> expressionAttributesValues = new HashMap<>(); expressionAttributesValues.put(":plaintexttest", AttributeValue.builder().s("PlaintextMigrationExample").build()); ScanEnhancedRequest scanEnhancedRequest = ScanEnhancedRequest.builder() // We use consistent reads because we run this test in our CI, // where we put items then scan for them very quickly. // This ensures our scan has data from all write requests. .consistentRead(true) .filterExpression(Expression.builder() .expression("attribute_not_exists(#header) and #pk = :plaintexttest") .expressionNames(expressionAttributesNames) .expressionValues(expressionAttributesValues) .build()) .build(); PageIterable<SimpleClass> scanIterable = table.scan(scanEnhancedRequest); // Verify we are about to modify an acceptable number of items. // In our test migration, this should be exactly 2. // Steps 0, 1, and 2 were run previously. // Steps 0 and 1 added plaintext items that did not have the header attribute, // while Step 2 added an encrypted item that did have the header attribute. // The scan should return the items from Steps 0 and 1. assert scanIterable.items().stream().count() == 2; // 6. Encrypt each item. // Since we have configured our table to write encrypted records, // we can simply put each item back to the table, // and the client will overwrite the plaintext record with the encrypted record. scanIterable.stream().forEach( p -> p.items().forEach( table::putItem ) ); // Demonstrate that the same scan now returns no results scanIterable = table.scan(scanEnhancedRequest); System.out.println(scanIterable.items().stream().count()); assert scanIterable.items().stream().count() == 0; } @Test public void TestEncryptExistingTable() { // Given: All the previous migration steps have been run. MigrationExampleStep0.MigrationStep0(TestUtils.TEST_DDB_TABLE_NAME, 0); MigrationExampleStep1.MigrationStep1(TestUtils.TEST_KMS_KEY_ID, TestUtils.TEST_DDB_TABLE_NAME, 1); MigrationExampleStep2.MigrationStep2(TestUtils.TEST_KMS_KEY_ID, TestUtils.TEST_DDB_TABLE_NAME, 2); // When: Execute migration, Then: Success (i.e. encrypts 2 plaintext values) EncryptExistingTable(TestUtils.TEST_KMS_KEY_ID, TestUtils.TEST_DDB_TABLE_NAME); } }
5,289
0
Create_ds/aws-database-encryption-sdk-dynamodb-java/Examples/runtimes/java/Migration/PlaintextToAWSDBE/src/main/java/software/amazon/cryptography/examples
Create_ds/aws-database-encryption-sdk-dynamodb-java/Examples/runtimes/java/Migration/PlaintextToAWSDBE/src/main/java/software/amazon/cryptography/examples/plaintext/CreateSimpleTable.java
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package software.amazon.cryptography.examples.plaintext; import software.amazon.awssdk.services.dynamodb.DynamoDbClient; import software.amazon.awssdk.services.dynamodb.model.AttributeDefinition; import software.amazon.awssdk.services.dynamodb.model.CreateTableRequest; import software.amazon.awssdk.services.dynamodb.model.CreateTableResponse; import software.amazon.awssdk.services.dynamodb.model.KeySchemaElement; import software.amazon.awssdk.services.dynamodb.model.KeyType; import software.amazon.awssdk.services.dynamodb.model.ScalarAttributeType; /** * This class is referenced by the README. */ @SuppressWarnings("unused") public class CreateSimpleTable { public static void Create(DynamoDbClient ddbClient, String ddbTableName) { CreateTableRequest request = CreateTableRequest.builder() .tableName(ddbTableName) .keySchema( KeySchemaElement.builder() .keyType(KeyType.HASH) .attributeName("partition_key") .build(), KeySchemaElement.builder() .keyType(KeyType.RANGE) .attributeName("sort_key") .build()) .attributeDefinitions( AttributeDefinition.builder() .attributeName("partition_key") .attributeType(ScalarAttributeType.S) .build(), AttributeDefinition.builder() .attributeName("sort_key") .attributeType(ScalarAttributeType.N) .build()) .build(); CreateTableResponse response = ddbClient.createTable(request); if (!response.sdkHttpResponse().isSuccessful()) { throw new RuntimeException( String.format( "Create Table Failed. HTTP response: %s", response.sdkHttpResponse())); } } }
5,290
0
Create_ds/aws-database-encryption-sdk-dynamodb-java/Examples/runtimes/java/Migration/PlaintextToAWSDBE/src/main/java/software/amazon/cryptography/examples
Create_ds/aws-database-encryption-sdk-dynamodb-java/Examples/runtimes/java/Migration/PlaintextToAWSDBE/src/main/java/software/amazon/cryptography/examples/plaintext/SimpleClass.java
package software.amazon.cryptography.examples.plaintext; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbAttribute; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbBean; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbPartitionKey; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbSortKey; /** * This class is used by the Migration Examples */ @DynamoDbBean public class SimpleClass { private String partitionKey; private int sortKey; private String attribute1; private String attribute2; private String attribute3; @DynamoDbPartitionKey @DynamoDbAttribute(value = "partition_key") public String getPartitionKey() { return this.partitionKey; } public void setPartitionKey(String partitionKey) { this.partitionKey = partitionKey; } @DynamoDbSortKey @DynamoDbAttribute(value = "sort_key") public int getSortKey() { return this.sortKey; } public void setSortKey(int sortKey) { this.sortKey = sortKey; } @DynamoDbAttribute(value="attribute1") public String getAttribute1() { return this.attribute1; } public void setAttribute1(String attribute1) { this.attribute1 = attribute1; } @DynamoDbAttribute(value="attribute2") public String getAttribute2() { return this.attribute2; } public void setAttribute2(String attribute2) { this.attribute2 = attribute2; } @DynamoDbAttribute(value="attribute3") public String getAttribute3() { return this.attribute3; } public void setAttribute3(String attribute3) { this.attribute3 = attribute3; } }
5,291
0
Create_ds/aws-database-encryption-sdk-dynamodb-java/Examples/runtimes/java/Migration/PlaintextToAWSDBE/src/main/java/software/amazon/cryptography/examples
Create_ds/aws-database-encryption-sdk-dynamodb-java/Examples/runtimes/java/Migration/PlaintextToAWSDBE/src/main/java/software/amazon/cryptography/examples/plaintext/EnhancedPlaintextPutGetExample.java
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package software.amazon.cryptography.examples.plaintext; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClient; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbTable; import software.amazon.awssdk.enhanced.dynamodb.TableSchema; import software.amazon.awssdk.services.dynamodb.DynamoDbClient; /** * This class is referenced by the README. */ @SuppressWarnings("unused") public class EnhancedPlaintextPutGetExample { public static void PutItemGetItem(DynamoDbClient ddb, String ddbTableName) { DynamoDbEnhancedClient enhancedClient = DynamoDbEnhancedClient.builder() .dynamoDbClient(ddb) .build(); final TableSchema<SimpleClass> tableSchema = TableSchema.fromBean(SimpleClass.class); final DynamoDbTable<SimpleClass> table = enhancedClient.table(ddbTableName, tableSchema); SimpleClass itemToPut = new SimpleClass(); itemToPut.setPartitionKey("anyKey"); itemToPut.setSortKey(0); itemToPut.setAttribute1("this is not encrypted"); table.putItem(itemToPut); // Load the item back from DynamoDB SimpleClass itemToGet = new SimpleClass(); itemToGet.setPartitionKey("anyKey"); itemToGet.setSortKey(0); SimpleClass returnedItem = table.getItem(itemToGet); } }
5,292
0
Create_ds/aws-database-encryption-sdk-dynamodb-java/Examples/runtimes/java/Migration/PlaintextToAWSDBE/src/main/java/software/amazon/cryptography/examples
Create_ds/aws-database-encryption-sdk-dynamodb-java/Examples/runtimes/java/Migration/PlaintextToAWSDBE/src/main/java/software/amazon/cryptography/examples/plaintext/MigrationExampleStep0.java
package software.amazon.cryptography.examples.plaintext; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClient; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbTable; import software.amazon.awssdk.enhanced.dynamodb.TableSchema; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.dynamodb.DynamoDbClient; /* Migration Step 0: This is the pre-migration step for the plaintext-to-encrypted database migration, and is the starting state for our migration from a plaintext database to a client-side encrypted database encrypted using the AWS Database Encryption SDK for DynamoDb. In this example, we configure a DynamoDbEnhancedClient to write a plaintext record to a table and read that record. This emulates the starting state of a plaintext-to-encrypted database migration; i.e. a plaintext database you can read and write to with the DynamoDbEnhancedClient. Running this example requires access to the DDB Table whose name is provided in CLI arguments. This table must be configured with the following primary key configuration: - Partition key is named "partition_key" with type (S) - Sort key is named "sort_key" with type (S) */ public class MigrationExampleStep0 { public static void MigrationStep0(String ddbTableName, int sortReadValue) { // 1. Create a Table Schema over your annotated class. // See SimpleClass.java in this directory for a sample annotated class // for a plaintext item. final TableSchema<SimpleClass> tableSchema = TableSchema.fromBean(SimpleClass.class); // 2. Create a DynamoDB EnhancedClient and a Table with the annotated class. // Note that the EnhancedClient is only available in AWS SDK for Java V2. // If you are using AWS SDK for Java v2's DDBMapper, you should first // migrate your config to the AWS SDK for Java v2's EnhancedClient. DynamoDbClient ddb = DynamoDbClient.builder() .region(Region.US_WEST_2) .build(); DynamoDbEnhancedClient enhancedClient = DynamoDbEnhancedClient.builder() .dynamoDbClient(ddb) .build(); final DynamoDbTable<SimpleClass> table = enhancedClient.table(ddbTableName, tableSchema); // 3. Put an example item into our DynamoDb table. // This item will be stored in plaintext. SimpleClass itemToPut = new SimpleClass(); itemToPut.setPartitionKey("PlaintextMigrationExample"); itemToPut.setSortKey(0); itemToPut.setAttribute1("this will be encrypted and signed"); itemToPut.setAttribute3("this will never be encrypted nor signed"); itemToPut.setAttribute2("this will never be encrypted, but it will be signed"); table.putItem(itemToPut); // 4. Get an item back from the table as it was written. // If this is an item written in plaintext (i.e. any item written // during Step 0 or 1), then the item will still be in plaintext // and will be able to be processed. // If this is an item that was encrypted client-side (i.e. any item written // during Step 2 or after), then the item will still be encrypted client-side // and will be unable to be processed in your code. To decrypt and process // client-side encrypted items, you will need to configure encrypted reads on // your enhanced client (this is configured from Step 1 onwards). SimpleClass itemToGet = new SimpleClass(); itemToGet.setPartitionKey("PlaintextMigrationExample"); itemToGet.setSortKey(sortReadValue); SimpleClass returnedItem = table.getItem(itemToGet); // Demonstrate we get the expected item back assert returnedItem.getPartitionKey().equals("PlaintextMigrationExample"); assert returnedItem.getAttribute1().equals("this will be encrypted and signed"); } public static void main(final String[] args) { if (args.length <= 1) { throw new IllegalArgumentException("To run this example, include the ddbTableName and sortReadValue as args."); } final String ddbTableName = args[0]; // You can manipulate this value to demonstrate reading records written in other steps final int sortReadValue = Integer.parseInt(args[1]); MigrationStep0(ddbTableName, sortReadValue); } }
5,293
0
Create_ds/aws-database-encryption-sdk-dynamodb-java/Examples/runtimes/java/Migration/PlaintextToAWSDBE/src/main/java/software/amazon/cryptography/examples
Create_ds/aws-database-encryption-sdk-dynamodb-java/Examples/runtimes/java/Migration/PlaintextToAWSDBE/src/main/java/software/amazon/cryptography/examples/awsdbe/SimpleClass.java
package software.amazon.cryptography.examples.awsdbe; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbAttribute; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbBean; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbPartitionKey; import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbSortKey; import software.amazon.cryptography.dbencryptionsdk.dynamodb.enhancedclient.DynamoDbEncryptionDoNothing; import software.amazon.cryptography.dbencryptionsdk.dynamodb.enhancedclient.DynamoDbEncryptionSignOnly; /** * This class is used by the Enhanced Client Tests */ @DynamoDbBean public class SimpleClass { private String partitionKey; private int sortKey; private String attribute1; private String attribute2; private String attribute3; @DynamoDbPartitionKey @DynamoDbAttribute(value = "partition_key") public String getPartitionKey() { return this.partitionKey; } public void setPartitionKey(String partitionKey) { this.partitionKey = partitionKey; } @DynamoDbSortKey @DynamoDbAttribute(value = "sort_key") public int getSortKey() { return this.sortKey; } public void setSortKey(int sortKey) { this.sortKey = sortKey; } @DynamoDbAttribute(value = "attribute1") public String getAttribute1() { return this.attribute1; } public void setAttribute1(String attribute1) { this.attribute1 = attribute1; } @DynamoDbEncryptionSignOnly @DynamoDbAttribute(value = "attribute2") public String getAttribute2() { return this.attribute2; } public void setAttribute2(String attribute2) { this.attribute2 = attribute2; } @DynamoDbEncryptionDoNothing @DynamoDbAttribute(value = "attribute3") public String getAttribute3() { return this.attribute3; } public void setAttribute3(String attribute3) { this.attribute3 = attribute3; } }
5,294
0
Create_ds/aws-database-encryption-sdk-dynamodb-java/Examples/runtimes/java/Migration/PlaintextToAWSDBE/src/main/java/software/amazon/cryptography/examples
Create_ds/aws-database-encryption-sdk-dynamodb-java/Examples/runtimes/java/Migration/PlaintextToAWSDBE/src/main/java/software/amazon/cryptography/examples/awsdbe/MigrationExampleStep3.java
package software.amazon.cryptography.examples.awsdbe; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import software.amazon.awssdk.core.client.config.ClientOverrideConfiguration; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClient; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbTable; import software.amazon.awssdk.enhanced.dynamodb.TableSchema; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.dynamodb.DynamoDbClient; import software.amazon.cryptography.materialproviders.IKeyring; import software.amazon.cryptography.materialproviders.MaterialProviders; import software.amazon.cryptography.materialproviders.model.CreateAwsKmsMrkMultiKeyringInput; import software.amazon.cryptography.materialproviders.model.MaterialProvidersConfig; import software.amazon.cryptography.dbencryptionsdk.dynamodb.DynamoDbEncryptionInterceptor; import software.amazon.cryptography.dbencryptionsdk.dynamodb.enhancedclient.CreateDynamoDbEncryptionInterceptorInput; import software.amazon.cryptography.dbencryptionsdk.dynamodb.enhancedclient.DynamoDbEnhancedClientEncryption; import software.amazon.cryptography.dbencryptionsdk.dynamodb.enhancedclient.DynamoDbEnhancedTableEncryptionConfig; /* Migration Step 3: This is an example demonstrating how to update your configuration to stop accepting reading plaintext items. Once you complete Step 3, all items being read by your system are encrypted. Before you move onto this step, you will need to encrypt all plaintext items in your dataset. How you will want to do this depends on your system. Running this example requires access to the DDB Table whose name is provided in CLI arguments. This table must be configured with the following primary key configuration: - Partition key is named "partition_key" with type (S) - Sort key is named "sort_key" with type (S) */ public class MigrationExampleStep3 { public static void MigrationStep3(String kmsKeyId, String ddbTableName, int sortReadValue) { // 1. Create a Keyring. This Keyring will be responsible for protecting the data keys that protect your data. // We will use the `CreateMrkMultiKeyring` method to create this keyring, // as it will correctly handle both single region and Multi-Region KMS Keys. MaterialProviders matProv = MaterialProviders.builder() .MaterialProvidersConfig(MaterialProvidersConfig.builder().build()) .build(); final CreateAwsKmsMrkMultiKeyringInput keyringInput = CreateAwsKmsMrkMultiKeyringInput.builder() .generator(kmsKeyId) .build(); final IKeyring kmsKeyring = matProv.CreateAwsKmsMrkMultiKeyring(keyringInput); // 2. Create a Table Schema over your annotated class. // This uses the same annotated class as Step 2, which MUST be deployed to all hosts // before deploying Step 2. final TableSchema<SimpleClass> tableSchema = TableSchema.fromBean(SimpleClass.class); // 3. Configure which attributes we expect to be excluded in the signature // when reading items. This value MUST be the same as in Steps 1 and 2. final List<String> unsignedAttributes = Arrays.asList("attribute3"); // 4. Create encryption configuration for table. // Do not specify a plaintext override. Unspecified plaintext override defaults to // `FORBID_PLAINTEXT_WRITE_FORBID_PLAINTEXT_READ`, which is the desired behavior // for a client interacting with a fully encrypted database. Map<String, DynamoDbEnhancedTableEncryptionConfig> tableConfigs = new HashMap<>(); tableConfigs.put(ddbTableName, DynamoDbEnhancedTableEncryptionConfig.builder() .logicalTableName(ddbTableName) .keyring(kmsKeyring) .schemaOnEncrypt(tableSchema) .allowedUnsignedAttributes(unsignedAttributes) .build()); // 5. Create DynamoDbEncryptionInterceptor using the above config DynamoDbEncryptionInterceptor interceptor = DynamoDbEnhancedClientEncryption.CreateDynamoDbEncryptionInterceptor( CreateDynamoDbEncryptionInterceptorInput.builder() .tableEncryptionConfigs(tableConfigs) .build()); // 6. Create the EnhancedClient using the interceptor, and create a table from the schema DynamoDbClient ddb = DynamoDbClient.builder() .region(Region.US_WEST_2) .overrideConfiguration( ClientOverrideConfiguration.builder() .addExecutionInterceptor(interceptor) .build()) .build(); DynamoDbEnhancedClient enhancedClient = DynamoDbEnhancedClient.builder() .dynamoDbClient(ddb) .build(); final DynamoDbTable<SimpleClass> table = enhancedClient.table(ddbTableName, tableSchema); // 7. Put an item into your table using the DynamoDb Enhanced Client. // This item will be encrypted. final SimpleClass item = new SimpleClass(); item.setPartitionKey("PlaintextMigrationExample"); item.setSortKey(3); item.setAttribute1("this will be encrypted and signed"); item.setAttribute3("this will never be encrypted nor signed"); item.setAttribute2("this will never be encrypted, but it will be signed"); table.putItem(item); // 8. Get an item back from the table using the DynamoDb Enhanced Client. // If this is an item written in plaintext (i.e. any item written // during Step 0 or 1), then the read will fail, as we have // configured our client to forbid reading plaintext items. // If this is an item that was encrypted client-side (i.e. any item written // during Step 2 or after), then the item will be decrypted client-side // and surfaced as a plaintext item. SimpleClass itemToGet = new SimpleClass(); itemToGet.setPartitionKey("PlaintextMigrationExample"); itemToGet.setSortKey(sortReadValue); SimpleClass returnedItem = table.getItem(itemToGet); // Demonstrate we get the expected item back assert returnedItem.getPartitionKey().equals("PlaintextMigrationExample"); assert returnedItem.getAttribute1().equals("this will be encrypted and signed"); } public static void main(final String[] args) { if (args.length < 3) { throw new IllegalArgumentException("To run this example, include the kmsKeyId, ddbTableName, and sortReadValue as args."); } final String kmsKeyId = args[0]; final String ddbTableName = args[1]; // You can manipulate this value to demonstrate reading records written in other steps final int sortReadValue = Integer.parseInt(args[2]); MigrationStep3(kmsKeyId, ddbTableName, sortReadValue); } }
5,295
0
Create_ds/aws-database-encryption-sdk-dynamodb-java/Examples/runtimes/java/Migration/PlaintextToAWSDBE/src/main/java/software/amazon/cryptography/examples
Create_ds/aws-database-encryption-sdk-dynamodb-java/Examples/runtimes/java/Migration/PlaintextToAWSDBE/src/main/java/software/amazon/cryptography/examples/awsdbe/MigrationExampleStep2.java
package software.amazon.cryptography.examples.awsdbe; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import software.amazon.awssdk.core.client.config.ClientOverrideConfiguration; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClient; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbTable; import software.amazon.awssdk.enhanced.dynamodb.TableSchema; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.dynamodb.DynamoDbClient; import software.amazon.cryptography.dbencryptionsdk.dynamodb.model.PlaintextOverride; import software.amazon.cryptography.materialproviders.IKeyring; import software.amazon.cryptography.materialproviders.MaterialProviders; import software.amazon.cryptography.materialproviders.model.CreateAwsKmsMrkMultiKeyringInput; import software.amazon.cryptography.materialproviders.model.MaterialProvidersConfig; import software.amazon.cryptography.dbencryptionsdk.dynamodb.DynamoDbEncryptionInterceptor; import software.amazon.cryptography.dbencryptionsdk.dynamodb.enhancedclient.CreateDynamoDbEncryptionInterceptorInput; import software.amazon.cryptography.dbencryptionsdk.dynamodb.enhancedclient.DynamoDbEnhancedClientEncryption; import software.amazon.cryptography.dbencryptionsdk.dynamodb.enhancedclient.DynamoDbEnhancedTableEncryptionConfig; /* Migration Step 2: This is an example demonstrating how to update your configuration to start writing encrypted items, but still continue to read any plaintext or encrypted items. Once you deploy this change to your system, you will have a dataset containing both encrypted and plaintext items. Because the changes in Step 1 have been deployed to all our readers, we can be sure that our entire system is ready to read this new data. Before you move onto the next step, you will need to encrypt all plaintext items in your dataset. How you will want to do this depends on your system. Running this example requires access to the DDB Table whose name is provided in CLI arguments. This table must be configured with the following primary key configuration: - Partition key is named "partition_key" with type (S) - Sort key is named "sort_key" with type (S) */ public class MigrationExampleStep2 { public static void MigrationStep2(String kmsKeyId, String ddbTableName, int sortReadValue) { // 1. Continue to configure your Keyring, Table Schema, legacy attribute actions, // and allowedUnsignedAttributes, and old DynamoDBEncryptor as you did in Step 1. MaterialProviders matProv = MaterialProviders.builder() .MaterialProvidersConfig(MaterialProvidersConfig.builder().build()) .build(); final CreateAwsKmsMrkMultiKeyringInput keyringInput = CreateAwsKmsMrkMultiKeyringInput.builder() .generator(kmsKeyId) .build(); final IKeyring kmsKeyring = matProv.CreateAwsKmsMrkMultiKeyring(keyringInput); final TableSchema<SimpleClass> tableSchema = TableSchema.fromBean(SimpleClass.class); final List<String> unsignedAttributes = Arrays.asList("attribute3"); // 2. When creating encryption configuration for your table, // you must use the plaintext override `FORBID_PLAINTEXT_WRITE_ALLOW_PLAINTEXT_READ`. // This plaintext override means: // - Write: Items are forbidden to be written as plaintext. // Items will be written as encrypted items. // - Read: Items are allowed to be read as plaintext. // Items are allowed to be read as encrypted items. Map<String, DynamoDbEnhancedTableEncryptionConfig> tableConfigs = new HashMap<>(); tableConfigs.put(ddbTableName, DynamoDbEnhancedTableEncryptionConfig.builder() .logicalTableName(ddbTableName) .keyring(kmsKeyring) .schemaOnEncrypt(tableSchema) .allowedUnsignedAttributes(unsignedAttributes) // Update plaintext override here .plaintextOverride(PlaintextOverride.FORBID_PLAINTEXT_WRITE_ALLOW_PLAINTEXT_READ) .build()); // 3. Create DynamoDbEncryptionInterceptor using the above config DynamoDbEncryptionInterceptor interceptor = DynamoDbEnhancedClientEncryption.CreateDynamoDbEncryptionInterceptor( CreateDynamoDbEncryptionInterceptorInput.builder() .tableEncryptionConfigs(tableConfigs) .build()); // 4. Create the EnhancedClient using the interceptor, and create a table from the schema DynamoDbClient ddb = DynamoDbClient.builder() .region(Region.US_WEST_2) .overrideConfiguration( ClientOverrideConfiguration.builder() .addExecutionInterceptor(interceptor) .build()) .build(); DynamoDbEnhancedClient enhancedClient = DynamoDbEnhancedClient.builder() .dynamoDbClient(ddb) .build(); final DynamoDbTable<SimpleClass> table = enhancedClient.table(ddbTableName, tableSchema); // 5. Put an item into your table using the DynamoDb Enhanced Client. // This item will be encrypted. final SimpleClass item = new SimpleClass(); item.setPartitionKey("PlaintextMigrationExample"); item.setSortKey(2); item.setAttribute1("this will be encrypted and signed"); item.setAttribute3("this will never be encrypted nor signed"); item.setAttribute2("this will never be encrypted, but it will be signed"); table.putItem(item); // 8. Get an item back from the table using the DynamoDb Enhanced Client. // If this is an item written in plaintext (i.e. any item written // during Step 0 or 1), then the item will still be in plaintext. // If this is an item that was encrypted client-side (i.e. any item written // during Step 2 or after), then the DDB enhanced client will decrypt the // item client-sid and surface it in our code as a plaintext item. SimpleClass itemToGet = new SimpleClass(); itemToGet.setPartitionKey("PlaintextMigrationExample"); itemToGet.setSortKey(sortReadValue); SimpleClass returnedItem = table.getItem(itemToGet); // Demonstrate we get the expected item back assert returnedItem.getPartitionKey().equals("PlaintextMigrationExample"); assert returnedItem.getAttribute1().equals("this will be encrypted and signed"); } public static void main(final String[] args) { if (args.length < 3) { throw new IllegalArgumentException("To run this example, include the kmsKeyId, ddbTableName, and sortReadValue as args."); } final String kmsKeyId = args[0]; final String ddbTableName = args[1]; // You can manipulate this value to demonstrate reading records written in other steps final int sortReadValue = Integer.parseInt(args[2]); MigrationStep2(kmsKeyId, ddbTableName, sortReadValue); } }
5,296
0
Create_ds/aws-database-encryption-sdk-dynamodb-java/Examples/runtimes/java/Migration/PlaintextToAWSDBE/src/main/java/software/amazon/cryptography/examples
Create_ds/aws-database-encryption-sdk-dynamodb-java/Examples/runtimes/java/Migration/PlaintextToAWSDBE/src/main/java/software/amazon/cryptography/examples/awsdbe/MigrationExampleStep1.java
package software.amazon.cryptography.examples.awsdbe; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import software.amazon.awssdk.core.client.config.ClientOverrideConfiguration; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClient; import software.amazon.awssdk.enhanced.dynamodb.DynamoDbTable; import software.amazon.awssdk.enhanced.dynamodb.TableSchema; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.dynamodb.DynamoDbClient; import software.amazon.cryptography.dbencryptionsdk.dynamodb.model.PlaintextOverride; import software.amazon.cryptography.materialproviders.IKeyring; import software.amazon.cryptography.materialproviders.MaterialProviders; import software.amazon.cryptography.materialproviders.model.CreateAwsKmsMrkMultiKeyringInput; import software.amazon.cryptography.materialproviders.model.MaterialProvidersConfig; import software.amazon.cryptography.dbencryptionsdk.dynamodb.DynamoDbEncryptionInterceptor; import software.amazon.cryptography.dbencryptionsdk.dynamodb.enhancedclient.CreateDynamoDbEncryptionInterceptorInput; import software.amazon.cryptography.dbencryptionsdk.dynamodb.enhancedclient.DynamoDbEnhancedClientEncryption; import software.amazon.cryptography.dbencryptionsdk.dynamodb.enhancedclient.DynamoDbEnhancedTableEncryptionConfig; /* Migration Step 1: This is an example demonstrating how to start using the AWS Database Encryption SDK with a pre-existing table with plaintext items. In this example, we configure a DynamoDb Encryption Interceptor to do the following: - Write items only in plaintext - Read items in plaintext or, if the item is encrypted, decrypt with our encryption configuration While this step configures your client to be ready to start reading encrypted items, we do not yet expect to be reading any encrypted items, as our client still writes plaintext items. Before you move on to step 2, ensure that these changes have successfully been deployed to all of your readers. Running this example requires access to the DDB Table whose name is provided in CLI arguments. This table must be configured with the following primary key configuration: - Partition key is named "partition_key" with type (S) - Sort key is named "sort_key" with type (S) */ public class MigrationExampleStep1 { public static void MigrationStep1(String kmsKeyId, String ddbTableName, int sortReadValue) { // 1. Create a Keyring. This Keyring will be responsible for protecting the data keys that protect your data. // We will use the `CreateMrkMultiKeyring` method to create this keyring, // as it will correctly handle both single region and Multi-Region KMS Keys. // // Note that while we still are not writing encrypted items, // and our key will not be used to encrypt items in this example, // our configuration specifies that we may read encrypted items, // and we should expect to be able to decrypt and process any encrypted items. // To that end, we must fully define our encryption configuration in // this step. MaterialProviders matProv = MaterialProviders.builder() .MaterialProvidersConfig(MaterialProvidersConfig.builder().build()) .build(); final CreateAwsKmsMrkMultiKeyringInput keyringInput = CreateAwsKmsMrkMultiKeyringInput.builder() .generator(kmsKeyId) .build(); final IKeyring kmsKeyring = matProv.CreateAwsKmsMrkMultiKeyring(keyringInput); // 2. Create a Table Schema over your annotated class. // See SimpleClass.java in this directory for the update to use the new DynamoDb Enhanced Client annotations. // All primary key attributes will be signed but not encrypted (SIGN_ONLY) // and by default all non-primary key attributes will be encrypted and signed (ENCRYPT_AND_SIGN). // If you want a particular non-primary key attribute to be signed but not encrypted, // use the `DynamoDbEncryptionSignOnly` annotation. // If you want a particular attribute to be neither signed nor encrypted (DO_NOTHING), // use the `DynamoDbEncryptionDoNothing` annotation. final TableSchema<SimpleClass> tableSchema = TableSchema.fromBean(SimpleClass.class); // 3. Configure which attributes we expect to be excluded in the signature // when reading items. This value represents all unsigned attributes // across our entire dataset. If you ever want to add new unsigned attributes // in the future, you must make an update to this field to all your readers // before deploying any change to start writing that new data. It is not safe // to remove attributes from this field. final List<String> unsignedAttributes = Arrays.asList("attribute3"); // 4. Create encryption configuration for table. // Again, while we are not writing encrypted items, // we should expect to be able to read encrypted items. Map<String, DynamoDbEnhancedTableEncryptionConfig> tableConfigs = new HashMap<>(); tableConfigs.put(ddbTableName, DynamoDbEnhancedTableEncryptionConfig.builder() .logicalTableName(ddbTableName) .keyring(kmsKeyring) .schemaOnEncrypt(tableSchema) .allowedUnsignedAttributes(unsignedAttributes) // This plaintext override means: // - Write: Items are forced to be written as plaintext. // Items may not be written as encrypted items. // - Read: Items are allowed to be read as plaintext. // Items are allowed to be read as encrypted items. .plaintextOverride(PlaintextOverride.FORCE_PLAINTEXT_WRITE_ALLOW_PLAINTEXT_READ) .build()); // 5. Create DynamoDbEncryptionInterceptor using the table config DynamoDbEncryptionInterceptor interceptor = DynamoDbEnhancedClientEncryption.CreateDynamoDbEncryptionInterceptor( CreateDynamoDbEncryptionInterceptorInput.builder() .tableEncryptionConfigs(tableConfigs) .build()); // 6. Create the EnhancedClient using the interceptor, and create a table from the schema DynamoDbClient ddb = DynamoDbClient.builder() .region(Region.US_WEST_2) .overrideConfiguration( ClientOverrideConfiguration.builder() .addExecutionInterceptor(interceptor) .build()) .build(); DynamoDbEnhancedClient enhancedClient = DynamoDbEnhancedClient.builder() .dynamoDbClient(ddb) .build(); final DynamoDbTable<SimpleClass> table = enhancedClient.table(ddbTableName, tableSchema); // 7. Put an item into your table using the DynamoDb Enhanced Client. // This item will be stored in plaintext. final SimpleClass item = new SimpleClass(); item.setPartitionKey("PlaintextMigrationExample"); item.setSortKey(1); item.setAttribute1("this will be encrypted and signed"); item.setAttribute3("this will never be encrypted nor signed"); item.setAttribute2("this will never be encrypted, but it will be signed"); table.putItem(item); // 8. Get an item back from the table using the DynamoDb Enhanced Client. // If this is an item written in plaintext (i.e. any item written // during Step 0 or 1), then the item will still be in plaintext. // If this is an item that was encrypted client-side (i.e. any item written // during Step 2 or after), then the item will be decrypted client-side // and surfaced as a plaintext item. SimpleClass itemToGet = new SimpleClass(); itemToGet.setPartitionKey("PlaintextMigrationExample"); itemToGet.setSortKey(sortReadValue); SimpleClass returnedItem = table.getItem(itemToGet); // Demonstrate we get the expected item back assert returnedItem.getPartitionKey().equals("PlaintextMigrationExample"); assert returnedItem.getAttribute1().equals("this will be encrypted and signed"); } public static void main(final String[] args) { if (args.length < 3) { throw new IllegalArgumentException("To run this example, include the kmsKeyId, ddbTableName, and sortReadValue as args."); } final String kmsKeyId = args[0]; final String ddbTableName = args[1]; // You can manipulate this value to demonstrate reading records written in other steps final int sortReadValue = Integer.parseInt(args[2]); MigrationStep1(kmsKeyId, ddbTableName, sortReadValue); } }
5,297
0
Create_ds/aws-database-encryption-sdk-dynamodb-java/TestVectors/runtimes/java/src/main/java
Create_ds/aws-database-encryption-sdk-dynamodb-java/TestVectors/runtimes/java/src/main/java/CreateInterceptedDDBClient_Compile/__default.java
package CreateInterceptedDDBClient_Compile; import software.amazon.cryptography.services.dynamodb.internaldafny.Shim; import Wrappers_Compile.Result; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.regions.providers.DefaultAwsRegionProviderChain; import software.amazon.cryptography.dbencryptionsdk.dynamodb.ToDafny; import software.amazon.cryptography.dbencryptionsdk.dynamodb.ToNative; import software.amazon.cryptography.dbencryptionsdk.dynamodb.model.DynamoDbTablesEncryptionConfig; import software.amazon.cryptography.dbencryptionsdk.dynamodb.DynamoDbEncryptionInterceptor; import software.amazon.awssdk.services.dynamodb.DynamoDbClient; import software.amazon.awssdk.core.client.config.ClientOverrideConfiguration; import java.net.URI; public class __default { public static Wrappers_Compile.Result< software.amazon.cryptography.services.dynamodb.internaldafny.types.IDynamoDBClient, software.amazon.cryptography.dbencryptionsdk.dynamodb.internaldafny.types.Error > CreateInterceptedDDBClient( software.amazon.cryptography.dbencryptionsdk.dynamodb.internaldafny.types.DynamoDbTablesEncryptionConfig config ) { try { final DynamoDbTablesEncryptionConfig nativeConfig = ToNative.DynamoDbTablesEncryptionConfig(config); DynamoDbEncryptionInterceptor encryptionInterceptor = DynamoDbEncryptionInterceptor.builder() .config(nativeConfig) .build(); final Region region = new DefaultAwsRegionProviderChain().getRegion(); final DynamoDbClient ddb = DynamoDbClient.builder() .endpointOverride(URI.create("http://localhost:8000")) .overrideConfiguration( ClientOverrideConfiguration.builder() .addExecutionInterceptor(encryptionInterceptor) .build()) .build(); final Shim wrappedClient = new Shim(ddb, region.toString()); return Result.create_Success(wrappedClient); } catch (Exception e) { return Result.create_Failure(ToDafny.Error((RuntimeException)e)); } } public static Wrappers_Compile.Result< software.amazon.cryptography.services.dynamodb.internaldafny.types.IDynamoDBClient, software.amazon.cryptography.dbencryptionsdk.dynamodb.internaldafny.types.Error > CreateVanillaDDBClient() { try { final Region region = new DefaultAwsRegionProviderChain().getRegion(); final DynamoDbClient ddb = DynamoDbClient.builder() .endpointOverride(URI.create("http://localhost:8000")) .build(); final Shim wrappedClient = new Shim(ddb, region.toString()); return Result.create_Success(wrappedClient); } catch (Exception e) { return Result.create_Failure(ToDafny.Error((RuntimeException)e)); } } }
5,298
0
Create_ds/aws-database-encryption-sdk-dynamodb-java/TestVectors/runtimes/java/src/main/java/software/amazon/cryptography/dbencryptionsdk/dynamodb/internaldafny
Create_ds/aws-database-encryption-sdk-dynamodb-java/TestVectors/runtimes/java/src/main/java/software/amazon/cryptography/dbencryptionsdk/dynamodb/internaldafny/wrapped/__default.java
package software.amazon.cryptography.dbencryptionsdk.dynamodb.internaldafny.wrapped; import software.amazon.cryptography.dbencryptionsdk.dynamodb.internaldafny.types.Error; import software.amazon.cryptography.dbencryptionsdk.dynamodb.internaldafny.types.IDynamoDbEncryptionClient; import software.amazon.cryptography.dbencryptionsdk.dynamodb.internaldafny.types.DynamoDbEncryptionConfig; import Wrappers_Compile.Result; import software.amazon.cryptography.dbencryptionsdk.dynamodb.ToNative; import software.amazon.cryptography.dbencryptionsdk.dynamodb.DynamoDbEncryption; import software.amazon.cryptography.dbencryptionsdk.dynamodb.wrapped.TestDynamoDbEncryption; import software.amazon.cryptography.materialproviders.internaldafny.wrapped._ExternBase___default; public class __default extends _ExternBase___default { public static Result<IDynamoDbEncryptionClient, Error> WrappedDynamoDbEncryption(DynamoDbEncryptionConfig config) { software.amazon.cryptography.dbencryptionsdk.dynamodb.model.DynamoDbEncryptionConfig wrappedConfig = ToNative.DynamoDbEncryptionConfig(config); software.amazon.cryptography.dbencryptionsdk.dynamodb.DynamoDbEncryption impl = DynamoDbEncryption.builder().DynamoDbEncryptionConfig(wrappedConfig).build(); TestDynamoDbEncryption wrappedClient = TestDynamoDbEncryption.builder().impl(impl).build(); return Result.create_Success(wrappedClient); } }
5,299