Use CreateKey with an AWS SDK or CLI - AWS Key Management Service

Use CreateKey with an AWS SDK or CLI

The following code examples show how to use CreateKey.

Action examples are code excerpts from larger programs and must be run in context. You can see this action in context in the following code examples:

.NET
AWS SDK for .NET
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository.

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."); } } }
  • For API details, see CreateKey in AWS SDK for .NET API Reference.

CLI
AWS CLI

Example 1: To create a customer managed KMS key in AWS KMS

The following create-key example creates a symmetric encryption KMS key.

To create the basic KMS key, a symmetric encryption key, you do not need to specify any parameters. The default values for those parameters create a symmetric encryption key.

Because this command doesn't specify a key policy, the KMS key gets the default key policy for programmatically created KMS keys. To view the key policy, use the get-key-policy command. To change the key policy, use the put-key-policy command.

aws kms create-key

The create-key command returns the key metadata, including the key ID and ARN of the new KMS key. You can use these values to identify the KMS key in other AWS KMS operations. The output does not include the tags. To view the tags for a KMS key, use the list-resource-tags command.

Output:

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

Note: The create-key command does not let you specify an alias, To create an alias for the new KMS key, use the create-alias command.

For more information, see Creating keys in the AWS Key Management Service Developer Guide.

Example 2: To create an asymmetric RSA KMS key for encryption and decryption

The following create-key example creates a KMS key that contains an asymmetric RSA key pair for encryption and decryption.

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

Output:

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

For more information, see Asymmetric keys in AWS KMS in the AWS Key Management Service Developer Guide.

Example 3: To create an asymmetric elliptic curve KMS key for signing and verification

To create an asymmetric KMS key that contains an asymmetric elliptic curve (ECC) key pair for signing and verification. The --key-usage parameter is required even though SIGN_VERIFY is the only valid value for ECC KMS keys.

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

Output:

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

For more information, see Asymmetric keys in AWS KMS in the AWS Key Management Service Developer Guide.

Example 4: To create an HMAC KMS key

The following create-key example creates a 384-bit HMAC KMS key. The GENERATE_VERIFY_MAC value for the --key-usage parameter is required even though it's the only valid value for HMAC KMS keys.

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

Output:

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

For more information, see HMAC keys in AWS KMS in the AWS Key Management Service Developer Guide.

Example 4: To create a multi-Region primary KMS key

The following create-key example creates a multi-Region primary symmetric encryption key. Because the default values for all parameters create a symmetric encryption key, only the --multi-region parameter is required for this KMS key. In the AWS CLI, to indicate that a Boolean parameter is true, just specify the parameter name.

aws kms create-key \ --multi-region

Output:

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

For more information, see Asymmetric keys in AWS KMS in the AWS Key Management Service Developer Guide.

Example 5: To create a KMS key for imported key material

The following create-key example creates a creates a KMS key with no key material. When the operation is complete, you can import your own key material into the KMS key. To create this KMS key, set the --origin parameter to EXTERNAL.

aws kms create-key \ --origin EXTERNAL

Output:

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

For more information, see Importing key material in AWS KMS keys in the AWS Key Management Service Developer Guide.

Example 6: To create a KMS key in an AWS CloudHSM key store

The following create-key example creates a creates a KMS key in the specified AWS CloudHSM key store. The operation creates the KMS key and its metadata in AWS KMS and creates the key material in the AWS CloudHSM cluster associated with the custom key store. The --custom-key-store-id and --origin parameters are required.

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

Output:

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

For more information, see AWS CloudHSM key stores in the AWS Key Management Service Developer Guide.

Example 7: To create a KMS key in an external key store

The following create-key example creates a creates a KMS key in the specified external key store. The --custom-key-store-id, --origin, and --xks-key-id parameters are required in this command.

The --xks-key-id parameter specifies the ID of an existing symmetric encryption key in your external key manager. This key serves as the external key material for the KMS key.The value of the --origin parameter must be EXTERNAL_KEY_STORE.The custom-key-store-id parameter must identify an external key store that is connected to its external key store proxy.

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

Output:

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

For more information, see External key stores in the AWS Key Management Service Developer Guide.

  • For API details, see CreateKey in AWS CLI Command Reference.

Java
SDK for Java 2.x
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository.

/** * 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); }); }
  • For API details, see CreateKey in AWS SDK for Java 2.x API Reference.

Kotlin
SDK for Kotlin
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository.

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 } }
  • For API details, see CreateKey in AWS SDK for Kotlin API reference.

Python
SDK for Python (Boto3)
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository.

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)? ")
  • For API details, see CreateKey in AWS SDK for Python (Boto3) API Reference.

Ruby
SDK for Ruby
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository.

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
  • For API details, see CreateKey in AWS SDK for Ruby API Reference.

Rust
SDK for Rust
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository.

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(()) }
  • For API details, see CreateKey in AWS SDK for Rust API reference.

For a complete list of AWS SDK developer guides and code examples, see Using this service with an AWS SDK. This topic also includes information about getting started and details about previous SDK versions.