

本文属于机器翻译版本。若本译文内容与英语原文存在差异，则一律以英文原文为准。

# `EnableKey`与 AWS SDK 或 CLI 配合使用
<a name="example_kms_EnableKey_section"></a>

以下代码示例演示如何使用 `EnableKey`。

操作示例是大型程序的代码摘录，必须在上下文中运行。在以下代码示例中，您可以查看此操作的上下文：
+  [了解基本功能](example_kms_Scenario_Basics_section.md) 

------
#### [ .NET ]

**适用于 .NET 的 SDK**  
 还有更多相关信息 GitHub。在 [AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/KMS#code-examples)中查找完整示例，了解如何进行设置和运行。

```
    using System;
    using System.Threading.Tasks;
    using Amazon.KeyManagementService;
    using Amazon.KeyManagementService.Model;

    /// <summary>
    /// Enable an AWS Key Management Service (AWS KMS) key.
    /// </summary>
    public class EnableKey
    {
        public static async Task Main()
        {
            var client = new AmazonKeyManagementServiceClient();

            // The identifier of the AWS KMS key to enable. You can use the
            // key Id or the Amazon Resource Name (ARN) of the AWS KMS key.
            var keyId = "1234abcd-12ab-34cd-56ef-1234567890ab";

            var request = new EnableKeyRequest
            {
                KeyId = keyId,
            };

            var response = await client.EnableKeyAsync(request);
            if (response.HttpStatusCode == System.Net.HttpStatusCode.OK)
            {
                // Retrieve information about the key to show that it has now
                // been enabled.
                var describeResponse = await client.DescribeKeyAsync(new DescribeKeyRequest
                {
                    KeyId = keyId,
                });
                Console.WriteLine($"{describeResponse.KeyMetadata.KeyId} - state: {describeResponse.KeyMetadata.KeyState}");
            }
        }
    }
```
+  有关 API 的详细信息，请参阅 *适用于 .NET 的 AWS SDK API 参考[EnableKey](https://docs.aws.amazon.com/goto/DotNetSDKV3/kms-2014-11-01/EnableKey)*中的。

------
#### [ CLI ]

**AWS CLI**  
**启用 KMS 密钥**  
以下 `enable-key` 示例启用客户托管密钥。您可以使用类似的命令来启用您通过 `disable-key` 命令暂时禁用的 KMS 密钥。您还可以使用它来启用已被禁用的 KMS 密钥，因为已计划删除该密钥且删除已取消。  
要指定 KMS 密钥，请使用 `key-id` 参数。此示例使用密钥 ID 值，但您可以在此命令中使用密钥 ID 或密钥 ARN 值。  
在运行此命令之前，将密钥 ID 示例替换为有效 ID。  

```
aws kms enable-key \
    --key-id 1234abcd-12ab-34cd-56ef-1234567890ab
```
此命令不生成任何输出。要验证 KMS 密钥是否已启用，请使用 `describe-key` 命令。查看 `describe-key` 输出中 `KeyState` 和 `Enabled` 字段的值。  
有关更多信息，请参阅《AWS 密钥管理服务开发人员指南》**中的[启用和禁用密钥](https://docs.aws.amazon.com/kms/latest/developerguide/enabling-keys.html)。  
+  有关 API 的详细信息，请参阅*AWS CLI 命令参考[EnableKey](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/kms/enable-key.html)*中的。

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

**适用于 Java 的 SDK 2.x**  
 还有更多相关信息 GitHub。在 [AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/kms#code-examples)中查找完整示例，了解如何进行设置和运行。

```
    /**
     * Asynchronously enables the specified key.
     *
     * @param keyId the ID of the key to enable
     * @return a {@link CompletableFuture} that completes when the key has been enabled
     */
    public CompletableFuture<Void> enableKeyAsync(String keyId) {
        EnableKeyRequest enableKeyRequest = EnableKeyRequest.builder()
            .keyId(keyId)
            .build();

        CompletableFuture<EnableKeyResponse> responseFuture = getAsyncClient().enableKey(enableKeyRequest);
        responseFuture.whenComplete((response, exception) -> {
            if (exception == null) {
                logger.info("Key with ID [{}] has been enabled.", keyId);
            } else {
                if (exception instanceof KmsException kmsEx) {
                    throw new RuntimeException("KMS error occurred while enabling key: " + kmsEx.getMessage(), kmsEx);
                } else {
                    throw new RuntimeException("An unexpected error occurred while enabling key: " + exception.getMessage(), exception);
                }
            }
        });

        return responseFuture.thenApply(response -> null);
    }
```
+  有关 API 的详细信息，请参阅 *AWS SDK for Java 2.x API 参考[EnableKey](https://docs.aws.amazon.com/goto/SdkForJavaV2/kms-2014-11-01/EnableKey)*中的。

------
#### [ Kotlin ]

**适用于 Kotlin 的 SDK**  
 还有更多相关信息 GitHub。在 [AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/kms#code-examples)中查找完整示例，了解如何进行设置和运行。

```
suspend fun enableKey(keyIdVal: String?) {
    val request =
        EnableKeyRequest {
            keyId = keyIdVal
        }

    KmsClient.fromEnvironment { region = "us-west-2" }.use { kmsClient ->
        kmsClient.enableKey(request)
        println("$keyIdVal was successfully enabled.")
    }
}
```
+  有关 API 的详细信息，请参阅适用[EnableKey](https://sdk.amazonaws.com/kotlin/api/latest/index.html)于 K *otlin 的AWS SDK API 参考*。

------
#### [ PHP ]

**适用于 PHP 的 SDK**  
 还有更多相关信息 GitHub。在 [AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code/kms#code-examples)中查找完整示例，了解如何进行设置和运行。

```
    /***
     * @param string $keyId
     * @return void
     */
    public function enableKey(string $keyId)
    {
        try {
            $this->client->enableKey([
                'KeyId' => $keyId,
            ]);
        }catch(KmsException $caught){
            if($caught->getAwsErrorMessage() == "NotFoundException"){
                echo "The request was rejected because the specified entity or resource could not be found.\n";
            }
            throw $caught;
        }
    }
```
+  有关 API 的详细信息，请参阅 *适用于 PHP 的 AWS SDK API 参考[EnableKey](https://docs.aws.amazon.com/goto/SdkForPHPV3/kms-2014-11-01/EnableKey)*中的。

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

**适用于 Python 的 SDK（Boto3）**  
 还有更多相关信息 GitHub。在 [AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/kms#code-examples)中查找完整示例，了解如何进行设置和运行。

```
class KeyManager:
    def __init__(self, kms_client):
        self.kms_client = kms_client
        self.created_keys = []

    @classmethod
    def from_client(cls) -> "KeyManager":
        """
        Creates a KeyManager instance with a default KMS client.

        :return: An instance of KeyManager initialized with the default KMS client.
        """
        kms_client = boto3.client("kms")
        return cls(kms_client)


    def enable_key(self, key_id: str) -> None:
        """
        Enables a key. Gets the key state after each state change.

        :param key_id: The ARN or ID of the key to enable.
        """
        try:
            self.kms_client.enable_key(KeyId=key_id)
        except ClientError as err:
            logging.error(
                "Couldn't enable key '%s'. Here's why: %s",
                key_id,
                err.response["Error"]["Message"],
            )
            raise
```
+  有关 API 的详细信息，请参阅适用[EnableKey](https://docs.aws.amazon.com/goto/boto3/kms-2014-11-01/EnableKey)于 *Python 的AWS SDK (Boto3) API 参考*。

------
#### [ SAP ABAP ]

**适用于 SAP ABAP 的 SDK**  
 还有更多相关信息 GitHub。在 [AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/kms#code-examples)中查找完整示例，了解如何进行设置和运行。

```
    TRY.
        " iv_key_id = 'arn:aws:kms:us-east-1:123456789012:key/1234abcd-12ab-34cd-56ef-1234567890ab'
        lo_kms->enablekey( iv_keyid = iv_key_id ).
        MESSAGE 'KMS key enabled successfully.' TYPE 'I'.
      CATCH /aws1/cx_kmsnotfoundexception.
        MESSAGE 'Key not found.' TYPE 'E'.
      CATCH /aws1/cx_kmskmsinternalex.
        MESSAGE 'An internal error occurred.' TYPE 'E'.
    ENDTRY.
```
+  有关 API 的详细信息，请参阅适用[EnableKey](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)于 S *AP 的AWS SDK ABAP API 参考*。

------

有关 S AWS DK 开发者指南和代码示例的完整列表，请参阅[将此服务与 AWS SDK 配合使用](sdk-general-information-section.md)。本主题还包括有关入门的信息以及有关先前的 SDK 版本的详细信息。