選取您的 Cookie 偏好設定

我們使用提供自身網站和服務所需的基本 Cookie 和類似工具。我們使用效能 Cookie 收集匿名統計資料,以便了解客戶如何使用我們的網站並進行改進。基本 Cookie 無法停用,但可以按一下「自訂」或「拒絕」以拒絕效能 Cookie。

如果您同意,AWS 與經核准的第三方也會使用 Cookie 提供實用的網站功能、記住您的偏好設定,並顯示相關內容,包括相關廣告。若要接受或拒絕所有非必要 Cookie,請按一下「接受」或「拒絕」。若要進行更詳細的選擇,請按一下「自訂」。

CreateKey 搭配 AWS SDK 或 CLI 使用

焦點模式
CreateKey 搭配 AWS SDK 或 CLI 使用 - AWS Key Management Service

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

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

下列程式碼範例示範如何使用 CreateKey

動作範例是大型程式的程式碼摘錄,必須在內容中執行。您可以在下列程式碼範例的內容中看到此動作:

.NET
適用於 .NET 的 SDK
注意

GitHub 上提供更多範例。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

using System; using System.Threading.Tasks; using Amazon.KeyManagementService; using Amazon.KeyManagementService.Model; /// <summary> /// Shows how to create a new AWS Key Management Service (AWS KMS) /// key. /// </summary> public class CreateKey { public static async Task Main() { // Note that if you need to create a Key in an AWS Region // other than the Region defined for the default user, you need to // pass the Region to the client constructor. var client = new AmazonKeyManagementServiceClient(); // The call to CreateKeyAsync will create a symmetrical AWS KMS // key. For more information about symmetrical and asymmetrical // keys, see: // // https://docs.aws.amazon.com/kms/latest/developerguide/symm-asymm-choose.html var response = await client.CreateKeyAsync(new CreateKeyRequest()); // The KeyMetadata object contains information about the new AWS KMS key. KeyMetadata keyMetadata = response.KeyMetadata; if (keyMetadata is not null) { Console.WriteLine($"KMS Key: {keyMetadata.KeyId} was successfully created."); } else { Console.WriteLine("Could not create KMS Key."); } } }
  • 如需 API 詳細資訊,請參閱 適用於 .NET 的 AWS SDK API 參考中的 CreateKey

CLI
AWS CLI

範例 1:在 KMS 中建立客戶受管 AWS KMS 金鑰

下列create-key範例會建立對稱加密 KMS 金鑰。

若要建立基本 KMS 金鑰,即對稱加密金鑰,您不需要指定任何參數。這些參數的預設值會建立對稱加密金鑰。

由於此命令未指定金鑰政策,KMS 金鑰會取得以程式設計方式建立的 KMS 金鑰的預設金鑰政策。若要檢視金鑰政策,請使用 get-key-policy命令。若要變更金鑰政策,請使用 put-key-policy命令。

aws kms create-key

create-key 命令會傳回金鑰中繼資料,包括新 KMS 金鑰的金鑰 ID 和 ARN。您可以使用這些值來識別其他 KMS 操作中的 AWS KMS 金鑰。輸出不包含標籤。若要檢視 KMS 金鑰的標籤,請使用 list-resource-tags command

輸出:

{ "KeyMetadata": { "AWSAccountId": "111122223333", "Arn": "arn:aws:kms:us-west-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab", "CreationDate": "2017-07-05T14:04:55-07:00", "CustomerMasterKeySpec": "SYMMETRIC_DEFAULT", "Description": "", "Enabled": true, "KeyId": "1234abcd-12ab-34cd-56ef-1234567890ab", "KeyManager": "CUSTOMER", "KeySpec": "SYMMETRIC_DEFAULT", "KeyState": "Enabled", "KeyUsage": "ENCRYPT_DECRYPT", "MultiRegion": false, "Origin": "AWS_KMS" "EncryptionAlgorithms": [ "SYMMETRIC_DEFAULT" ] } }

注意: create-key命令不允許您指定別名。若要為新的 KMS 金鑰建立別名,請使用 create-alias命令。

如需詳細資訊,請參閱 金鑰管理服務開發人員指南中的建立AWS 金鑰

範例 2:建立用於加密和解密的非對稱 RSA KMS 金鑰

下列create-key範例會建立 KMS 金鑰,其中包含用於加密和解密的非對稱 RSA 金鑰對。

aws kms create-key \ --key-spec RSA_4096 \ --key-usage ENCRYPT_DECRYPT

輸出:

{ "KeyMetadata": { "Arn": "arn:aws:kms:us-east-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab", "AWSAccountId": "111122223333", "CreationDate": "2021-04-05T14:04:55-07:00", "CustomerMasterKeySpec": "RSA_4096", "Description": "", "Enabled": true, "EncryptionAlgorithms": [ "RSAES_OAEP_SHA_1", "RSAES_OAEP_SHA_256" ], "KeyId": "1234abcd-12ab-34cd-56ef-1234567890ab", "KeyManager": "CUSTOMER", "KeySpec": "RSA_4096", "KeyState": "Enabled", "KeyUsage": "ENCRYPT_DECRYPT", "MultiRegion": false, "Origin": "AWS_KMS" } }

如需詳細資訊,請參閱 金鑰管理服務開發人員指南中的 AWS KMS 中的非對稱金鑰。 AWS

範例 3:建立非對稱橢圓曲線 KMS 金鑰以進行簽署和驗證

建立非對稱 KMS 金鑰,其中包含用於簽署和驗證的非對稱橢圓曲線 (ECC) 金鑰對。即使此--key-usage參數SIGN_VERIFY是 ECC KMS 金鑰的唯一有效值,仍為必要項目。

aws kms create-key \ --key-spec ECC_NIST_P521 \ --key-usage SIGN_VERIFY

輸出:

{ "KeyMetadata": { "Arn": "arn:aws:kms:us-east-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab", "AWSAccountId": "111122223333", "CreationDate": "2019-12-02T07:48:55-07:00", "CustomerMasterKeySpec": "ECC_NIST_P521", "Description": "", "Enabled": true, "KeyId": "1234abcd-12ab-34cd-56ef-1234567890ab", "KeyManager": "CUSTOMER", "KeySpec": "ECC_NIST_P521", "KeyState": "Enabled", "KeyUsage": "SIGN_VERIFY", "MultiRegion": false, "Origin": "AWS_KMS", "SigningAlgorithms": [ "ECDSA_SHA_512" ] } }

如需詳細資訊,請參閱 金鑰管理服務開發人員指南中的 AWS KMS 中的非對稱金鑰。 AWS

範例 4:建立 HMAC KMS 金鑰

下列create-key範例會建立 384 位元 HMAC KMS 金鑰。即使--key-usage參數GENERATE_VERIFY_MAC是 HMAC KMS 金鑰的唯一有效值,仍需要 參數的值。

aws kms create-key \ --key-spec HMAC_384 \ --key-usage GENERATE_VERIFY_MAC

輸出:

{ "KeyMetadata": { "Arn": "arn:aws:kms:us-east-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab", "AWSAccountId": "111122223333", "CreationDate": "2022-04-05T14:04:55-07:00", "CustomerMasterKeySpec": "HMAC_384", "Description": "", "Enabled": true, "KeyId": "1234abcd-12ab-34cd-56ef-1234567890ab", "KeyManager": "CUSTOMER", "KeySpec": "HMAC_384", "KeyState": "Enabled", "KeyUsage": "GENERATE_VERIFY_MAC", "MacAlgorithms": [ "HMAC_SHA_384" ], "MultiRegion": false, "Origin": "AWS_KMS" } }

如需詳細資訊,請參閱 金鑰管理服務開發人員指南中的 AWS KMS 中的 HMAC 金鑰。 AWS

範例 4:建立多區域主要 KMS 金鑰

下列create-key範例會建立多區域主要對稱加密金鑰。由於所有參數的預設值都會建立對稱加密金鑰,因此此 KMS 金鑰只需要 --multi-region 參數。在 AWS CLI 中,若要指出布林值參數為 true,只要指定參數名稱即可。

aws kms create-key \ --multi-region

輸出:

{ "KeyMetadata": { "Arn": "arn:aws:kms:us-west-2:111122223333:key/mrk-1234abcd12ab34cd56ef12345678990ab", "AWSAccountId": "111122223333", "CreationDate": "2021-09-02T016:15:21-09:00", "CustomerMasterKeySpec": "SYMMETRIC_DEFAULT", "Description": "", "Enabled": true, "EncryptionAlgorithms": [ "SYMMETRIC_DEFAULT" ], "KeyId": "mrk-1234abcd12ab34cd56ef12345678990ab", "KeyManager": "CUSTOMER", "KeySpec": "SYMMETRIC_DEFAULT", "KeyState": "Enabled", "KeyUsage": "ENCRYPT_DECRYPT", "MultiRegion": true, "MultiRegionConfiguration": { "MultiRegionKeyType": "PRIMARY", "PrimaryKey": { "Arn": "arn:aws:kms:us-west-2:111122223333:key/mrk-1234abcd12ab34cd56ef12345678990ab", "Region": "us-west-2" }, "ReplicaKeys": [] }, "Origin": "AWS_KMS" } }

如需詳細資訊,請參閱 金鑰管理服務開發人員指南中的 AWS KMS 中的非對稱金鑰。 AWS

範例 5:為匯入的金鑰材料建立 KMS 金鑰

下列create-key範例會建立不含金鑰材料的 KMS 金鑰。操作完成後,您可以將自己的金鑰材料匯入 KMS 金鑰。若要建立此 KMS 金鑰,請將 --origin 參數設定為 EXTERNAL

aws kms create-key \ --origin EXTERNAL

輸出:

{ "KeyMetadata": { "Arn": "arn:aws:kms:us-east-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab", "AWSAccountId": "111122223333", "CreationDate": "2019-12-02T07:48:55-07:00", "CustomerMasterKeySpec": "SYMMETRIC_DEFAULT", "Description": "", "Enabled": false, "EncryptionAlgorithms": [ "SYMMETRIC_DEFAULT" ], "KeyId": "1234abcd-12ab-34cd-56ef-1234567890ab", "KeyManager": "CUSTOMER", "KeySpec": "SYMMETRIC_DEFAULT", "KeyState": "PendingImport", "KeyUsage": "ENCRYPT_DECRYPT", "MultiRegion": false, "Origin": "EXTERNAL" } }

如需詳細資訊,請參閱 金鑰管理服務開發人員指南中的在 AWS KMS 金鑰中匯入金鑰材料AWS

範例 6:在 a AWS CloudHSM 金鑰存放區中建立 KMS 金鑰

下列create-key範例會在指定的 AWS CloudHSM 金鑰存放區中建立 KMS 金鑰。操作會在 KMS 中建立 AWS KMS 金鑰及其中繼資料,並在與自訂金鑰存放區相關聯的 AWS CloudHSM 叢集中建立金鑰材料。--custom-key-store-id--origin 是必要參數。

aws kms create-key \ --origin AWS_CLOUDHSM \ --custom-key-store-id cks-1234567890abcdef0

輸出:

{ "KeyMetadata": { "Arn": "arn:aws:kms:us-east-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab", "AWSAccountId": "111122223333", "CloudHsmClusterId": "cluster-1a23b4cdefg", "CreationDate": "2019-12-02T07:48:55-07:00", "CustomerMasterKeySpec": "SYMMETRIC_DEFAULT", "CustomKeyStoreId": "cks-1234567890abcdef0", "Description": "", "Enabled": true, "EncryptionAlgorithms": [ "SYMMETRIC_DEFAULT" ], "KeyId": "1234abcd-12ab-34cd-56ef-1234567890ab", "KeyManager": "CUSTOMER", "KeySpec": "SYMMETRIC_DEFAULT", "KeyState": "Enabled", "KeyUsage": "ENCRYPT_DECRYPT", "MultiRegion": false, "Origin": "AWS_CLOUDHSM" } }

如需詳細資訊,請參閱 金鑰管理服務開發人員指南中的 AWS CloudHSM 金鑰存放區。 AWS

範例 7:在外部金鑰存放區中建立 KMS 金鑰

下列create-key範例會在指定的外部金鑰存放區中建立 KMS 金鑰。此命令需要 --custom-key-store-id--origin--xks-key-id 參數。

--xks-key-id 參數指定外部金鑰管理器中現有對稱加密金鑰的 ID。此金鑰做為 KMS 金鑰的外部金鑰材料。 --origin 參數的值必須是 EXTERNAL_KEY_STOREcustom-key-store-id 參數必須識別連接到其外部金鑰存放區代理的外部金鑰存放區。

aws kms create-key \ --origin EXTERNAL_KEY_STORE \ --custom-key-store-id cks-9876543210fedcba9 \ --xks-key-id bb8562717f809024

輸出:

{ "KeyMetadata": { "Arn": "arn:aws:kms:us-east-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab", "AWSAccountId": "111122223333", "CreationDate": "2022-12-02T07:48:55-07:00", "CustomerMasterKeySpec": "SYMMETRIC_DEFAULT", "CustomKeyStoreId": "cks-9876543210fedcba9", "Description": "", "Enabled": true, "EncryptionAlgorithms": [ "SYMMETRIC_DEFAULT" ], "KeyId": "1234abcd-12ab-34cd-56ef-1234567890ab", "KeyManager": "CUSTOMER", "KeySpec": "SYMMETRIC_DEFAULT", "KeyState": "Enabled", "KeyUsage": "ENCRYPT_DECRYPT", "MultiRegion": false, "Origin": "EXTERNAL_KEY_STORE", "XksKeyConfiguration": { "Id": "bb8562717f809024" } } }

如需詳細資訊,請參閱 AWS Key Management Service 開發人員指南中的外部金鑰存放區。

  • 如需 API 詳細資訊,請參閱 AWS CLI 命令參考中的 CreateKey

Java
SDK for Java 2.x
注意

GitHub 上提供更多範例。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

/** * Creates a new symmetric encryption key asynchronously. * * @param keyDesc the description of the key to be created * @return a {@link CompletableFuture} that completes with the ID of the newly created key * @throws RuntimeException if an error occurs while creating the key */ public CompletableFuture<String> createKeyAsync(String keyDesc) { CreateKeyRequest keyRequest = CreateKeyRequest.builder() .description(keyDesc) .keySpec(KeySpec.SYMMETRIC_DEFAULT) .keyUsage(KeyUsageType.ENCRYPT_DECRYPT) .build(); return getAsyncClient().createKey(keyRequest) .thenApply(resp -> resp.keyMetadata().keyId()) .exceptionally(ex -> { throw new RuntimeException("An error occurred while creating the key: " + ex.getMessage(), ex); }); }
  • 如需 API 詳細資訊,請參閱 AWS SDK for Java 2.x API 參考中的 CreateKey

Kotlin
SDK for Kotlin
注意

GitHub 上提供更多範例。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

suspend fun createKey(keyDesc: String?): String? { val request = CreateKeyRequest { description = keyDesc customerMasterKeySpec = CustomerMasterKeySpec.SymmetricDefault keyUsage = KeyUsageType.fromValue("ENCRYPT_DECRYPT") } KmsClient { region = "us-west-2" }.use { kmsClient -> val result = kmsClient.createKey(request) println("Created a customer key with id " + result.keyMetadata?.arn) return result.keyMetadata?.keyId } }
  • 如需 API 詳細資訊,請參閱 AWS SDK for Kotlin API 參考中的 CreateKey

PHP
SDK for PHP
注意

GitHub 上提供更多範例。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

/*** * @param string $keySpec * @param string $keyUsage * @param string $description * @return array */ public function createKey(string $keySpec = "", string $keyUsage = "", string $description = "Created by the SDK for PHP") { $parameters = ['Description' => $description]; if($keySpec && $keyUsage){ $parameters['KeySpec'] = $keySpec; $parameters['KeyUsage'] = $keyUsage; } try { $result = $this->client->createKey($parameters); return $result['KeyMetadata']; }catch(KmsException $caught){ // Check for error specific to createKey operations if ($caught->getAwsErrorMessage() == "LimitExceededException"){ echo "The request was rejected because a quota was exceeded. For more information, see Quotas in the Key Management Service Developer Guide."; } throw $caught; } }
  • 如需 API 詳細資訊,請參閱 適用於 PHP 的 AWS SDK API 參考中的 CreateKey

Python
SDK for Python (Boto3)
注意

GitHub 上提供更多範例。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

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 create_key(self, key_description: str) -> dict[str, any]: """ Creates a key with a user-provided description. :param key_description: A description for the key. :return: The key ID. """ try: key = self.kms_client.create_key(Description=key_description)["KeyMetadata"] self.created_keys.append(key) return key except ClientError as err: logging.error( "Couldn't create your key. Here's why: %s", err.response["Error"]["Message"], ) raise
  • 如需 API 詳細資訊,請參閱 AWS SDK for Python (Boto3) API 參考中的 CreateKey

Ruby
SDK for Ruby
注意

GitHub 上提供更多範例。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

require 'aws-sdk-kms' # v2: require 'aws-sdk' # Create a AWS KMS key. # As long we are only encrypting small amounts of data (4 KiB or less) directly, # a KMS key is fine for our purposes. # For larger amounts of data, # use the KMS key to encrypt a data encryption key (DEK). client = Aws::KMS::Client.new resp = client.create_key({ tags: [ { tag_key: 'CreatedBy', tag_value: 'ExampleUser' } ] }) puts resp.key_metadata.key_id
  • 如需 API 詳細資訊,請參閱 適用於 Ruby 的 AWS SDK API 參考中的 CreateKey

Rust
SDK for Rust
注意

GitHub 上提供更多範例。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

async fn make_key(client: &Client) -> Result<(), Error> { let resp = client.create_key().send().await?; let id = resp.key_metadata.as_ref().unwrap().key_id(); println!("Key: {}", id); Ok(()) }
  • 如需 API 詳細資訊,請參閱 AWS SDK for Rust API 參考中的 CreateKey

適用於 .NET 的 SDK
注意

GitHub 上提供更多範例。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

using System; using System.Threading.Tasks; using Amazon.KeyManagementService; using Amazon.KeyManagementService.Model; /// <summary> /// Shows how to create a new AWS Key Management Service (AWS KMS) /// key. /// </summary> public class CreateKey { public static async Task Main() { // Note that if you need to create a Key in an AWS Region // other than the Region defined for the default user, you need to // pass the Region to the client constructor. var client = new AmazonKeyManagementServiceClient(); // The call to CreateKeyAsync will create a symmetrical AWS KMS // key. For more information about symmetrical and asymmetrical // keys, see: // // https://docs.aws.amazon.com/kms/latest/developerguide/symm-asymm-choose.html var response = await client.CreateKeyAsync(new CreateKeyRequest()); // The KeyMetadata object contains information about the new AWS KMS key. KeyMetadata keyMetadata = response.KeyMetadata; if (keyMetadata is not null) { Console.WriteLine($"KMS Key: {keyMetadata.KeyId} was successfully created."); } else { Console.WriteLine("Could not create KMS Key."); } } }
  • 如需 API 詳細資訊,請參閱 適用於 .NET 的 AWS SDK API 參考中的 CreateKey

如需 AWS SDK 開發人員指南和程式碼範例的完整清單,請參閱 將此服務與 AWS SDK 搭配使用。此主題也包含有關入門的資訊和舊版 SDK 的詳細資訊。

下一個主題:

Decrypt

上一個主題:

CreateGrant
隱私權網站條款Cookie 偏好設定
© 2025, Amazon Web Services, Inc.或其附屬公司。保留所有權利。