

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

# AWS KMS keyring
<a name="use-kms-keyring"></a>

 AWS KMS keyring 使用 [AWS KMS keys](https://docs.aws.amazon.com/kms/latest/developerguide/concepts.html#master_keys) 來產生、加密和解密資料金鑰。 AWS Key Management Service (AWS KMS) 會保護您的 KMS 金鑰，並在 FIPS 邊界內執行密碼編譯操作。我們建議您盡可能使用 AWS KMS keyring 或具有類似安全屬性的 keyring。

支援 keyring 的所有程式設計語言實作都支援使用對稱加密 KMS 金鑰的 AWS KMS keyring。下列程式設計語言實作也支援使用非對稱 RSA KMS 金鑰的 AWS KMS keyring：
+ 3.*x* 版 適用於 JAVA 的 AWS Encryption SDK
+ AWS Encryption SDK 適用於 .NET 的 4.*x* 版和更新版本
+ 4.*x* 版 適用於 Python 的 AWS Encryption SDK，與選用[的加密材料提供者程式庫](https://github.com/aws/aws-cryptographic-material-providers-library) (MPL) 相依性搭配使用時。
+ for Rust 的 1.*x* AWS Encryption SDK 版
+ 適用於 Go 的 0.1.*x* AWS Encryption SDK 版或更新版本

如果您嘗試在任何其他語言實作的加密 keyring 中包含非對稱 KMS 金鑰，加密呼叫會失敗。如果您在解密 keyring 中包含它，則會予以忽略。

您可以在 AWS KMS keyring 或主金鑰提供者中使用 AWS KMS 多區域金鑰，從 的 [2.3.*x* 版](about-versions.md#version2.3) AWS Encryption SDK 和 AWS 加密 CLI 的 3.0.*x* 版開始。如需使用multi-Region-aware符號的詳細資訊和範例，請參閱 [使用多區域 AWS KMS keys](configure.md#config-mrks)。如需多區域金鑰的相關資訊，請參閱《 *AWS Key Management Service 開發人員指南*》中的[使用多區域金鑰](https://docs.aws.amazon.com/kms/latest/developerguide/multi-region-keys-overview.html)。

**注意**  
中 AWS Encryption SDK 所有提及的 *KMS keyring *都參考 AWS KMS keyring。

AWS KMS keyring 可以包含兩種類型的包裝金鑰：
+ **產生器金鑰**：產生純文字資料金鑰並將其加密。加密資料的 keyring 必須有一個產生器金鑰。
+ **其他金鑰**：加密產生器金鑰產生的純文字資料金鑰。 AWS KMS keyrings 可以有零個或多個其他金鑰。

使用 必須具有產生器金鑰才能加密訊息。當 AWS KMS keyring 只有一個 KMS 金鑰時，該金鑰會用來產生和加密資料金鑰。解密時，產生器金鑰是選用的，並且會忽略產生器金鑰和其他金鑰之間的差異。

與所有 keyring 一樣， AWS KMS keyring 可以獨立使用，也可以與相同或不同類型的其他 keyring [多重 keyring](use-multi-keyring.md)搭配使用。

**Topics**
+ [AWS KMS keyring 的必要許可](#kms-keyring-permissions)
+ [在 AWS KMS keyring AWS KMS keys 中識別](#kms-keyring-id)
+ [建立 AWS KMS keyring](#kms-keyring-encrypt)
+ [使用 AWS KMS 探索 keyring](#kms-keyring-discovery)
+ [使用 AWS KMS 區域探索 keyring](#kms-keyring-regional)

## AWS KMS keyring 的必要許可
<a name="kms-keyring-permissions"></a>

 AWS Encryption SDK 不需要 ， AWS 帳戶 也不依賴任何 AWS 服務。不過，若要使用 AWS KMS keyring，您需要 keyring AWS KMS keys 中 的 AWS 帳戶 和下列最低許可。
+ 若要使用 AWS KMS keyring 加密，您需要產生器金鑰上的 [kms:GenerateDataKey](https://docs.aws.amazon.com/kms/latest/APIReference/API_GenerateDataKey.html) 許可。您需要 AWS KMS keyring 中所有其他金鑰的 [kms:Encrypt](https://docs.aws.amazon.com/kms/latest/APIReference/API_Encrypt.html) 許可。
+ 若要使用 AWS KMS keyring 解密，您需要 AWS KMS keyring 中至少一個金鑰的 [kms:Decrypt](https://docs.aws.amazon.com/kms/latest/APIReference/API_Decrypt.html) 許可。
+ 若要使用由 AWS KMS keyring 組成的多 keyring 加密，您需要產生器 keyring 中產生器金鑰的 [kms:GenerateDataKey](https://docs.aws.amazon.com/kms/latest/APIReference/API_GenerateDataKey.html) 許可。您需要所有其他 AWS KMS keyring 中所有其他金鑰的 [kms:Encrypt](https://docs.aws.amazon.com/kms/latest/APIReference/API_Encrypt.html) 許可。
+ 若要使用非對稱 RSA AWS KMS keyring 加密，您不需要 [kms:GenerateDataKey](https://docs.aws.amazon.com/kms/latest/APIReference/API_GenerateDataKey.html) 或 [kms:Encrypt](https://docs.aws.amazon.com/kms/latest/APIReference/API_Encrypt.html)，因為您必須在建立 keyring 時指定要用於加密的公有金鑰材料。使用此 keyring 加密時不會進行任何 AWS KMS 呼叫。若要使用非對稱 RSA AWS KMS keyring 解密，您需要 [kms:Decrypt](https://docs.aws.amazon.com/kms/latest/APIReference/API_Decrypt.html) 許可。

如需 許可的詳細資訊 AWS KMS keys，請參閱《 *AWS Key Management Service 開發人員指南*》中的 [KMS 金鑰存取和許可](https://docs.aws.amazon.com/kms/latest/developerguide/control-access.html)。

## 在 AWS KMS keyring AWS KMS keys 中識別
<a name="kms-keyring-id"></a>

 AWS KMS keyring 可以包含一或多個 AWS KMS keys。若要在 AWS KMS keyring AWS KMS key 中指定 ，請使用支援的 AWS KMS 金鑰識別符。您可以用來識別 keyring AWS KMS key 中 的金鑰識別符會因 操作和語言實作而有所不同。如需 金鑰識別符的詳細資訊 AWS KMS key，請參閱《 *AWS Key Management Service 開發人員指南*》中的[金鑰識別符](https://docs.aws.amazon.com/kms/latest/developerguide/concepts.html#key-id)。

最佳實務是使用最適用於您任務的特定金鑰識別符。
+ 在 的加密 keyring 中 適用於 C 的 AWS Encryption SDK，您可以使用[金鑰 ARN](https://docs.aws.amazon.com/kms/latest/developerguide/concepts.html#key-id-key-ARN) 或[別名 ARN](https://docs.aws.amazon.com/kms/latest/developerguide/concepts.html#key-id-alias-ARN) 來識別 KMS 金鑰。在所有其他語言實作中，您可以使用[金鑰 ID](https://docs.aws.amazon.com/kms/latest/developerguide/concepts.html#key-id-key-id)、[金鑰 ARN](https://docs.aws.amazon.com/kms/latest/developerguide/concepts.html#key-id-key-ARN)、[別名名稱](https://docs.aws.amazon.com/kms/latest/developerguide/concepts.html#key-id-alias-name)或[別名 ARN](https://docs.aws.amazon.com/kms/latest/developerguide/concepts.html#key-id-alias-ARN) 來加密資料。
+ 在解密 keyring 中，您必須使用金鑰 ARN 來識別 AWS KMS keys。此要求適用於 AWS Encryption SDK的所有語言實作。如需詳細資訊，請參閱[選取包裝金鑰](configure.md#config-keys)。
+ 在用於加密和解密的 keyring 中，您必須使用金鑰 ARN 來識別 AWS KMS keys。此要求適用於 AWS Encryption SDK的所有語言實作。

如果您在加密 keyring 中指定 KMS 金鑰的別名名稱或別名 ARN，加密操作會將目前與別名相關聯的金鑰 ARN 儲存在加密資料金鑰的中繼資料中。它不會儲存別名。別名的變更不會影響用來解密加密資料金鑰的 KMS 金鑰。

## 建立 AWS KMS keyring
<a name="kms-keyring-encrypt"></a>

您可以使用相同 AWS KMS key 或不同 AWS 帳戶 和 AWS KMS keys 中的單一或多個 來設定每個 AWS KMS keyring AWS 區域。 AWS KMS keys 必須是對稱加密 KMS 金鑰 (SYMMETRIC\$1DEFAULT) 或非對稱 RSA KMS 金鑰。您也可以使用對稱加密[多區域 KMS 金鑰](configure.md#config-mrks)。您可以在多 AWS KMS keyring 中使用一或多個 keyring。 [多重 keyring](use-multi-keyring.md)

您可以建立加密和解密資料的 AWS KMS keyring，也可以建立專門用於加密或解密的 AWS KMS keyring。當您建立 AWS KMS keyring 來加密資料時，必須指定*產生器金鑰*，這是用來產生純文字資料金鑰並將其加密 AWS KMS key 的 。資料金鑰在數學上與 KMS 金鑰無關。然後，如果您選擇，您可以指定其他 AWS KMS keys 來加密相同的純文字資料金鑰。若要解密受此 keyring 保護的加密欄位，您使用的解密 keyring 必須包含至少一個在 keyring 中 AWS KMS keys 定義的 ，或否 AWS KMS keys。（沒有 的 AWS KMS keyring AWS KMS keys 稱為[AWS KMS 探索 keyring](#kms-keyring-discovery)。)

在 以外的 AWS Encryption SDK 語言實作中 適用於 C 的 AWS Encryption SDK，加密 keyring 或 multi-keyring 中的所有包裝金鑰都必須能夠加密資料金鑰。如果任何包裝金鑰無法加密，加密方法會失敗。因此，發起人必須擁有 keyring 中所有金鑰[的必要許可](#kms-keyring-permissions)。如果您使用探索 keyring 單獨加密資料或在多 keyring 中加密資料，加密操作會失敗。例外是 適用於 C 的 AWS Encryption SDK，其中加密操作會忽略標準探索 keyring，但如果您單獨或在多區域 keyring 中指定多區域探索 keyring，則會失敗。

下列範例會建立具有產生器金鑰和一個額外金鑰的 AWS KMS keyring。產生器金鑰和其他金鑰都是對稱加密 KMS 金鑰。這些範例使用[金鑰 ARNs](https://docs.aws.amazon.com/kms/latest/developerguide/concepts.html#key-id-key-ARN) 來識別 KMS 金鑰。這是用於加密的 AWS KMS keyring 的最佳實務，以及用於解密的 AWS KMS keyring 的需求。如需詳細資訊，請參閱[在 AWS KMS keyring AWS KMS keys 中識別](#kms-keyring-id)。

------
#### [ C ]

若要在 AWS KMS key 的加密 keyring 中識別 適用於 C 的 AWS Encryption SDK，請指定[金鑰 ARN](https://docs.aws.amazon.com/kms/latest/developerguide/concepts.html#key-id-key-ARN) 或[別名 ARN](https://docs.aws.amazon.com/kms/latest/developerguide/concepts.html#key-id-alias-arn)。在解密 Keyring 中，您必須使用金鑰 ARN。如需詳細資訊，請參閱[在 AWS KMS keyring AWS KMS keys 中識別](#kms-keyring-id)。

如需完整範例，請參閱 [string.cpp](https://github.com/aws/aws-encryption-sdk-c/blob/master/examples/string.cpp)。

```
const char * generator_key = "arn:aws:kms:us-west-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab"

const char * additional_key = "arn:aws:kms:us-west-2:111122223333:key/0987dcba-09fe-87dc-65ba-ab0987654321"    

struct aws_cryptosdk_keyring *kms_encrypt_keyring = 
       Aws::Cryptosdk::KmsKeyring::Builder().Build(generator_key,{additional_key});
```

------
#### [ C\$1 / .NET ]

若要在 AWS Encryption SDK 適用於 .NET 的 中建立具有一或多個 KMS 金鑰的 keyring，請使用 `CreateAwsKmsMultiKeyring()`方法。此範例使用兩個 AWS KMS 金鑰。若要指定一個 KMS 金鑰，請僅使用 `Generator` 參數。指定其他 KMS 金鑰的 `KmsKeyIds` 參數是選用的。

此 keyring 的輸入不會採用 AWS KMS 用戶端。相反地， 會針對 keyring 中 KMS 金鑰所代表的每個區域 AWS Encryption SDK 使用預設 AWS KMS 用戶端。例如，如果 參數值識別的 KMS 金鑰`Generator`位於美國西部 （奧勒岡） 區域 (`us-west-2`)，則 會為該`us-west-2`區域 AWS Encryption SDK 建立預設 AWS KMS 用戶端。如果您需要自訂用戶端 AWS KMS ，請使用 `CreateAwsKmsKeyring()`方法。

當您 AWS KMS key 在適用於 .NET AWS Encryption SDK 的 中為加密 keyring 指定 時，您可以使用任何有效的金鑰識別符：[金鑰 ID](https://docs.aws.amazon.com/kms/latest/developerguide/concepts.html#key-id-key-id)、[金鑰 ARN](https://docs.aws.amazon.com/kms/latest/developerguide/concepts.html#key-id-key-ARN)、[別名名稱](https://docs.aws.amazon.com/kms/latest/developerguide/concepts.html#key-id-alias-name)或[別名 ARN](https://docs.aws.amazon.com/kms/latest/developerguide/concepts.html#key-id-alias-arn)。如需在 AWS KMS keyring AWS KMS keys 中識別 的說明，請參閱 [在 AWS KMS keyring AWS KMS keys 中識別](#kms-keyring-id)。

下列範例使用 AWS Encryption SDK 適用於 .NET 的 4.*x* 版和 `CreateAwsKmsKeyring()`方法來自訂 AWS KMS 用戶端。

```
// Instantiate the AWS Encryption SDK and material providers
var esdk =  new ESDK(new AwsEncryptionSdkConfig());
var mpl = new MaterialProviders(new MaterialProvidersConfig());

string generatorKey = "arn:aws:kms:us-west-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab";
List<string> additionalKeys = new List<string> { "arn:aws:kms:us-west-2:111122223333:key/0987dcba-09fe-87dc-65ba-ab0987654321" };

// Instantiate the keyring input object
var createEncryptKeyringInput = new CreateAwsKmsMultiKeyringInput
{
    Generator = generatorKey,
    KmsKeyIds = additionalKeys
};

var kmsEncryptKeyring = mpl.CreateAwsKmsMultiKeyring(createEncryptKeyringInput);
```

------
#### [ JavaScript Browser ]

當您 AWS KMS key 在 中為加密 keyring 指定 時 適用於 JavaScript 的 AWS Encryption SDK，您可以使用任何有效的金鑰識別符：[金鑰 ID](https://docs.aws.amazon.com/kms/latest/developerguide/concepts.html#key-id-key-id)、[金鑰 ARN](https://docs.aws.amazon.com/kms/latest/developerguide/concepts.html#key-id-key-ARN)、[別名名稱](https://docs.aws.amazon.com/kms/latest/developerguide/concepts.html#key-id-alias-name)或[別名 ARN](https://docs.aws.amazon.com/kms/latest/developerguide/concepts.html#key-id-alias-arn)。如需在 AWS KMS keyring AWS KMS keys 中識別 的說明，請參閱 [在 AWS KMS keyring AWS KMS keys 中識別](#kms-keyring-id)。

下列範例使用 `buildClient`函數來指定[預設承諾政策](migrate-commitment-policy.md) `REQUIRE_ENCRYPT_REQUIRE_DECRYPT`。您也可以使用 `buildClient`來限制加密訊息中的加密資料金鑰數量。如需詳細資訊，請參閱[限制加密的資料金鑰](configure.md#config-limit-keys)。

如需完整範例，請參閱 GitHub 中 適用於 JavaScript 的 AWS Encryption SDK 儲存庫中的 [kms\$1simple.ts](https://github.com/aws/aws-encryption-sdk-javascript/blob/master/modules/example-browser/src/kms_simple.ts)。

```
import {
  KmsKeyringNode,
  buildClient,
  CommitmentPolicy,
} from '@aws-crypto/client-node'

const { encrypt, decrypt } = buildClient(
  CommitmentPolicy.REQUIRE_ENCRYPT_REQUIRE_DECRYPT
)

const clientProvider = getClient(KMS, { credentials })
const generatorKeyId = 'arn:aws:kms:us-west-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab'
const additionalKey = 'alias/exampleAlias'

const keyring = new KmsKeyringBrowser({
  clientProvider, 
  generatorKeyId, 
  keyIds: [additionalKey] 
})
```

------
#### [ JavaScript Node.js ]

當您 AWS KMS key 在 中為加密 keyring 指定 時 適用於 JavaScript 的 AWS Encryption SDK，您可以使用任何有效的金鑰識別符：[金鑰 ID](https://docs.aws.amazon.com/kms/latest/developerguide/concepts.html#key-id-key-id)、[金鑰 ARN](https://docs.aws.amazon.com/kms/latest/developerguide/concepts.html#key-id-key-ARN)、[別名名稱](https://docs.aws.amazon.com/kms/latest/developerguide/concepts.html#key-id-alias-name)或[別名 ARN](https://docs.aws.amazon.com/kms/latest/developerguide/concepts.html#key-id-alias-arn)。如需在 AWS KMS keyring AWS KMS keys 中識別 的說明，請參閱 [在 AWS KMS keyring AWS KMS keys 中識別](#kms-keyring-id)。

下列範例使用 `buildClient`函數來指定[預設承諾政策](migrate-commitment-policy.md) `REQUIRE_ENCRYPT_REQUIRE_DECRYPT`。您也可以使用 `buildClient`來限制加密訊息中的加密資料金鑰數量。如需詳細資訊，請參閱[限制加密的資料金鑰](configure.md#config-limit-keys)。

如需完整範例，請參閱 GitHub 中 適用於 JavaScript 的 AWS Encryption SDK 儲存庫中的 [kms\$1simple.ts](https://github.com/aws/aws-encryption-sdk-javascript/blob/master/modules/example-node/src/kms_simple.ts)。

```
import {
  KmsKeyringNode,
  buildClient,
  CommitmentPolicy,
} from '@aws-crypto/client-node'

const { encrypt, decrypt } = buildClient(
  CommitmentPolicy.REQUIRE_ENCRYPT_REQUIRE_DECRYPT
)

const generatorKeyId = 'arn:aws:kms:us-west-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab'
                            
const additionalKey = 'alias/exampleAlias'

const keyring = new KmsKeyringNode({
  generatorKeyId,
  keyIds: [additionalKey]
})
```

------
#### [ Java ]

若要使用一或多個 AWS KMS 金鑰建立 keyring，請使用 `CreateAwsKmsMultiKeyring()`方法。此範例使用兩個 KMS 金鑰。若要指定一個 KMS 金鑰，請僅使用 `generator` 參數。指定其他 KMS 金鑰的 `kmsKeyIds` 參數是選用的。

此 keyring 的輸入不會採用 AWS KMS 用戶端。相反地， 會針對 keyring 中 KMS 金鑰所代表的每個區域 AWS Encryption SDK 使用預設 AWS KMS 用戶端。例如，如果 參數值識別的 KMS 金鑰`Generator`位於美國西部 （奧勒岡） 區域 (`us-west-2`)，則 會為該`us-west-2`區域 AWS Encryption SDK 建立預設 AWS KMS 用戶端。如果您需要自訂用戶端 AWS KMS ，請使用 `CreateAwsKmsKeyring()`方法。

當您 AWS KMS key 在 中為加密 keyring 指定 時 適用於 JAVA 的 AWS Encryption SDK，您可以使用任何有效的金鑰識別符：[金鑰 ID](https://docs.aws.amazon.com/kms/latest/developerguide/concepts.html#key-id-key-id)、[金鑰 ARN](https://docs.aws.amazon.com/kms/latest/developerguide/concepts.html#key-id-key-ARN)、[別名名稱](https://docs.aws.amazon.com/kms/latest/developerguide/concepts.html#key-id-alias-name)或[別名 ARN](https://docs.aws.amazon.com/kms/latest/developerguide/concepts.html#key-id-alias-arn)。如需在 AWS KMS keyring AWS KMS keys 中識別 的說明，請參閱 [在 AWS KMS keyring AWS KMS keys 中識別](#kms-keyring-id)。

如需完整範例，請參閱 GitHub 中 適用於 JAVA 的 AWS Encryption SDK 儲存庫中的 [BasicEncryptionKeyringExample.java](https://github.com/aws/aws-encryption-sdk-java/blob/master/src/examples/java/com/amazonaws/crypto/examples/keyrings/BasicEncryptionKeyringExample.java)。

```
// Instantiate the AWS Encryption SDK and material providers
final AwsCrypto crypto = AwsCrypto.builder().build();
final MaterialProviders materialProviders = MaterialProviders.builder()
            .MaterialProvidersConfig(MaterialProvidersConfig.builder().build())
            .build();

String generatorKey = "arn:aws:kms:us-west-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab";
List<String> additionalKey = Collections.singletonList("arn:aws:kms:us-west-2:111122223333:key/0987dcba-09fe-87dc-65ba-ab0987654321");
// Create the keyring
final CreateAwsKmsMultiKeyringInput keyringInput = CreateAwsKmsMultiKeyringInput.builder()
        .generator(generatorKey)
        .kmsKeyIds(additionalKey)
        .build();
final IKeyring kmsKeyring = materialProviders.CreateAwsKmsMultiKeyring(keyringInput);
```

------
#### [ Python ]

若要使用一或多個 AWS KMS 金鑰建立 keyring，請使用 `create_aws_kms_multi_keyring()`方法。此範例使用兩個 KMS 金鑰。若要指定一個 KMS 金鑰，請僅使用 `generator` 參數。指定其他 KMS 金鑰的 `kms_key_ids` 參數是選用的。

此 keyring 的輸入不會採用 AWS KMS 用戶端。反之， 會針對 keyring 中 KMS 金鑰所代表的每個區域 AWS Encryption SDK 使用預設 AWS KMS 用戶端。例如，如果 參數值識別的 KMS 金鑰`generator`位於美國西部 （奧勒岡） 區域 (`us-west-2`)，則 會為該`us-west-2`區域 AWS Encryption SDK 建立預設 AWS KMS 用戶端。如果您需要自訂用戶端 AWS KMS ，請使用 `create_aws_kms_keyring()`方法。

當您 AWS KMS key 在 中為加密 keyring 指定 時 適用於 Python 的 AWS Encryption SDK，您可以使用任何有效的金鑰識別符：[金鑰 ID](https://docs.aws.amazon.com/kms/latest/developerguide/concepts.html#key-id-key-id)、[金鑰 ARN](https://docs.aws.amazon.com/kms/latest/developerguide/concepts.html#key-id-key-ARN)、[別名名稱](https://docs.aws.amazon.com/kms/latest/developerguide/concepts.html#key-id-alias-name)或[別名 ARN](https://docs.aws.amazon.com/kms/latest/developerguide/concepts.html#key-id-alias-arn)。如需在 AWS KMS keyring AWS KMS keys 中識別 的說明，請參閱 [在 AWS KMS keyring AWS KMS keys 中識別](#kms-keyring-id)。

下列範例會使用[預設承諾政策](migrate-commitment-policy.md) 來執行個體化 AWS Encryption SDK 用戶端`REQUIRE_ENCRYPT_REQUIRE_DECRYPT`。如需完整範例，請參閱 GitHub 中 適用於 Python 的 AWS Encryption SDK 儲存庫中的 [aws\$1kms\$1multi\$1keyring\$1example.py。](https://github.com/aws/aws-encryption-sdk-python/tree/master/examples/src/aws_kms_multi_keyring_example.py)

```
# Instantiate the AWS Encryption SDK client
client = aws_encryption_sdk.EncryptionSDKClient(
    commitment_policy=CommitmentPolicy.REQUIRE_ENCRYPT_REQUIRE_DECRYPT
)
        
# Optional: Create an encryption context
encryption_context: Dict[str, str] = {
    "encryption": "context",
    "is not": "secret",
    "but adds": "useful metadata",
    "that can help you": "be confident that",
    "the data you are handling": "is what you think it is",
}

# Instantiate the material providers library
mat_prov: AwsCryptographicMaterialProviders = AwsCryptographicMaterialProviders(
    config=MaterialProvidersConfig()
)

# Create the AWS KMS keyring 
kms_multi_keyring_input: CreateAwsKmsMultiKeyringInput = CreateAwsKmsMultiKeyringInput(
    generator="arn:aws:kms:us-west-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab",
    kms_key_ids="arn:aws:kms:us-west-2:111122223333:key/0987dcba-09fe-87dc-65ba-ab0987654321"
)

kms_multi_keyring: IKeyring = mat_prov.create_aws_kms_multi_keyring(
    input=kms_multi_keyring_input
)
```

------
#### [ Rust ]

若要使用一或多個 AWS KMS 金鑰建立 keyring，請使用 `create_aws_kms_multi_keyring()`方法。此範例使用兩個 KMS 金鑰。若要指定一個 KMS 金鑰，請僅使用 `generator` 參數。指定其他 KMS 金鑰的 `kms_key_ids` 參數是選用的。

此 keyring 的輸入不會採用 AWS KMS 用戶端。反之， 會針對 keyring 中 KMS 金鑰所代表的每個區域 AWS Encryption SDK 使用預設 AWS KMS 用戶端。例如，如果 參數值識別的 KMS 金鑰`generator`位於美國西部 （奧勒岡） 區域 (`us-west-2`)，則 會為該`us-west-2`區域 AWS Encryption SDK 建立預設 AWS KMS 用戶端。如果您需要自訂用戶端 AWS KMS ，請使用 `create_aws_kms_keyring()`方法。

當您 AWS KMS key 在 for Rust 中為加密 keyring AWS Encryption SDK 指定 時，您可以使用任何有效的金鑰識別符：[金鑰 ID](https://docs.aws.amazon.com/kms/latest/developerguide/concepts.html#key-id-key-id)、[金鑰 ARN](https://docs.aws.amazon.com/kms/latest/developerguide/concepts.html#key-id-key-ARN)、[別名名稱](https://docs.aws.amazon.com/kms/latest/developerguide/concepts.html#key-id-alias-name)或[別名 ARN](https://docs.aws.amazon.com/kms/latest/developerguide/concepts.html#key-id-alias-arn)。如需在 AWS KMS keyring AWS KMS keys 中識別 的說明，請參閱 [在 AWS KMS keyring AWS KMS keys 中識別](#kms-keyring-id)。

下列範例會使用[預設承諾政策](migrate-commitment-policy.md) 來執行個體化 AWS Encryption SDK 用戶端`REQUIRE_ENCRYPT_REQUIRE_DECRYPT`。如需完整範例，請參閱 GitHub 上 [aws-encryption-sdk 儲存庫的 Rust 目錄中的 aws\$1kms\$1keyring\$1example.rs](https://github.com/aws/aws-encryption-sdk-dafny/tree/mainline/AwsEncryptionSDK/runtimes/rust/examples/keyring/aws_kms_keyring_example.rs)。 aws-encryption-sdk 

```
// Instantiate the AWS Encryption SDK client
let esdk_config = AwsEncryptionSdkConfig::builder().build()?;
let esdk_client = esdk_client::Client::from_conf(esdk_config)?;
        
// Create an AWS KMS client
let sdk_config = aws_config::load_defaults(aws_config::BehaviorVersion::latest()).await;
let kms_client = aws_sdk_kms::Client::new(&sdk_config);
    
// Optional: Create an encryption context
let encryption_context = HashMap::from([
    ("encryption".to_string(), "context".to_string()),
    ("is not".to_string(), "secret".to_string()),
    ("but adds".to_string(), "useful metadata".to_string()),
    ("that can help you".to_string(), "be confident that".to_string()),
    ("the data you are handling".to_string(), "is what you think it is".to_string()),
]);

// Instantiate the material providers library
let mpl_config = MaterialProvidersConfig::builder().build()?;
let mpl = mpl_client::Client::from_conf(mpl_config)?;

// Create the AWS KMS keyring 
let kms_keyring = mpl
    .create_aws_kms_keyring()
    .kms_key_id(kms_key_id)
    .kms_client(kms_client)
    .send()
    .await?;

kms_multi_keyring: IKeyring = mpl.create_aws_kms_multi_keyring(
    input=kms_multi_keyring_input
)
```

------
#### [ Go ]

若要使用一或多個 AWS KMS 金鑰建立 keyring，請使用 `create_aws_kms_multi_keyring()`方法。此範例使用兩個 KMS 金鑰。若要指定一個 KMS 金鑰，請僅使用 `generator` 參數。指定其他 KMS 金鑰的 `kms_key_ids` 參數是選用的。

此 keyring 的輸入不會採用 AWS KMS 用戶端。反之， 會針對 keyring 中 KMS 金鑰所代表的每個區域 AWS Encryption SDK 使用預設 AWS KMS 用戶端。例如，如果 參數值識別的 KMS 金鑰`generator`位於美國西部 （奧勒岡） 區域 (`us-west-2`)，則 會為該`us-west-2`區域 AWS Encryption SDK 建立預設 AWS KMS 用戶端。如果您需要自訂用戶端 AWS KMS ，請使用 `create_aws_kms_keyring()`方法。

當您 AWS KMS key 在 AWS Encryption SDK for Go 中為加密 keyring 指定 時，您可以使用任何有效的金鑰識別符：[金鑰 ID](https://docs.aws.amazon.com/kms/latest/developerguide/concepts.html#key-id-key-id)、[金鑰 ARN](https://docs.aws.amazon.com/kms/latest/developerguide/concepts.html#key-id-key-ARN)、[別名名稱](https://docs.aws.amazon.com/kms/latest/developerguide/concepts.html#key-id-alias-name)或[別名 ARN](https://docs.aws.amazon.com/kms/latest/developerguide/concepts.html#key-id-alias-arn)。如需在 AWS KMS keyring AWS KMS keys 中識別 的說明，請參閱 [在 AWS KMS keyring AWS KMS keys 中識別](#kms-keyring-id)。

下列範例會使用[預設承諾政策](migrate-commitment-policy.md) 來執行個體化 AWS Encryption SDK 用戶端`REQUIRE_ENCRYPT_REQUIRE_DECRYPT`。

```
import (
    "context"
    
	mpl "aws/aws-cryptographic-material-providers-library/releases/go/mpl/awscryptographymaterialproviderssmithygenerated"
	mpltypes "aws/aws-cryptographic-material-providers-library/releases/go/mpl/awscryptographymaterialproviderssmithygeneratedtypes"
	client "github.com/aws/aws-encryption-sdk/awscryptographyencryptionsdksmithygenerated"
	esdktypes "github.com/aws/aws-encryption-sdk/awscryptographyencryptionsdksmithygeneratedtypes"
)

// Instantiate the AWS Encryption SDK client
encryptionClient, err := client.NewClient(esdktypes.AwsEncryptionSdkConfig{})
if err != nil {
    panic(err)
}

// Optional: Create an encryption context
encryptionContext := map[string]string{
    "encryption":                "context",
    "is not":                    "secret",
    "but adds":                  "useful metadata",
    "that can help you":         "be confident that",
    "the data you are handling": "is what you think it is",
}

// Instantiate the material providers library
matProv, err := mpl.NewClient(mpltypes.MaterialProvidersConfig{})
if err != nil {
    panic(err)
}

// Create the AWS KMS keyring 
awsKmsMultiKeyringInput := mpltypes.CreateAwsKmsMultiKeyringInput{
    Generator: "&arn:aws:kms:us-west-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab",
    KmsKeyIds: []string{"arn:aws:kms:us-west-2:111122223333:key/0987dcba-09fe-87dc-65ba-ab0987654321"},
}
awsKmsMultiKeyring, err := matProv.CreateAwsKmsMultiKeyring(context.Background(), awsKmsMultiKeyringInput)
```

------

 AWS Encryption SDK 也支援使用非對稱 RSA KMS 金鑰的 AWS KMS keyring。非對稱 RSA AWS KMS keyring 只能包含一個金鑰對。

若要使用非對稱 RSA AWS KMS keyring 加密，您不需要 [kms:GenerateDataKey](https://docs.aws.amazon.com/kms/latest/APIReference/API_GenerateDataKey.html) 或 [kms:Encrypt](https://docs.aws.amazon.com/kms/latest/APIReference/API_Encrypt.html)，因為您必須在建立 keyring 時指定要用於加密的公有金鑰材料。使用此 keyring 加密時不會進行任何 AWS KMS 呼叫。若要使用非對稱 RSA AWS KMS keyring 解密，您需要 [kms:Decrypt](https://docs.aws.amazon.com/kms/latest/APIReference/API_Decrypt.html) 許可。

**注意**  
若要建立使用非對稱 RSA KMS 金鑰的 AWS KMS keyring，您必須使用下列其中一種程式設計語言實作：  
3.*x* 版 適用於 JAVA 的 AWS Encryption SDK
AWS Encryption SDK 適用於 .NET 的 4.*x* 版和更新版本
4.*x* 版 適用於 Python 的 AWS Encryption SDK，與選用[的加密材料提供者程式庫](https://github.com/aws/aws-cryptographic-material-providers-library) (MPL) 相依性搭配使用時。
for Rust 1.*x* AWS Encryption SDK 版
適用於 Go 的 0.1.*x* AWS Encryption SDK 版或更新版本

下列範例使用 `CreateAwsKmsRsaKeyring`方法建立具有非對稱 RSA KMS 金鑰的 AWS KMS keyring。若要建立非對稱 RSA AWS KMS keyring，請提供下列值。
+ `kmsClient`：建立新的 AWS KMS 用戶端
+ `kmsKeyID`：識別非對稱 RSA KMS 金鑰的金鑰 ARN
+ `publicKey`：UTF-8 編碼 PEM 檔案的 ByteBuffer，代表您傳遞給 之金鑰的公有金鑰 `kmsKeyID`
+ `encryptionAlgorithm`：加密演算法必須為 `RSAES_OAEP_SHA_256`或 `RSAES_OAEP_SHA_1`

------
#### [ C\$1 / .NET ]

若要建立非對稱 RSA AWS KMS keyring，您必須從非對稱 RSA KMS 金鑰提供公有金鑰和私有金鑰 ARN。公有金鑰必須為 PEM 編碼。下列範例會建立具有非對稱 RSA 金鑰對的 AWS KMS keyring。

```
// Instantiate the AWS Encryption SDK and material providers
var esdk =  new ESDK(new AwsEncryptionSdkConfig());
var mpl = new MaterialProviders(new MaterialProvidersConfig());
        
var publicKey = new MemoryStream(Encoding.UTF8.GetBytes(AWS KMS RSA public key));

// Instantiate the keyring input object
var createKeyringInput = new CreateAwsKmsRsaKeyringInput
{
    KmsClient = new AmazonKeyManagementServiceClient(),
    KmsKeyId = AWS KMS RSA private key ARN,
    PublicKey = publicKey,
    EncryptionAlgorithm = EncryptionAlgorithmSpec.RSAES_OAEP_SHA_256
};

// Create the keyring
var kmsRsaKeyring = mpl.CreateAwsKmsRsaKeyring(createKeyringInput);
```

------
#### [ Java ]

若要建立非對稱 RSA AWS KMS keyring，您必須從非對稱 RSA KMS 金鑰提供公有金鑰和私有金鑰 ARN。公有金鑰必須為 PEM 編碼。下列範例會建立具有非對稱 RSA 金鑰對的 AWS KMS keyring。

```
// Instantiate the AWS Encryption SDK and material providers
final AwsCrypto crypto = AwsCrypto.builder()
        // Specify algorithmSuite without asymmetric signing here
        //
        // ALG_AES_128_GCM_IV12_TAG16_NO_KDF("0x0014"),
        // ALG_AES_192_GCM_IV12_TAG16_NO_KDF("0x0046"),
        // ALG_AES_256_GCM_IV12_TAG16_NO_KDF("0x0078"),
        // ALG_AES_128_GCM_IV12_TAG16_HKDF_SHA256("0x0114"),
        // ALG_AES_192_GCM_IV12_TAG16_HKDF_SHA256("0x0146"),
        // ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA256("0x0178")
        .withEncryptionAlgorithm(CryptoAlgorithm.ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA256)
        .build();
                
final MaterialProviders matProv = MaterialProviders.builder()
        .MaterialProvidersConfig(MaterialProvidersConfig.builder().build())
        .build();

// Create a KMS RSA keyring.
//    This keyring takes in:
//     - kmsClient
//     - kmsKeyId: Must be an ARN representing an asymmetric RSA KMS 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 CreateAwsKmsRsaKeyringInput createAwsKmsRsaKeyringInput =
        CreateAwsKmsRsaKeyringInput.builder()
                .kmsClient(KmsClient.create())
                .kmsKeyId(rsaKeyArn)
                .publicKey(publicKey)
                .encryptionAlgorithm(EncryptionAlgorithmSpec.RSAES_OAEP_SHA_256)
                .build();
IKeyring awsKmsRsaKeyring = matProv.CreateAwsKmsRsaKeyring(createAwsKmsRsaKeyringInput);
```

------
#### [ Python ]

若要建立非對稱 RSA AWS KMS keyring，您必須從非對稱 RSA KMS 金鑰提供公有金鑰和私有金鑰 ARN。公有金鑰必須為 PEM 編碼。下列範例會建立具有非對稱 RSA 金鑰對的 AWS KMS keyring。

```
# Instantiate the AWS Encryption SDK client
client = aws_encryption_sdk.EncryptionSDKClient(
    commitment_policy=CommitmentPolicy.REQUIRE_ENCRYPT_REQUIRE_DECRYPT
)
        
# Optional: Create an encryption context
encryption_context: Dict[str, str] = {
    "encryption": "context",
    "is not": "secret",
    "but adds": "useful metadata",
    "that can help you": "be confident that",
    "the data you are handling": "is what you think it is",
}

# Instantiate the material providers library
mat_prov: AwsCryptographicMaterialProviders = AwsCryptographicMaterialProviders(
    config=MaterialProvidersConfig()
)

# Create the AWS KMS keyring 
keyring_input: CreateAwsKmsRsaKeyringInput = CreateAwsKmsRsaKeyringInput(
    public_key="public_key",
    kms_key_id="kms_key_id",
    encryption_algorithm="RSAES_OAEP_SHA_256",
    kms_client=kms_client
)

kms_rsa_keyring: IKeyring = mat_prov.create_aws_kms_rsa_keyring(
    input=keyring_input
)
```

------
#### [ Rust ]

若要建立非對稱 RSA AWS KMS keyring，您必須從非對稱 RSA KMS 金鑰提供公有金鑰和私有金鑰 ARN。公有金鑰必須為 PEM 編碼。下列範例會建立具有非對稱 RSA 金鑰對的 AWS KMS keyring。

```
// Instantiate the AWS Encryption SDK client
let esdk_config = AwsEncryptionSdkConfig::builder().build()?;
let esdk_client = esdk_client::Client::from_conf(esdk_config)?;

// Create an AWS KMS client
let sdk_config = aws_config::load_defaults(aws_config::BehaviorVersion::latest()).await;
let kms_client = aws_sdk_kms::Client::new(&sdk_config);

// Optional: Create an encryption context
let encryption_context = HashMap::from([
    ("encryption".to_string(), "context".to_string()),
    ("is not".to_string(), "secret".to_string()),
    ("but adds".to_string(), "useful metadata".to_string()),
    ("that can help you".to_string(), "be confident that".to_string()),
    ("the data you are handling".to_string(), "is what you think it is".to_string()),
]);

// Instantiate the material providers library
let mpl_config = MaterialProvidersConfig::builder().build()?;
let mpl = mpl_client::Client::from_conf(mpl_config)?;

// Create the AWS KMS keyring
let kms_rsa_keyring = mpl
    .create_aws_kms_rsa_keyring()
    .kms_key_id(kms_key_id)
    .public_key(aws_smithy_types::Blob::new(public_key))
    .encryption_algorithm(aws_sdk_kms::types::EncryptionAlgorithmSpec::RsaesOaepSha256)
    .kms_client(kms_client)
    .send()
    .await?;
```

------
#### [ Go ]

```
import (
    "context"
    
	mpl "aws/aws-cryptographic-material-providers-library/releases/go/mpl/awscryptographymaterialproviderssmithygenerated"
	mpltypes "aws/aws-cryptographic-material-providers-library/releases/go/mpl/awscryptographymaterialproviderssmithygeneratedtypes"
	client "github.com/aws/aws-encryption-sdk/awscryptographyencryptionsdksmithygenerated"
	esdktypes "github.com/aws/aws-encryption-sdk/awscryptographyencryptionsdksmithygeneratedtypes"
    "github.com/aws/aws-sdk-go-v2/config"
    "github.com/aws/aws-sdk-go-v2/service/kms"
)

// Instantiate the AWS Encryption SDK client
encryptionClient, err := client.NewClient(esdktypes.AwsEncryptionSdkConfig{})
if err != nil {
    panic(err)
}

// Create an AWS KMS client
cfg, err := config.LoadDefaultConfig(context.TODO())
if err != nil {
    panic(err)
}
kmsClient := kms.NewFromConfig(cfg, func(o *kms.Options) {
    o.Region = KmsKeyRegion
})

// Optional: Create an encryption context
encryptionContext := map[string]string{
    "encryption":                "context",
    "is not":                    "secret",
    "but adds":                  "useful metadata",
    "that can help you":         "be confident that",
    "the data you are handling": "is what you think it is",
}

// Instantiate the material providers library
matProv, err := mpl.NewClient(mpltypes.MaterialProvidersConfig{})
if err != nil {
    panic(err)
}

// Create the AWS KMS keyring
awsKmsRSAKeyringInput := mpltypes.CreateAwsKmsRsaKeyringInput{
    KmsClient:           kmsClient,
    KmsKeyId:            kmsKeyID,
    PublicKey:           kmsPublicKey,
    EncryptionAlgorithm: kmstypes.EncryptionAlgorithmSpecRsaesOaepSha256,
}
awsKmsRSAKeyring, err := matProv.CreateAwsKmsRsaKeyring(context.Background(), awsKmsRSAKeyringInput)
if err != nil {
    panic(err)
}
```

------

## 使用 AWS KMS 探索 keyring
<a name="kms-keyring-discovery"></a>

解密時，[最佳實務](best-practices.md)是指定 AWS Encryption SDK 可以使用的包裝金鑰。若要遵循此最佳實務，請使用 AWS KMS 解密 keyring，將 AWS KMS 包裝金鑰限制為您指定的金鑰。不過，您也可以建立*AWS KMS 探索 keyring*，也就是不指定任何包裝金鑰的 AWS KMS keyring。

為 AWS KMS 多區域金鑰 AWS Encryption SDK 提供標準 AWS KMS 探索 keyring 和探索 keyring。如需搭配 使用多區域金鑰的詳細資訊 AWS Encryption SDK，請參閱 [使用多區域 AWS KMS keys](configure.md#config-mrks)。

由於不會指定任何包裝金鑰，探索 keyring 無法加密資料。如果您使用探索 keyring 單獨加密資料或在多 keyring 中加密資料，加密操作會失敗。例外狀況是 適用於 C 的 AWS Encryption SDK，加密操作會忽略標準探索 keyring，但如果您單獨或在多區域 keyring 中指定多區域探索 keyring，則會失敗。

解密時，探索 keyring 可讓 使用 AWS KMS key 加密的 AWS KMS 來 AWS Encryption SDK 要求解密任何加密的資料金鑰，無論誰擁有或有權存取該金鑰 AWS KMS key。呼叫只有在發起人具有 `kms:Decrypt`許可時才會成功 AWS KMS key。

**重要**  
如果您在解密多 keyring 中包含 AWS KMS 探索 keyring，則探索 keyring 會覆寫多 keyring 中其他 keyring 指定的所有 KMS 金鑰限制。 [多重 keyring](use-multi-keyring.md)多 keyring 的行為類似於其限制最低的 keyring。 AWS KMS 探索 keyring 本身或多 keyring 使用時，不會影響加密。

為了方便起見， AWS Encryption SDK 提供 AWS KMS 探索 keyring。不過，基於下列原因，建議您在可能時使用較具限制的 keyring。
+ **真實性** – AWS KMS 探索 keyring 可以使用用來加密加密訊息中資料金鑰的任何 AWS KMS key ，就像呼叫者具有使用該金鑰解密的 AWS KMS key 許可一樣。這可能不是發起 AWS KMS key 人打算使用的 。例如，其中一個加密的資料金鑰可能已在較不安全的情況下加密 AWS KMS key ，任何人都可以使用。
+ **延遲和效能** – 探索 AWS KMS keyring 可能比其他 keyring 明顯較慢，因為 AWS Encryption SDK 會嘗試解密所有加密的資料金鑰，包括 AWS KMS keys 在其他 AWS 帳戶 和 區域中加密的資料金鑰，而且 AWS KMS keys 發起人無權使用 進行解密。

如果您使用探索 keyring，我們建議您使用[*探索篩選條件*](configure.md#config-discovery)來限制 KMS 金鑰，這些金鑰可用於指定 AWS 帳戶 和 [分割區](https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html)中的金鑰。1.7.*x* 版和更新版本支援探索篩選條件。 AWS Encryption SDK如需尋找帳戶 ID 和分割區的說明，請參閱 中的[識別 AWS 帳戶 符](https://docs.aws.amazon.com/general/latest/gr/acct-identifiers.html)和 [ARN 格式](https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html#arns-syntax)*AWS 一般參考*。

下列程式碼會使用 AWS KMS 探索篩選條件來執行個體化探索 keyring，將 AWS Encryption SDK 可以使用的 KMS 金鑰限制在`aws`分割區和 111122223333 範例帳戶中的金鑰。

使用此程式碼之前，請將範例 AWS 帳戶 和分割區值取代為 AWS 帳戶 和分割區的有效值。如果您的 KMS 金鑰位於中國區域，請使用`aws-cn`分割區值。如果您的 KMS 金鑰位於 中 AWS GovCloud (US) Regions，請使用`aws-us-gov`分割區值。對於所有其他 AWS 區域，請使用`aws`分割區值。

------
#### [ C ]

如需完整範例，請參閱：[kms\$1discovery.cpp](https://github.com/aws/aws-encryption-sdk-c/blob/master/examples/kms_discovery.cpp)。

```
std::shared_ptr<KmsKeyring::> discovery_filter(
    KmsKeyring::DiscoveryFilter::Builder("aws")
        .AddAccount("111122223333")
        .Build());

struct aws_cryptosdk_keyring *kms_discovery_keyring = Aws::Cryptosdk::KmsKeyring::Builder()
       .BuildDiscovery(discovery_filter));
```

------
#### [ C\$1 / .NET ]

下列範例使用適用於 .NET 的 4 AWS Encryption SDK .*x* 版。

```
// Instantiate the AWS Encryption SDK and material providers
var esdk =  new ESDK(new AwsEncryptionSdkConfig());
var mpl = new MaterialProviders(new MaterialProvidersConfig());

List<string> account = new List<string> { "111122223333" };
        
// In a discovery keyring, you specify an AWS KMS client and a discovery filter,
// but not a AWS KMS key
var kmsDiscoveryKeyringInput = new CreateAwsKmsDiscoveryKeyringInput
{
    KmsClient = new AmazonKeyManagementServiceClient(),
    DiscoveryFilter = new DiscoveryFilter()
    {
        AccountIds = account,
        Partition = "aws"
    }
};
        
var kmsDiscoveryKeyring = mpl.CreateAwsKmsDiscoveryKeyring(kmsDiscoveryKeyringInput);
```

------
#### [ JavaScript Browser ]

在 JavaScript 中，您必須明確指定探索屬性。

下列範例使用 `buildClient`函數來指定[預設承諾政策](migrate-commitment-policy.md) `REQUIRE_ENCRYPT_REQUIRE_DECRYPT`。您也可以使用 `buildClient`來限制加密訊息中的加密資料金鑰數量。如需詳細資訊，請參閱[限制加密的資料金鑰](configure.md#config-limit-keys)。

```
import {
  KmsKeyringBrowser,
  buildClient,
  CommitmentPolicy,
} from '@aws-crypto/client-browser'

const { encrypt, decrypt } = buildClient(
  CommitmentPolicy.REQUIRE_ENCRYPT_REQUIRE_DECRYPT
)

const clientProvider = getClient(KMS, { credentials })

const discovery = true
const keyring = new KmsKeyringBrowser(clientProvider, {
    discovery,
    discoveryFilter: { accountIDs: [111122223333], partition: 'aws' }
})
```

------
#### [ JavaScript Node.js ]

在 JavaScript 中，您必須明確指定探索屬性。

下列範例使用 `buildClient`函數來指定[預設承諾政策](migrate-commitment-policy.md) `REQUIRE_ENCRYPT_REQUIRE_DECRYPT`。您也可以使用 `buildClient`來限制加密訊息中的加密資料金鑰數量。如需詳細資訊，請參閱[限制加密的資料金鑰](configure.md#config-limit-keys)。

```
import {
  KmsKeyringNode,
  buildClient,
  CommitmentPolicy,
} from '@aws-crypto/client-node'

const { encrypt, decrypt } = buildClient(
  CommitmentPolicy.REQUIRE_ENCRYPT_REQUIRE_DECRYPT
)

const discovery = true

const keyring = new KmsKeyringNode({
    discovery,
    discoveryFilter: { accountIDs: ['111122223333'], partition: 'aws' }
})
```

------
#### [ Java ]

```
// Create discovery filter
DiscoveryFilter discoveryFilter = DiscoveryFilter.builder()
        .partition("aws")
        .accountIds(111122223333)
        .build();
// Create the discovery keyring
CreateAwsKmsMrkDiscoveryMultiKeyringInput createAwsKmsMrkDiscoveryMultiKeyringInput = CreateAwsKmsMrkDiscoveryMultiKeyringInput.builder()
        .discoveryFilter(discoveryFilter)
        .build();
IKeyring decryptKeyring = matProv.CreateAwsKmsMrkDiscoveryMultiKeyring(createAwsKmsMrkDiscoveryMultiKeyringInput);
```

------
#### [ Python ]

```
# Instantiate the AWS Encryption SDK
client = aws_encryption_sdk.EncryptionSDKClient(
    commitment_policy=CommitmentPolicy.REQUIRE_ENCRYPT_REQUIRE_DECRYPT
)

# Create a boto3 client for AWS KMS
kms_client = boto3.client('kms', region_name=aws_region)

# Optional: Create an encryption context
encryption_context: Dict[str, str] = {
    "encryption": "context",
    "is not": "secret",
    "but adds": "useful metadata",
    "that can help you": "be confident that",
    "the data you are handling": "is what you think it is",
}

# Instantiate the material providers
mat_prov: AwsCryptographicMaterialProviders = AwsCryptographicMaterialProviders(
    config=MaterialProvidersConfig()
)

# Create the AWS KMS discovery keyring
discovery_keyring_input: CreateAwsKmsDiscoveryKeyringInput = CreateAwsKmsDiscoveryKeyringInput(
    kms_client=kms_client,
    discovery_filter=DiscoveryFilter(
        account_ids=[aws_account_id],
        partition="aws"
    )
)

discovery_keyring: IKeyring = mat_prov.create_aws_kms_discovery_keyring(
    input=discovery_keyring_input
)
```

------
#### [ Rust ]

```
// Instantiate the AWS Encryption SDK
let esdk_config = AwsEncryptionSdkConfig::builder().build()?;
let esdk_client = esdk_client::Client::from_conf(esdk_config)?;

// Create a AWS KMS client.
let sdk_config = aws_config::load_defaults(aws_config::BehaviorVersion::latest()).await;
let kms_client = aws_sdk_kms::Client::new(&sdk_config);


// Instantiate the material providers library
let mpl_config = MaterialProvidersConfig::builder().build()?;
let mpl = mpl_client::Client::from_conf(mpl_config)?;

// Create discovery filter
let discovery_filter = DiscoveryFilter::builder()
    .account_ids(vec![aws_account_id.to_string()])
    .partition("aws".to_string())
    .build()?;

// Create the AWS KMS discovery keyring
let discovery_keyring = mpl
    .create_aws_kms_discovery_keyring()
    .kms_client(kms_client.clone())
    .discovery_filter(discovery_filter)
    .send()
    .await?;
```

------
#### [ Go ]

```
import (
    "context"
    
	mpl "aws/aws-cryptographic-material-providers-library/releases/go/mpl/awscryptographymaterialproviderssmithygenerated"
	mpltypes "aws/aws-cryptographic-material-providers-library/releases/go/mpl/awscryptographymaterialproviderssmithygeneratedtypes"
	client "github.com/aws/aws-encryption-sdk/awscryptographyencryptionsdksmithygenerated"
	esdktypes "github.com/aws/aws-encryption-sdk/awscryptographyencryptionsdksmithygeneratedtypes"
    "github.com/aws/aws-sdk-go-v2/config"
    "github.com/aws/aws-sdk-go-v2/service/kms"
)

// Instantiate the AWS Encryption SDK client
encryptionClient, err := client.NewClient(esdktypes.AwsEncryptionSdkConfig{})
if err != nil {
    panic(err)
}

// Create an AWS KMS client
cfg, err := config.LoadDefaultConfig(context.TODO())
if err != nil {
    panic(err)
}
kmsClient := kms.NewFromConfig(cfg, func(o *kms.Options) {
    o.Region = KmsKeyRegion
})

// Optional: Create an encryption context
encryptionContext := map[string]string{
    "encryption":                "context",
    "is not":                    "secret",
    "but adds":                  "useful metadata",
    "that can help you":         "be confident that",
    "the data you are handling": "is what you think it is",
}

// Instantiate the material providers library
matProv, err := mpl.NewClient(mpltypes.MaterialProvidersConfig{})
if err != nil {
    panic(err)
}

// Create discovery filter
discoveryFilter := mpltypes.DiscoveryFilter{
    AccountIds: []string{kmsKeyAccountID},
    Partition:  "aws",
}
awsKmsDiscoveryKeyringInput := mpltypes.CreateAwsKmsDiscoveryKeyringInput{
    KmsClient:       kmsClient,
    DiscoveryFilter: &discoveryFilter,
}
awsKmsDiscoveryKeyring, err := matProv.CreateAwsKmsDiscoveryKeyring(context.Background(), awsKmsDiscoveryKeyringInput)
if err != nil {
    panic(err)
}
```

------

## 使用 AWS KMS 區域探索 keyring
<a name="kms-keyring-regional"></a>

*AWS KMS 區域探索 keyring* 是不指定 KMS 金鑰 ARNs keyring。反之，它允許 只使用 KMS 金鑰 AWS Encryption SDK 來解密 AWS 區域。

使用 AWS KMS 區域探索 keyring 解密時， 會 AWS Encryption SDK 解密在指定 AWS KMS key 中的 下加密的任何加密資料金鑰 AWS 區域。若要成功，發起人必須在加密資料金鑰的指定 AWS KMS keys 中，擁有至少一個 AWS 區域 的`kms:Decrypt`許可。

如同其他探索 keyring，區域探索 keyring 不會影響加密。只有在解密加密的訊息時才有效。如果您在用於加密和解密的多 keyring 中使用區域探索 keyring，則只有在解密時才有效。如果您使用多區域探索 keyring 單獨加密資料或在多 keyring 中加密資料，加密操作會失敗。

**重要**  
如果您在解密多 keyring 中包含 AWS KMS 區域探索 keyring，區域探索 keyring 會覆寫多 keyring 中其他 keyring 指定的所有 KMS 金鑰限制。 [多重 keyring](use-multi-keyring.md)多 keyring 的行為類似於其限制最低的 keyring。 AWS KMS 探索 keyring 本身或多 keyring 使用時，不會影響加密。

中的區域探索 keyring 適用於 C 的 AWS Encryption SDK 嘗試僅使用指定區域中的 KMS 金鑰進行解密。當您在 和 適用於 JavaScript 的 AWS Encryption SDK AWS Encryption SDK .NET 中使用探索 keyring 時，您可以在 AWS KMS 用戶端上設定 區域。這些 AWS Encryption SDK 實作不會依區域篩選 KMS 金鑰，但 AWS KMS 會失敗指定區域外 KMS 金鑰的解密請求。

如果您使用探索 keyring，我們建議您使用*探索篩選條件*，將解密所用的 KMS 金鑰限制為指定 AWS 帳戶 和 分割區中的金鑰。1.7.*x* 版和更新版本支援探索篩選條件。 AWS Encryption SDK

例如，下列程式碼會使用探索篩選條件建立 AWS KMS 區域探索 keyring。此 keyring 會將 限制 AWS Encryption SDK 在美國西部 （奧勒岡） 區域 (us-west-2) 帳戶 111122223333 中的 KMS 金鑰。

------
#### [ C ]

若要檢視此 keyring 和 `create_kms_client` 方法的工作實例，請參閱 [kms\$1discovery.cpp](https://github.com/aws/aws-encryption-sdk-c/blob/master/examples/kms_discovery.cpp)。

```
std::shared_ptr<KmsKeyring::DiscoveryFilter> discovery_filter(
    KmsKeyring::DiscoveryFilter::Builder("aws")
        .AddAccount("111122223333")
        .Build());

struct aws_cryptosdk_keyring *kms_regional_keyring = Aws::Cryptosdk::KmsKeyring::Builder()
       .WithKmsClient(create_kms_client(Aws::Region::US_WEST_2)).BuildDiscovery(discovery_filter));
```

------
#### [ C\$1 / .NET ]

for AWS Encryption SDK .NET 沒有專用的區域探索 keyring。不過，您可以使用數種技術來限制解密至特定區域時所使用的 KMS 金鑰。

探索 keyring 中限制區域的最有效方法是使用multi-Region-aware探索 keyring，即使您只使用單一區域金鑰來加密資料。當遇到單一區域金鑰時，multi-Region-aware keyring 不會使用任何多區域功能。

`CreateAwsKmsMrkDiscoveryKeyring()` 方法傳回的 keyring 會依區域篩選 KMS 金鑰，然後再呼叫 AWS KMS。 AWS KMS 只有當加密的資料金鑰由`CreateAwsKmsMrkDiscoveryKeyringInput`物件中 `Region` 參數指定的區域中的 KMS 金鑰加密時，才會傳送解密請求至 。

下列範例使用 AWS Encryption SDK 適用於 .NET 的 4.*x* 版。

```
// Instantiate the AWS Encryption SDK and material providers
var esdk =  new ESDK(new AwsEncryptionSdkConfig());
var mpl = new MaterialProviders(new MaterialProvidersConfig());

List<string> account = new List<string> { "111122223333" };

// Create the discovery filter
var filter = DiscoveryFilter = new DiscoveryFilter
{
    AccountIds = account,
    Partition = "aws"
};
                                
var regionalDiscoveryKeyringInput = new CreateAwsKmsMrkDiscoveryKeyringInput
{
    KmsClient = new AmazonKeyManagementServiceClient(RegionEndpoint.USWest2),
    Region = RegionEndpoint.USWest2,
    DiscoveryFilter = filter
};                                

var kmsRegionalDiscoveryKeyring = mpl.CreateAwsKmsMrkDiscoveryKeyring(regionalDiscoveryKeyringInput);
```

您也可以 AWS 區域 在 AWS KMS 用戶端執行個體 ([AmazonKeyManagementServiceClient](https://docs.aws.amazon.com/sdkfornet/v4/apidocs/items/KeyManagementService/TKeyManagementServiceClient.html)) 中指定區域，將 KMS 金鑰限制為特定 。不過，相較於使用multi-Region-aware探索 keyring，此組態效率較低，且成本可能更高。不會在呼叫之前依區域篩選 KMS 金鑰 AWS KMS， AWS Encryption SDK for .NET AWS KMS 會為每個加密的資料金鑰呼叫 （直到它解密一個），並依賴 AWS KMS 將其使用的 KMS 金鑰限制在指定的區域。

下列範例使用適用於 .NET 的 4 AWS Encryption SDK .*x* 版。

```
// Instantiate the AWS Encryption SDK and material providers
var esdk =  new ESDK(new AwsEncryptionSdkConfig());
var mpl = new MaterialProviders(new MaterialProvidersConfig());

List<string> account = new List<string> { "111122223333" };
        
// Create the discovery filter,
// but not a AWS KMS key
var createRegionalDiscoveryKeyringInput = new CreateAwsKmsDiscoveryKeyringInput
{
    KmsClient = new AmazonKeyManagementServiceClient(RegionEndpoint.USWest2),
    DiscoveryFilter = new DiscoveryFilter()
    {
        AccountIds = account,
        Partition = "aws"
    }
};
        
var kmsRegionalDiscoveryKeyring = mlp.CreateAwsKmsDiscoveryKeyring(createRegionalDiscoveryKeyringInput);
```

------
#### [ JavaScript Browser ]

下列範例使用 `buildClient`函數來指定[預設承諾政策](migrate-commitment-policy.md) `REQUIRE_ENCRYPT_REQUIRE_DECRYPT`。您也可以使用 `buildClient`來限制加密訊息中的加密資料金鑰數量。如需詳細資訊，請參閱[限制加密的資料金鑰](configure.md#config-limit-keys)。

```
import {
  KmsKeyringNode,
  buildClient,
  CommitmentPolicy,
} from '@aws-crypto/client-node'

const { encrypt, decrypt } = buildClient(
  CommitmentPolicy.REQUIRE_ENCRYPT_REQUIRE_DECRYPT
)

const clientProvider = getClient(KMS, { credentials })

const discovery = true
const clientProvider = limitRegions(['us-west-2'], getKmsClient)
const keyring = new KmsKeyringBrowser(clientProvider, {
    discovery,
    discoveryFilter: { accountIDs: ['111122223333'], partition: 'aws' }
})
```

------
#### [ JavaScript Node.js ]

下列範例使用 `buildClient`函數來指定[預設承諾政策](migrate-commitment-policy.md) `REQUIRE_ENCRYPT_REQUIRE_DECRYPT`。您也可以使用 `buildClient`來限制加密訊息中的加密資料金鑰數量。如需詳細資訊，請參閱[限制加密的資料金鑰](configure.md#config-limit-keys)。

若要檢視此 keyring 和`limitRegions`函數，在工作範例中，請參閱 [kms\$1regional\$1discovery.ts](https://github.com/aws/aws-encryption-sdk-javascript/blob/master/modules/example-node/src/kms_regional_discovery.ts)。

```
import {
  KmsKeyringNode,
  buildClient,
  CommitmentPolicy,
} from '@aws-crypto/client-node'

const { encrypt, decrypt } = buildClient(
  CommitmentPolicy.REQUIRE_ENCRYPT_REQUIRE_DECRYPT
)

const discovery = true
const clientProvider = limitRegions(['us-west-2'], getKmsClient)
const keyring = new KmsKeyringNode({
    clientProvider,
    discovery,
    discoveryFilter: { accountIDs: ['111122223333'], partition: 'aws' }
})
```

------
#### [ Java ]

```
// Create the discovery filter
DiscoveryFilter discoveryFilter = DiscoveryFilter.builder()
        .partition("aws")
        .accountIds(111122223333)
        .build();
// Create the discovery keyring
CreateAwsKmsMrkDiscoveryMultiKeyringInput createAwsKmsMrkDiscoveryMultiKeyringInput = CreateAwsKmsMrkDiscoveryMultiKeyringInput.builder()
        .discoveryFilter(discoveryFilter)
        .regions("us-west-2")
        .build();
IKeyring decryptKeyring = matProv.CreateAwsKmsMrkDiscoveryMultiKeyring(createAwsKmsMrkDiscoveryMultiKeyringInput);
```

------
#### [ Python ]

```
# Instantiate the AWS Encryption SDK
client = aws_encryption_sdk.EncryptionSDKClient(
    commitment_policy=CommitmentPolicy.REQUIRE_ENCRYPT_REQUIRE_DECRYPT
)

# Create a boto3 client for AWS KMS
kms_client = boto3.client('kms', region_name=aws_region)

# Optional: Create an encryption context
encryption_context: Dict[str, str] = {
    "encryption": "context",
    "is not": "secret",
    "but adds": "useful metadata",
    "that can help you": "be confident that",
    "the data you are handling": "is what you think it is",
}

# Instantiate the material providers
mat_prov: AwsCryptographicMaterialProviders = AwsCryptographicMaterialProviders(
    config=MaterialProvidersConfig()
)

# Create the AWS KMS regional discovery keyring
regional_discovery_keyring_input: CreateAwsKmsMrkDiscoveryKeyringInput = \
    CreateAwsKmsMrkDiscoveryKeyringInput(
        kms_client=kms_client,
        region=mrk_replica_decrypt_region,
        discovery_filter=DiscoveryFilter(
            account_ids=[111122223333],
            partition="aws"
        )
)

    regional_discovery_keyring: IKeyring = mat_prov.create_aws_kms_mrk_discovery_keyring(
        input=regional_discovery_keyring_input
    )
```

------
#### [ Rust ]

```
// Instantiate the AWS Encryption SDK
let esdk_config = AwsEncryptionSdkConfig::builder().build()?;
let esdk_client = esdk_client::Client::from_conf(esdk_config)?;

// Optional: Create an encryption context
let encryption_context = HashMap::from([
    ("encryption".to_string(), "context".to_string()),
    ("is not".to_string(), "secret".to_string()),
    ("but adds".to_string(), "useful metadata".to_string()),
    ("that can help you".to_string(), "be confident that".to_string()),
    ("the data you are handling".to_string(), "is what you think it is".to_string()),
]);

// Instantiate the material providers library
let mpl_config = MaterialProvidersConfig::builder().build()?;
let mpl = mpl_client::Client::from_conf(mpl_config)?;

// Create an AWS KMS client
let decrypt_kms_config = aws_sdk_kms::config::Builder::from(&sdk_config)
    .region(Region::new(mrk_replica_decrypt_region.clone()))
    .build();
let decrypt_kms_client = aws_sdk_kms::Client::from_conf(decrypt_kms_config);


// Create discovery filter
let discovery_filter = DiscoveryFilter::builder()
    .account_ids(vec![aws_account_id.to_string()])
    .partition("aws".to_string())
    .build()?;

// Create the regional discovery keyring
let discovery_keyring = mpl
    .create_aws_kms_mrk_discovery_keyring()
    .kms_client(decrypt_kms_client)
    .region(mrk_replica_decrypt_region)
    .discovery_filter(discovery_filter)
    .send()
    .await?;
```

------
#### [ Go ]

```
import (
    "context"
    
	mpl "aws/aws-cryptographic-material-providers-library/releases/go/mpl/awscryptographymaterialproviderssmithygenerated"
	mpltypes "aws/aws-cryptographic-material-providers-library/releases/go/mpl/awscryptographymaterialproviderssmithygeneratedtypes"
	client "github.com/aws/aws-encryption-sdk/awscryptographyencryptionsdksmithygenerated"
	esdktypes "github.com/aws/aws-encryption-sdk/awscryptographyencryptionsdksmithygeneratedtypes"
    "github.com/aws/aws-sdk-go-v2/config"
    "github.com/aws/aws-sdk-go-v2/service/kms"
)

// Instantiate the AWS Encryption SDK client
encryptionClient, err := client.NewClient(esdktypes.AwsEncryptionSdkConfig{})
if err != nil {
    panic(err)
}

// Create an AWS KMS client
cfg, err := config.LoadDefaultConfig(context.TODO())
if err != nil {
    panic(err)
}
kmsClient := kms.NewFromConfig(cfg, func(o *kms.Options) {
    o.Region = KmsKeyRegion
})

// Optional: Create an encryption context
encryptionContext := map[string]string{
    "encryption":                "context",
    "is not":                    "secret",
    "but adds":                  "useful metadata",
    "that can help you":         "be confident that",
    "the data you are handling": "is what you think it is",
}

// Create discovery filter
discoveryFilter := mpltypes.DiscoveryFilter{
    AccountIds: []string{awsAccountID},
    Partition:  "aws",
}

// Create the regional discovery keyring
awsKmsMrkDiscoveryInput := mpltypes.CreateAwsKmsMrkDiscoveryKeyringInput{
    KmsClient:       kmsClient,
    Region:          alternateRegionMrkKeyRegion,
    DiscoveryFilter: &discoveryFilter,
}
awsKmsMrkDiscoveryKeyring, err := matProv.CreateAwsKmsMrkDiscoveryKeyring(context.Background(), awsKmsMrkDiscoveryInput)
if err != nil {
    panic(err)
}
```

------

 適用於 JavaScript 的 AWS Encryption SDK 也會匯出 Node.js 和瀏覽器的 `excludeRegions`函數。此函數會建立在特定 AWS KMS keys 區域中省略的區域 AWS KMS 探索 keyring。下列範例會建立 AWS KMS 區域探索 keyring，除了美國東部 （維吉尼亞北部） (us-east-1) AWS 區域 以外，可在 中的 AWS KMS keys 帳戶 111122223333 中使用。

 適用於 C 的 AWS Encryption SDK 沒有類似的方法，但您可以透過建立自訂 [ClientSupplier](https://github.com/aws/aws-encryption-sdk-c/blob/master/aws-encryption-sdk-cpp/include/aws/cryptosdk/cpp/kms_keyring.h#L157) 實作。

此範例顯示 Node.js 的程式碼。

```
const discovery = true
const clientProvider = excludeRegions(['us-east-1'], getKmsClient)
const keyring = new KmsKeyringNode({
    clientProvider,
    discovery,
    discoveryFilter: { accountIDs: [111122223333], partition: 'aws' }
})
```