本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。
与 AWS SDK或CreateKey
一起使用 CLI
以下代码示例演示如何使用 CreateKey
。
操作示例是大型程序的代码摘录,必须在上下文中运行。在以下代码示例中,您可以查看此操作的上下文:
- .NET
-
- AWS SDK for .NET
-
注意
还有更多相关信息 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详细信息,请参阅 “AWS SDK for .NET 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
命令返回密钥元数据,包括密钥 ID 和新密钥ARN的KMS密钥。您可以使用这些值来标识其他 AWS KMS操作中的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 Key Management Service 开发人员指南》中的创建密钥。
示例 2:创建用于加密和解密的非对称密RSAKMS钥
以下
create-key
示例创建了一个包含用于加密和解KMS密的非对称RSA密钥对的密钥。aws kms create-key \ --key-spec
RSA_4096
\ --key-usageENCRYPT_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 密钥对的非对称密钥,用于签名和验证。尽管
SIGN_VERIFY
该--key-usage
参数是ECCKMS键的唯一有效值,但该参数也是必需的。aws kms create-key \ --key-spec
ECC_NIST_P521
\ --key-usageSIGN_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:创建HMACKMS密钥
以下
create-key
示例创建一个 384 位HMACKMS密钥。--key-usage
参数的GENERATE_VERIFY_MAC
值是必需的,即使它是HMACKMS键的唯一有效值。aws kms create-key \ --key-spec
HMAC_384
\ --key-usageGENERATE_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密AWS 钥管理服务开发人员指南》 AWS KMS中的密钥。
示例 4:创建多区域主键 KMS
以下
create-key
示例创建多区域主对称加密密钥。由于所有参数的默认值都会创建对称加密密钥,因此该密KMS钥只需要该--multi-region
参数。在中 AWS 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" } }
有关更多信息,请参阅《密钥管理服务开发人员指南》 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:在 AWS Cloud KMS 密钥存储区中创建HSM密钥
以下
create-key
示例在指定的 AWS Cloud KMS 密钥存储区中创建了一个HSM密钥。该操作在中创建KMS密钥及其元数据, AWS KMS并在与自定义密钥存储关联的 AWS Cloud HSM 集群中创建密钥材料。--custom-key-store-id
和--origin
参数是必需的。aws kms create-key \ --origin
AWS_CLOUDHSM
\ --custom-key-store-idcks-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" } }
有关更多信息,请参阅《HSM密钥管理服务开发人员指南》中的AWS Cloud AWS 密钥存储。
示例 7:在外部密KMS钥存储库中创建密钥
以下
create-key
示例在指定的外部KMS密钥存储库中创建了一个密钥。在此命令中需要使用--custom-key-store-id
、--origin
和--xks-key-id
参数。--xks-key-id
参数指定外部密钥管理器中现有对称加密密钥的 ID。此密钥用作密钥的外部密KMS钥材料。参数的值必须--origin
为EXTERNAL_KEY_STORE
。custom-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详细信息,请参阅 “CreateKey AWS CLI
命令参考”。
-
- Java
-
- SDK适用于 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对于 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详细信息,请参阅CreateKey
中的 Kotlin AWS SDK API 参考。
-
- 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详细信息,请参阅 “AWS SDK for PHP API参考 CreateKey” 中的。
-
- Python
-
- SDK适用于 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详细信息,请参阅CreateKey中的 AWS SDKPython (Boto3) API 参考。
-
- Ruby
-
- SDK对于 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详细信息,请参阅 “AWS SDK for Ruby API参考 CreateKey” 中的。
-
- Rust
-
- SDK对于 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详细信息,请参见CreateKey
中的 Rust AWS SDK API 参考。
-
有关 AWS SDK开发者指南和代码示例的完整列表,请参阅将此服务与 AWS SDK 结合使用。本主题还包括有关入门的信息以及有关先前SDK版本的详细信息。