There are more AWS SDK examples available in the AWS Doc SDK Examples
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
-
- 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-keyexample 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-policycommand. To change the key policy, use theput-key-policycommand.aws kms create-keyThe
create-keycommand 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 thelist-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", "CurrentKeyMaterialId": "0b7fd7ddbac6eef27907413567cad8c810e2883dc8a7534067a82ee1142fc1e6", "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-keycommand does not let you specify an alias, To create an alias for the new KMS key, use thecreate-aliascommand.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-keyexample creates a KMS key that contains an asymmetric RSA key pair for encryption and decryption. The key spec and key usage can't be changed after the key is created.:aws kms create-key \ --key-specRSA_4096\ --key-usageENCRYPT_DECRYPTOutput:
{ "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-usageparameter is required even thoughSIGN_VERIFYis the only valid value for ECC KMS keys. The key spec and key usage can't be changed after the key is created.:aws kms create-key \ --key-specECC_NIST_P521\ --key-usageSIGN_VERIFYOutput:
{ "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 asymmetric ML-DSA KMS key for signing and verification
This example creates a module-lattice digital signature algorithm (ML-DSA) key for signing and verification. The key-usage parameter is required even though
SIGN_VERIFYis the only valid value for ML-DSA keys.aws kms create-key \ --key-specML_DSA_65\ --key-usageSIGN_VERIFYOutput:
{ "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", "Description": "", "Enabled": true, "KeyId": "1234abcd-12ab-34cd-56ef-1234567890ab", "KeyManager": "CUSTOMER", "KeySpec": "ML_DSA_65", "KeyState": "Enabled", "KeyUsage": "SIGN_VERIFY", "MultiRegion": false, "Origin": "AWS_KMS", "SigningAlgorithms": [ "ML_DSA_SHAKE_256" ] } }For more information, see Asymmetric keys in AWS KMS in the AWS Key Management Service Developer Guide.
Example 5: To create an HMAC KMS key
The following
create-keyexample creates a 384-bit HMAC KMS key. TheGENERATE_VERIFY_MACvalue for the--key-usageparameter is required even though it's the only valid value for HMAC KMS keys.aws kms create-key \ --key-specHMAC_384\ --key-usageGENERATE_VERIFY_MACOutput:
{ "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 6: To create a multi-Region primary KMS key
The following
create-keyexample creates a multi-Region primary symmetric encryption key. Because the default values for all parameters create a symmetric encryption key, only the--multi-regionparameter 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-regionOutput:
{ "KeyMetadata": { "Arn": "arn:aws:kms:us-west-2:111122223333:key/mrk-1234abcd12ab34cd56ef12345678990ab", "AWSAccountId": "111122223333", "CreationDate": "2021-09-02T016:15:21-09:00", "CurrentKeyMaterialId": "0b7fd7ddbac6eef27907413567cad8c810e2883dc8a7534067a82ee1142fc1e6", "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 7: To create a KMS key for imported key material
The following
create-keyexample 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--originparameter toEXTERNAL.aws kms create-key \ --originEXTERNALOutput:
{ "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-keyexample 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-idand--originparameters are required.aws kms create-key \ --originAWS_CLOUDHSM\ --custom-key-store-idcks-1234567890abcdef0Output:
{ "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 8: To create a KMS key in an external key store
The following
create-keyexample creates a creates a KMS key in the specified external key store. The--custom-key-store-id,--origin, and--xks-key-idparameters are required in this command.The
--xks-key-idparameter 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--originparameter must beEXTERNAL_KEY_STORE.Thecustom-key-store-idparameter 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 bb8562717f809024Output:
{ "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.fromEnvironment { 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.
-
- PHP
-
- SDK for PHP
-
Note
There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository
. /*** * @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; } }-
For API details, see CreateKey in AWS SDK for PHP 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 = [] @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-
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.
-