

本文為英文版的機器翻譯版本，如內容有任何歧義或不一致之處，概以英文版為準。

# 適用於 Java 的 DynamoDB 加密用戶端的範例程式碼
<a name="java-examples"></a>

**注意**  
我們的用戶端加密程式庫已[重新命名為 AWS 資料庫加密 SDK](DDBEC-rename.md)。下列主題提供有關適用於 Java 的 DynamoDB 加密用戶端 1.*x*-2.*x* 版和適用於 Python 的 DynamoDB 加密用戶端 1.*x*-3.*x* 版的資訊。如需詳細資訊，請參閱[AWS 資料庫加密 SDK for DynamoDB 版本支援](legacy-dynamodb-encryption-client.md#legacy-support)。

下列範例示範如何使用適用於 Java 的 DynamoDB 加密用戶端來保護應用程式中的 DynamoDB 資料表項目。您可以在 GitHub 上 [aws-database-encryption-sdk-dynamodb](https://github.com/aws/aws-database-encryption-sdk-dynamodb/) 儲存庫[的範例](https://github.com/aws/aws-database-encryption-sdk-dynamodb/blob/main/Examples/runtimes/java/DDBECwithSDKV2/src/main/java/)目錄中找到更多範例 （並自行提供）。

**Topics**
+ [使用 DynamoDBEncryptor](#java-example-ddb-encryptor)

## 使用 DynamoDBEncryptor
<a name="java-example-ddb-encryptor"></a>

這個範例說明如何使用較低層級的 [DynamoDBEncryptor](https://aws.github.io/aws-database-encryption-sdk-dynamodb/com/amazonaws/services/dynamodbv2/datamodeling/sdkv2/encryption/DynamoDBEncryptor.html) 搭配[直接 KMS 提供者](direct-kms-provider.md)。Direct KMS 提供者會在您指定的 [AWS KMS key](https://docs.aws.amazon.com/kms/latest/developerguide/concepts.html#master_keys) in AWS Key Management Service (AWS KMS) 下產生並保護其密碼編譯資料。

您可以搭配 使用任何相容的[密碼編譯資料提供者](DDBEC-legacy-concepts.md#concept-material-provider) (CMP)`DynamoDBEncryptor`。

**查看完整的程式碼範例**：[AwsKmsEncryptedItem.java](https://github.com/aws/aws-database-encryption-sdk-dynamodb/blob/main/Examples/runtimes/java/DDBECwithSDKV2/src/main/java/AwsKmsEncryptedItem.java)

步驟 1：建立直接 KMS 提供者  
建立具有指定區域的 AWS KMS 用戶端執行個體。然後，使用用戶端執行個體，使用您偏好的 建立 Direct KMS 提供者的執行個體 AWS KMS key。  
此範例使用 Amazon Resource Name (ARN) 來識別 AWS KMS key，但您可以使用[任何有效的金鑰識別符](https://docs.aws.amazon.com/kms/latest/developerguide/viewing-keys.html#find-cmk-id-arn)。  

```
final String keyArn = "arn:aws:kms:us-west-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab";
final String region = "us-west-2";

final KmsClient kms = KmsClient.builder().region(Region.of({{region}})).build();
final DirectKmsMaterialProvider cmp = new DirectKmsMaterialProvider(kms, {{keyArn}});
```

步驟 2：建立項目  
這個範例會定義 `record` HashMap，其代表範例資料表項目。  

```
final String partitionKeyName = "partition_attribute";
final String sortKeyName = "sort_attribute";

final Map<String, AttributeValue> record = new HashMap<>();
record.put(partitionKeyName, new AttributeValue().withS("value1"));
record.put(sortKeyName, new AttributeValue().withN("55"));
record.put("example", new AttributeValue().withS("data"));
record.put("numbers", new AttributeValue().withN("99"));
record.put("binary", new AttributeValue().withB(ByteBuffer.wrap(new byte[]{0x00, 0x01, 0x02})));
record.put("test", new AttributeValue().withS("test-value"));
```

步驟 3：建立 DynamoDBEncryptor  
使用直接 KMS 提供者建立 `DynamoDBEncryptor` 的執行個體。  

```
final DynamoDBEncryptor encryptor = DynamoDBEncryptor.getInstance(cmp);
```

步驟 4：建立 DynamoDB 加密內容  
[DynamoDB 加密內容](concepts.md#encryption-context)包含資料表結構及其加密和簽署方式的相關資訊。  

```
final String tableName = "testTable";

final EncryptionContext encryptionContext = new EncryptionContext.Builder()
    .withTableName(tableName)
    .withHashKeyName(partitionKeyName)
    .withRangeKeyName(sortKeyName)
    .build();
```

步驟 5：建立屬性動作物件  
[屬性動作](DDBEC-legacy-concepts.md#legacy-attribute-actions)決定項目的哪些屬性會加密並簽署，哪些屬性只會簽署，以及哪些屬性不會加密或簽署。  
在 Java 中，若要指定屬性動作，您可建立屬性名稱和 `EncryptionFlags` 值組的 HashMap。  
例如，下列 Java 程式碼會建立 `actions` HashMap，其可加密並簽署 `record` 項目中的所有屬性，但是分割區索引鍵與排序索引鍵屬性 (簽署但不加密) 以及 `test` 屬性 (不簽署或加密) 除外。  

```
final EnumSet<EncryptionFlags> signOnly = EnumSet.of(EncryptionFlags.SIGN);
final EnumSet<EncryptionFlags> encryptAndSign = EnumSet.of(EncryptionFlags.ENCRYPT, EncryptionFlags.SIGN);
final Map<String, Set<EncryptionFlags>> actions = new HashMap<>();

for (final String attributeName : record.keySet()) {
  switch (attributeName) {
    case partitionKeyName: // fall through to the next case
    case sortKeyName:
      // Partition and sort keys must not be encrypted, but should be signed
      actions.put(attributeName, signOnly);
      break;
    case "test":
      // Neither encrypted nor signed
      break;
    default:
      // Encrypt and sign all other attributes
      actions.put(attributeName, encryptAndSign);
      break;
  }
}
```

步驟 6：將項目加密並簽署  
若要加密並簽署資料表項目，請在 `encryptRecord` 的執行個體上呼叫 `DynamoDBEncryptor` 方法。指定資料表項目 (`record`)、屬性動作 (`actions`) 及加密細節 (`encryptionContext`)。  

```
final Map<String, AttributeValue> encrypted_record = encryptor.encryptRecord(record, actions, encryptionContext);
```

步驟 7：將項目放在 DynamoDB 資料表中  
最後，將加密和簽署的項目放入 DynamoDB 資料表。  

```
final DynamoDbClient ddb = DynamoDbClient.builder().region(Region.of(region)).build();
ddb.putItem(tableName, encrypted_record);
```