CreateKey搭配使用 Amazon SDK或 CLI - Amazon Key Management Service
Amazon Web Services 文档中描述的 Amazon Web Services 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅 中国的 Amazon Web Services 服务入门 (PDF)

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

CreateKey搭配使用 Amazon SDK或 CLI

以下代码示例演示如何使用 CreateKey

操作示例是大型程序的代码摘录,必须在上下文中运行。您可以在以下代码示例中查看此操作的上下文:

.NET
Amazon SDK for .NET
注意

还有更多相关信息 GitHub。在中查找完整的示例,学习如何设置和运行 Amazon 代码示例存储库

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详细信息,请参阅CreateKey中的 Amazon SDK for .NET API参考

CLI
Amazon CLI

示例 1:在中创建客户托管KMS密钥 Amazon KMS

以下create-key示例创建对称加密KMS密钥。

要创建基本KMS密钥,即对称加密密钥,您无需指定任何参数。这些参数的默认值会创建对称加密密钥。

由于此命令未指定密钥策略,因此该KMS密钥将获得以编程方式创建的密钥的默认KMS密钥策略。要查看密钥策略,请使用 get-key-policy 命令。要更改密钥策略,请使用 put-key-policy 命令。

aws kms create-key

create-key命令返回密钥元数据,包括密钥 ID 和新密钥ARN的KMS密钥。您可以使用这些值来标识其他KMS密钥 Amazon 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命令。

有关更多信息,请参阅中的创建密钥 Amazon 密钥管理服务开发人员指南

示例 2:创建用于加密和解密的非对称密RSAKMS钥

以下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" } }

有关更多信息,请参阅中的非对称密钥 Amazon KMSAmazon 密钥管理服务开发人员指南

示例 3:创建用于签名和验证的非对称椭圆曲线KMS密钥

创建包含非对称椭圆曲线 () KMS ECC 密钥对的非对称密钥,用于签名和验证。尽管SIGN_VERIFY--key-usage参数是ECCKMS键的唯一有效值,但该参数也是必需的。

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" ] } }

有关更多信息,请参阅中的非对称密钥 Amazon KMSAmazon 密钥管理服务开发人员指南

示例 4:创建HMACKMS密钥

以下create-key示例创建一个 384 位HMACKMS的密钥。--key-usage参数的GENERATE_VERIFY_MAC值是必需的,即使它是HMACKMS键的唯一有效值。

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" } }

有关更多信息,请参阅中的HMAC密钥 Amazon KMSAmazon 密钥管理服务开发人员指南

示例 4:创建多区域主键 KMS

以下 create-key 示例创建多区域主对称加密密钥。由于所有参数的默认值都会创建对称加密密钥,因此该密KMS钥只需要该--multi-region参数。在 Amazon CLI,要表示布尔参数为真,只需指定参数名称即可。

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" } }

有关更多信息,请参阅中的非对称密钥 Amazon KMSAmazon 密钥管理服务开发人员指南

示例 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" } }

有关更多信息,请参阅中的导入密钥材料 Amazon KMS里面的钥匙 Amazon 密钥管理服务开发人员指南

示例 6:在中创建KMS密钥 Amazon 云HSM密钥存储

以下create-key示例创建了一个在指定的KMS密钥中创建了一个密钥 Amazon 云HSM密钥存储。该操作在中创建KMS密钥及其元数据 Amazon KMS并在中创建密钥材料 Amazon 与自定义密钥库关联的云HSM集群。--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" } }

有关更多信息,请参阅 Amazon 云HSM密钥存储Amazon 密钥管理服务开发人员指南

示例 7:在外部密KMS钥存储库中创建密钥

以下create-key示例在指定的外部KMS密钥存储库中创建了一个密钥。在此命令中需要使用 --custom-key-store-id--origin--xks-key-id 参数。

--xks-key-id 参数指定外部密钥管理器中现有对称加密密钥的 ID。此密钥用作密钥的外部密KMS钥材料。参数的值必须--originEXTERNAL_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" } } }

有关更多信息,请参阅中的外部密钥存储库 Amazon 密钥管理服务开发人员指南

  • 有关API详细信息,请参阅CreateKey中的 Amazon CLI 命令参考

Java
SDK适用于 Java 2.x
注意

还有更多相关信息 GitHub。在中查找完整的示例,学习如何设置和运行 Amazon 代码示例存储库

/** * 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详细信息,请参阅CreateKey中的 Amazon SDK for Java 2.x API参考

Kotlin
SDK对于 Kotlin 来说
注意

还有更多相关信息 GitHub。在中查找完整的示例,学习如何设置和运行 Amazon 代码示例存储库

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详细信息,请参阅CreateKey中的 Amazon SDK以供API参考 Kotlin。

Python
SDK适用于 Python (Boto3)
注意

还有更多相关信息 GitHub。在中查找完整的示例,学习如何设置和运行 Amazon 代码示例存储库

class KeyManager: def __init__(self, kms_client): self.kms_client = kms_client self.created_keys = [] def create_key(self): """ Creates a key (or multiple keys) with a user-provided description. """ answer = "y" while answer.lower() == "y": key_desc = input("\nLet's create a key. Describe it for me: ") if not key_desc: key_desc = "Key management demo key" try: key = self.kms_client.create_key(Description=key_desc)["KeyMetadata"] except ClientError as err: logging.error( "Couldn't create your key. Here's why: %s", err.response["Error"]["Message"], ) raise else: print("Key created:") pprint(key) self.created_keys.append(key) answer = input("Create another (y/n)? ")
  • 有关API详细信息,请参阅CreateKey中的 Amazon SDK供参考 Python (Boto3) API。

Ruby
SDK对于 Ruby
注意

还有更多相关信息 GitHub。在中查找完整的示例,学习如何设置和运行 Amazon 代码示例存储库

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详细信息,请参阅CreateKey中的 Amazon SDK for Ruby API参考

Rust
SDK对于 Rust
注意

还有更多相关信息 GitHub。在中查找完整的示例,学习如何设置和运行 Amazon 代码示例存储库

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详细信息,请参阅CreateKey中的 Amazon SDK供API参考 Rust

有关完整列表 Amazon SDK开发者指南和代码示例,请参阅使用 Amazon KMS 用一个 Amazon SDK。本主题还包括有关入门的信息以及有关先前SDK版本的详细信息。