Amazon KMS examples using Amazon CLI - Amazon Command Line Interface
Services or capabilities described in Amazon Web Services documentation might vary by Region. To see the differences applicable to the China Regions, see Getting Started with Amazon Web Services in China (PDF).

Amazon KMS examples using Amazon CLI

The following code examples show you how to perform actions and implement common scenarios by using the Amazon Command Line Interface with Amazon KMS.

Actions are code excerpts from larger programs and must be run in context. While actions show you how to call individual service functions, you can see actions in context in their related scenarios and cross-service examples.

Scenarios are code examples that show you how to accomplish a specific task by calling multiple functions within the same service.

Each example includes a link to GitHub, where you can find instructions on how to set up and run the code in context.

Topics

Actions

The following code example shows how to use cancel-key-deletion.

Amazon CLI

To cancel the scheduled deletion of a customer managed KMS key

The following cancel-key-deletion example cancels the scheduled deletion of a customer managed KMS key.

aws kms cancel-key-deletion \ --key-id 1234abcd-12ab-34cd-56ef-1234567890ab

Output:

{ "KeyId": "arn:aws:kms:us-west-2:123456789012:key/1234abcd-12ab-34cd-56ef-1234567890ab" }

When the cancel-key-deletion command succeeds, the scheduled deletion is canceled. However, the key state of the KMS key is Disabled, so you can't use the KMS key in cryptographic operations. To restore its functionality, use the enable-key command .

For more information, see Scheduling and canceling key deletion in the Amazon Key Management Service Developer Guide.

The following code example shows how to use connect-custom-key-store.

Amazon CLI

To connect a custom key store

The following connect-custom-key-store example reconnects the specified custom key store. You can use a command like this one to connect a custom key store for the first time or to reconnect a key store that was disconnected.

You can use this command to connect an Amazon CloudHSM key store or an external key store.

aws kms connect-custom-key-store \ --custom-key-store-id cks-1234567890abcdef0

This command does not return any output. To verify that the command was effective, use the describe-custom-key-stores command.

For information about connecting an Amazon CloudHSM key store, see Connecting and disconnecting an Amazon CloudHSM key store in the Amazon Key Management Service Developer Guide.

For information about connecting an external key store, see Connecting and disconnecting an external key store in the Amazon Key Management Service Developer Guide.

The following code example shows how to use create-alias.

Amazon CLI

To create an alias for a KMS key

The following create-alias command creates an alias named example-alias for the KMS key identified by key ID 1234abcd-12ab-34cd-56ef-1234567890ab.

Alias names must begin with alias/. Do not use alias names that begin with alias/aws; these are reserved for use by Amazon.

aws kms create-alias \ --alias-name alias/example-alias \ --target-key-id 1234abcd-12ab-34cd-56ef-1234567890ab

This command doesn't return any output. To see the new alias, use the list-aliases command.

For more information, see Using aliases in the Amazon Key Management Service Developer Guide.

  • For API details, see CreateAlias in Amazon CLI Command Reference.

The following code example shows how to use create-custom-key-store.

Amazon CLI

Example 1: To create an Amazon CloudHSM key store

The following create-custom-key-store example creates an Amazon CloudHSM key store backed by an Amazon CloudHSM cluster using the required parameters. You can also add the custom-key-store-type``parameter with the default value: ``AWS_CLOUDHSM.

To specify the file input for the trust-anchor-certificate command in the Amazon CLI, the file:// prefix is required.

aws kms create-custom-key-store \ --custom-key-store-name ExampleCloudHSMKeyStore \ --cloud-hsm-cluster-id cluster-1a23b4cdefg \ --key-store-password kmsPswd \ --trust-anchor-certificate file://customerCA.crt

Output:

{ "CustomKeyStoreId": cks-1234567890abcdef0 }

For more information, see Creating an Amazon CloudHSM key store in the Amazon Key Management Service Developer Guide.

Example 2: To create an external key store with public endpoint connectivity

The following create-custom-key-store example creates an external key store (XKS) that communicates with Amazon KMS over the internet.

In this example, the XksProxyUriPath uses an optional prefix of example-prefix.

NOTE: If you use Amazon CLI version 1.0, run the following command before specifying a parameter with an HTTP or HTTPS value, such as the XksProxyUriEndpoint parameter.

aws configure set cli_follow_urlparam false

Otherwise, Amazon CLI version 1.0 replaces the parameter value with the content found at that URI address.

aws kms create-custom-key-store \ --custom-key-store-name ExamplePublicEndpointXKS \ --custom-key-store-type EXTERNAL_KEY_STORE \ --xks-proxy-connectivity PUBLIC_ENDPOINT \ --xks-proxy-uri-endpoint "https://myproxy.xks.example.com" \ --xks-proxy-uri-path "/example-prefix/kms/xks/v1" \ --xks-proxy-authentication-credential "AccessKeyId=ABCDE12345670EXAMPLE, RawSecretAccessKey=DXjSUawnel2fr6SKC7G25CNxTyWKE5PF9XX6H/u9pSo="

Output:

{ "CustomKeyStoreId": cks-2234567890abcdef0 }

For more information, see Creating an external key store in the Amazon Key Management Service Developer Guide.

Example 3: To create an external key store with VPC endpoint service connectivity

The following create-custom-key-store example creates an external key store (XKS) that uses an Amazon VPC endpoint service to communicate with Amazon KMS.

NOTE: If you use Amazon CLI version 1.0, run the following command before specifying a parameter with an HTTP or HTTPS value, such as the XksProxyUriEndpoint parameter.

aws configure set cli_follow_urlparam false

Otherwise, Amazon CLI version 1.0 replaces the parameter value with the content found at that URI address.

aws kms create-custom-key-store \ --custom-key-store-name ExampleVPCEndpointXKS \ --custom-key-store-type EXTERNAL_KEY_STORE \ --xks-proxy-connectivity VPC_ENDPOINT_SERVICE \ --xks-proxy-uri-endpoint "https://myproxy-private.xks.example.com" \ --xks-proxy-uri-path "/kms/xks/v1" \ --xks-proxy-vpc-endpoint-service-name "com.amazonaws.vpce.us-east-1.vpce-svc-example1" \ --xks-proxy-authentication-credential "AccessKeyId=ABCDE12345670EXAMPLE, RawSecretAccessKey=DXjSUawnel2fr6SKC7G25CNxTyWKE5PF9XX6H/u9pSo="

Output:

{ "CustomKeyStoreId": cks-3234567890abcdef0 }

For more information, see Creating an external key store in the Amazon Key Management Service Developer Guide.

The following code example shows how to use create-grant.

Amazon CLI

To create a grant

The following create-grant example creates a grant that allows the exampleUser user to use the decrypt command on the 1234abcd-12ab-34cd-56ef-1234567890ab example KMS key. The retiring principal is the adminRole role. The grant uses the EncryptionContextSubset grant constraint to allow this permission only when the encryption context in the decrypt request includes the "Department": "IT" key-value pair.

aws kms create-grant \ --key-id 1234abcd-12ab-34cd-56ef-1234567890ab \ --grantee-principal arn:aws:iam::123456789012:user/exampleUser \ --operations Decrypt \ --constraints EncryptionContextSubset={Department=IT} \ --retiring-principal arn:aws:iam::123456789012:role/adminRole

Output:

{ "GrantId": "1a2b3c4d2f5e69f440bae30eaec9570bb1fb7358824f9ddfa1aa5a0dab1a59b2", "GrantToken": "<grant token here>" }

To view detailed information about the grant, use the list-grants command.

For more information, see Grants in Amazon KMS in the Amazon Key Management Service Developer Guide.

  • For API details, see CreateGrant in Amazon CLI Command Reference.

The following code example shows how to use create-key.

Amazon CLI

Example 1: To create a customer managed KMS key in Amazon 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 Amazon 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 Amazon 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 Amazon KMS in the Amazon 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 Amazon KMS in the Amazon 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 Amazon KMS in the Amazon 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 Amazon 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 Amazon KMS in the Amazon 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 Amazon KMS keys in the Amazon Key Management Service Developer Guide.

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

The following create-key example creates a creates a KMS key in the specified Amazon CloudHSM key store. The operation creates the KMS key and its metadata in Amazon KMS and creates the key material in the Amazon 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 Amazon CloudHSM key stores in the Amazon 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 Amazon Key Management Service Developer Guide.

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

The following code example shows how to use decrypt.

Amazon CLI

Example 1: To decrypt an encrypted message with a symmetric KMS key (Linux and macOS)

The following decrypt command example demonstrates the recommended way to decrypt data with the Amazon CLI. This version shows how to decrypt data under a symmetric KMS key.

Provide the ciphertext in a file.In the value of the --ciphertext-blob parameter, use the fileb:// prefix, which tells the CLI to read the data from a binary file. If the file is not in the current directory, type the full path to file. For more information about reading Amazon CLI parameter values from a file, see Loading Amazon CLI parameters from a file <https://docs.aws.amazon.com/cli/latest/userguide/cli-usage-parameters-file.html> in the Amazon Command Line Interface User Guide and Best Practices for Local File Parameters<https://aws.amazon.com/blogs/developer/best-practices-for-local-file-parameters/> in the Amazon Command Line Tool Blog.Specify the KMS key to decrypt the ciphertext.The --key-id parameter is not required when decrypting with a symmetric KMS key. Amazon KMS can get the key ID of the KMS key that was used to encrypt the data from the metadata in the ciphertext. But it's always a best practice to specify the KMS key you are using. This practice ensures that you use the KMS key that you intend, and prevents you from inadvertently decrypting a ciphertext using a KMS key you do not trust.Request the plaintext output as a text value.The --query parameter tells the CLI to get only the value of the Plaintext field from the output. The --output parameter returns the output as text.Base64-decode the plaintext and save it in a file.The following example pipes (|) the value of the Plaintext parameter to the Base64 utility, which decodes it. Then, it redirects (>) the decoded output to the ExamplePlaintext file.

Before running this command, replace the example key ID with a valid key ID from your Amazon account.

aws kms decrypt \ --ciphertext-blob fileb://ExampleEncryptedFile \ --key-id 1234abcd-12ab-34cd-56ef-1234567890ab \ --output text \ --query Plaintext | base64 \ --decode > ExamplePlaintextFile

This command produces no output. The output from the decrypt command is base64-decoded and saved in a file.

For more information, see Decrypt in the Amazon Key Management Service API Reference.

Example 2: To decrypt an encrypted message with a symmetric KMS key (Windows command prompt)

The following example is the same as the previous one except that it uses the certutil utility to Base64-decode the plaintext data. This procedure requires two commands, as shown in the following examples.

Before running this command, replace the example key ID with a valid key ID from your Amazon account.

aws kms decrypt ^ --ciphertext-blob fileb://ExampleEncryptedFile ^ --key-id 1234abcd-12ab-34cd-56ef-1234567890ab ^ --output text ^ --query Plaintext > ExamplePlaintextFile.base64

Run the certutil command.

certutil -decode ExamplePlaintextFile.base64 ExamplePlaintextFile

Output:

Input Length = 18 Output Length = 12 CertUtil: -decode command completed successfully.

For more information, see Decrypt in the Amazon Key Management Service API Reference.

Example 3: To decrypt an encrypted message with an asymmetric KMS key (Linux and macOS)

The following decrypt command example shows how to decrypt data encrypted under an RSA asymmetric KMS key.

When using an asymmetric KMS key, the encryption-algorithm parameter, which specifies the algorithm used to encrypt the plaintext, is required.

Before running this command, replace the example key ID with a valid key ID from your Amazon account.

aws kms decrypt \ --ciphertext-blob fileb://ExampleEncryptedFile \ --key-id 0987dcba-09fe-87dc-65ba-ab0987654321 \ --encryption-algorithm RSAES_OAEP_SHA_256 \ --output text \ --query Plaintext | base64 \ --decode > ExamplePlaintextFile

This command produces no output. The output from the decrypt command is base64-decoded and saved in a file.

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

  • For API details, see Decrypt in Amazon CLI Command Reference.

The following code example shows how to use delete-alias.

Amazon CLI

To delete an Amazon KMS alias

The following delete-alias example deletes the alias alias/example-alias. The alias name must begin with alias/.

aws kms delete-alias \ --alias-name alias/example-alias

This command produces no output. To find the alias, use the list-aliases command.

For more information, see Deleting an alias in the Amazon Key Management Service Developer Guide.

  • For API details, see DeleteAlias in Amazon CLI Command Reference.

The following code example shows how to use delete-custom-key-store.

Amazon CLI

To delete a custom key store

The following delete-custom-key-store example deletes the specified custom key store.

Deleting an Amazon CloudHSM key store has no effect on the associated CloudHSM cluster. Deleting an external key store has no effect on the associated external key store proxy, external key manager, or external keys.

NOTE: Before you can delete a custom key store, you must schedule the deletion of all KMS keys in the custom key store and then wait for those KMS keys to be deleted. Then, you must disconnect the custom key store. For help finding the KMS keys in your custom key store, see Delete an Amazon CloudHSM key store (API) in the Amazon Key Management Service Developer Guide.

delete-custom-key-store \ --custom-key-store-id cks-1234567890abcdef0

This command does not return any output. To verify that the custom key store is deleted, use the describe-custom-key-stores command.

For information about deleting an Amazon CloudHSM key stores, see Deleting an Amazon CloudHSM key store in the Amazon Key Management Service Developer Guide.

For information about deleting external key stores, see Deleting an external key store in the Amazon Key Management Service Developer Guide.

The following code example shows how to use delete-imported-key-material.

Amazon CLI

To delete imported key material from a KMS key

The following delete-imported-key-material example deletes key material that had been imported into a KMS key.

aws kms delete-imported-key-material \ --key-id 1234abcd-12ab-34cd-56ef-1234567890ab

This command produces no output. To verify that the key material is deleted, use the describe-key command to look for a key state of PendingImport or PendingDeletion.

For more information, see Deleting imported key material<https://docs.aws.amazon.com/kms/latest/developerguide/importing-keys-delete-key-material.html> in the Amazon Key Management Service Developer Guide.

The following code example shows how to use describe-custom-key-stores.

Amazon CLI

Example 1: To get details about an Amazon CloudHSM key store

The following describe-custom-key-store example displays details about the specified Amazon CloudHSM key store. The command is the same for all types of custom key stores, but the output differs with the key store type and, for an external key store, its connectivity option.

By default, this command displays information about all custom key stores in the account and Region. To display information about a particular custom key store, use the custom-key-store-name or custom-key-store-id parameter.

aws kms describe-custom-key-stores \ --custom-key-store-name ExampleCloudHSMKeyStore

The output of this command includes useful details about the Amazon CloudHSM key store including its connection state (ConnectionState). If the connection state is FAILED, the output includes a ConnectionErrorCode field that describes the problem.

Output:

{ "CustomKeyStores": [ { "CloudHsmClusterId": "cluster-1a23b4cdefg", "ConnectionState": "CONNECTED", "CreationDate": "2022-04-05T14:04:55-07:00", "CustomKeyStoreId": "cks-1234567890abcdef0", "CustomKeyStoreName": "ExampleExternalKeyStore", "TrustAnchorCertificate": "<certificate appears here>" } ] }

For more information, see Viewing an Amazon CloudHSM key store in the Amazon Key Management Service Developer Guide.

Example 2: To get details about an external key store with public endpoint connectivity

The following describe-custom-key-store example displays details about the specified external key store. The command is the same for all types of custom key stores, but the output differs with the key store type and, for an external key store, its connectivity option.

By default, this command displays information about all custom key stores in the account and Region. To display information about a particular custom key store, use the custom-key-store-name or custom-key-store-id parameter.

aws kms describe-custom-key-stores \ --custom-key-store-id cks-9876543210fedcba9

The output of this command includes useful details about the external key store including its connection state (ConnectionState). If the connection state is FAILED, the output includes a ConnectionErrorCode field that describes the problem.

Output:

{ "CustomKeyStores": [ { "CustomKeyStoreId": "cks-9876543210fedcba9", "CustomKeyStoreName": "ExampleXKS", "ConnectionState": "CONNECTED", "CreationDate": "2022-12-02T07:48:55-07:00", "CustomKeyStoreType": "EXTERNAL_KEY_STORE", "XksProxyConfiguration": { "AccessKeyId": "ABCDE12345670EXAMPLE", "Connectivity": "PUBLIC_ENDPOINT", "UriEndpoint": "https://myproxy.xks.example.com", "UriPath": "/example-prefix/kms/xks/v1" } } ] }

For more information, see Viewing an external key store in the Amazon Key Management Service Developer Guide.

Example 3: To get details about an external key store with VPC endpoint service connectivity

The following describe-custom-key-store example displays details about the specified external key store. The command is the same for all types of custom key stores, but the output differs with the key store type and, for an external key store, its connectivity option.

By default, this command displays information about all custom key stores in the account and Region. To display information about a particular custom key store, use the custom-key-store-name or custom-key-store-id parameter.

aws kms describe-custom-key-stores \ --custom-key-store-id cks-2234567890abcdef0

The output of this command includes useful details about the external key store including its connection state (ConnectionState). If the connection state is FAILED, the output includes a ConnectionErrorCode field that describes the problem.

Output:

{ "CustomKeyStores": [ { "CustomKeyStoreId": "cks-3234567890abcdef0", "CustomKeyStoreName": "ExampleVPCExternalKeyStore", "ConnectionState": "CONNECTED", "CreationDate": "2022-12-22T07:48:55-07:00", "CustomKeyStoreType": "EXTERNAL_KEY_STORE", "XksProxyConfiguration": { "AccessKeyId": "ABCDE12345670EXAMPLE", "Connectivity": "VPC_ENDPOINT_SERVICE", "UriEndpoint": "https://myproxy-private.xks.example.com", "UriPath": "/kms/xks/v1", "VpcEndpointServiceName": "com.amazonaws.vpce.us-east-1.vpce-svc-example1" } } ] }

For more information, see Viewing an external key store in the Amazon Key Management Service Developer Guide.

The following code example shows how to use describe-key.

Amazon CLI

Example 1: To find detailed information about a KMS key

The following describe-key example gets detailed information about the Amazon managed key for Amazon S3 in the example account and Region. You can use this command to find details about Amazon managed keys and customer managed keys.

To specify the KMS key, use the key-id parameter. This example uses an alias name value, but you can use a key ID, key ARN, alias name, or alias ARN in this command.

aws kms describe-key \ --key-id alias/aws/s3

Output:

{ "KeyMetadata": { "AWSAccountId": "846764612917", "KeyId": "b8a9477d-836c-491f-857e-07937918959b", "Arn": "arn:aws:kms:us-west-2:846764612917:key/b8a9477d-836c-491f-857e-07937918959b", "CreationDate": 2017-06-30T21:44:32.140000+00:00, "Enabled": true, "Description": "Default KMS key that protects my S3 objects when no other key is defined", "KeyUsage": "ENCRYPT_DECRYPT", "KeyState": "Enabled", "Origin": "AWS_KMS", "KeyManager": "AWS", "CustomerMasterKeySpec": "SYMMETRIC_DEFAULT", "EncryptionAlgorithms": [ "SYMMETRIC_DEFAULT" ] } }

For more information, see Viewing keys in the Amazon Key Management Service Developer Guide.

Example 2: To get details about an RSA asymmetric KMS key

The following describe-key example gets detailed information about an asymmetric RSA KMS key used for signing and verification.

aws kms describe-key \ --key-id 1234abcd-12ab-34cd-56ef-1234567890ab

Output:

{ "KeyMetadata": { "AWSAccountId": "111122223333", "KeyId": "1234abcd-12ab-34cd-56ef-1234567890ab", "Arn": "arn:aws:kms:us-west-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab", "CreationDate": "2019-12-02T19:47:14.861000+00:00", "CustomerMasterKeySpec": "RSA_2048", "Enabled": false, "Description": "", "KeyState": "Disabled", "Origin": "AWS_KMS", "MultiRegion": false, "KeyManager": "CUSTOMER", "KeySpec": "RSA_2048", "KeyUsage": "SIGN_VERIFY", "SigningAlgorithms": [ "RSASSA_PKCS1_V1_5_SHA_256", "RSASSA_PKCS1_V1_5_SHA_384", "RSASSA_PKCS1_V1_5_SHA_512", "RSASSA_PSS_SHA_256", "RSASSA_PSS_SHA_384", "RSASSA_PSS_SHA_512" ] } }

Example 3: To get details about a multi-Region replica key

The following describe-key example gets metadata for a multi-Region replica key. This multi-Region key is a symmetric encryption key. The output of a describe-key command for any multi-Region key returns information about the primary key and all of its replicas.

aws kms describe-key \ --key-id arn:aws:kms:ap-northeast-1:111122223333:key/mrk-1234abcd12ab34cd56ef1234567890ab

Output:

{ "KeyMetadata": { "MultiRegion": true, "AWSAccountId": "111122223333", "Arn": "arn:aws:kms:ap-northeast-1:111122223333:key/mrk-1234abcd12ab34cd56ef1234567890ab", "CreationDate": "2021-06-28T21:09:16.114000+00:00", "Description": "", "Enabled": true, "KeyId": "mrk-1234abcd12ab34cd56ef1234567890ab", "KeyManager": "CUSTOMER", "KeyState": "Enabled", "KeyUsage": "ENCRYPT_DECRYPT", "Origin": "AWS_KMS", "CustomerMasterKeySpec": "SYMMETRIC_DEFAULT", "EncryptionAlgorithms": [ "SYMMETRIC_DEFAULT" ], "MultiRegionConfiguration": { "MultiRegionKeyType": "PRIMARY", "PrimaryKey": { "Arn": "arn:aws:kms:us-west-2:111122223333:key/mrk-1234abcd12ab34cd56ef1234567890ab", "Region": "us-west-2" }, "ReplicaKeys": [ { "Arn": "arn:aws:kms:eu-west-1:111122223333:key/mrk-1234abcd12ab34cd56ef1234567890ab", "Region": "eu-west-1" }, { "Arn": "arn:aws:kms:ap-northeast-1:111122223333:key/mrk-1234abcd12ab34cd56ef1234567890ab", "Region": "ap-northeast-1" }, { "Arn": "arn:aws:kms:sa-east-1:111122223333:key/mrk-1234abcd12ab34cd56ef1234567890ab", "Region": "sa-east-1" } ] } } }

Example 4: To get details about an HMAC KMS key

The following describe-key example gets detailed information about an HMAC KMS key.

aws kms describe-key \ --key-id 1234abcd-12ab-34cd-56ef-1234567890ab

Output:

{ "KeyMetadata": { "AWSAccountId": "123456789012", "KeyId": "1234abcd-12ab-34cd-56ef-1234567890ab", "Arn": "arn:aws:kms:us-west-2:123456789012:key/1234abcd-12ab-34cd-56ef-1234567890ab", "CreationDate": "2022-04-03T22:23:10.194000+00:00", "Enabled": true, "Description": "Test key", "KeyUsage": "GENERATE_VERIFY_MAC", "KeyState": "Enabled", "Origin": "AWS_KMS", "KeyManager": "CUSTOMER", "CustomerMasterKeySpec": "HMAC_256", "MacAlgorithms": [ "HMAC_SHA_256" ], "MultiRegion": false } }
  • For API details, see DescribeKey in Amazon CLI Command Reference.

The following code example shows how to use disable-key-rotation.

Amazon CLI

To disable automatic rotation of a KMS key

The following disable-key-rotation example disables automatic rotation of a customer managed KMS key. To reenable automatic rotation, use the enable-key-rotation command.

aws kms disable-key-rotation \ --key-id arn:aws:kms:us-west-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab

This command produces no output. To verify that automatic rotation is disable for the KMS key, use the get-key-rotation-status command.

For more information, see Rotating keys in the Amazon Key Management Service Developer Guide.

The following code example shows how to use disable-key.

Amazon CLI

To temporarily disable a KMS key

The following example uses the disable-key command to disable a customer managed KMS key. To re-enable the KMS key, use the enable-key command.

aws kms disable-key \ --key-id 1234abcd-12ab-34cd-56ef-1234567890ab

This command produces no output.

For more information, see Enabling and Disabling Keys in the Amazon Key Management Service Developer Guide.

  • For API details, see DisableKey in Amazon CLI Command Reference.

The following code example shows how to use disconnect-custom-key-store.

Amazon CLI

To disconnect a custom key store

The following disconnect-custom-key-store example disconnects a custom key store from its Amazon CloudHSM cluster. You might disconnect a key store to troubleshoot a problem, to update its settings, or to prevent KMS keys in the keystore from being used in cryptographic operations.

This command is the same for all custom key stores, including Amazon CloudHSM key stores and external key stores.

Before running this command, replace the example custom key store ID with a valid one.

$ aws kms disconnect-custom-key-store \ --custom-key-store-id cks-1234567890abcdef0

This command produces no output. verify that the command was effective, use the describe-custom-key-stores command.

For more information about disconnecting an Amazon CloudHSM key store, see Connecting and disconnecting an Amazon CloudHSM key store in the Amazon Key Management Service Developer Guide.

For more information about disconnecting an external key store, see Connecting and disconnecting an external key store in the Amazon Key Management Service Developer Guide.

The following code example shows how to use enable-key-rotation.

Amazon CLI

To enable automatic rotation of a KMS key

The following enable-key-rotation example enables automatic rotation of a customer managed KMS key with a rotation period of 180 days. The KMS key will be rotated one year (approximate 365 days) from the date that this command completes and every year thereafter.

The --key-id parameter identifies the KMS key. This example uses a key ARN value, but you can use either the key ID or the ARN of the KMS key.The --rotation-period-in-days parameter specifies the number of days between each rotation date. Specify a value between 90 and 2560 days. If no value is specified, the default value is 365 days.

aws kms enable-key-rotation \ --key-id arn:aws:kms:us-west-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab \ --rotation-period-in-days 180

This command produces no output. To verify that the KMS key is enabled, use the get-key-rotation-status command.

For more information, see Rotating keys in the Amazon Key Management Service Developer Guide.

The following code example shows how to use enable-key.

Amazon CLI

To enable a KMS key

The following enable-key example enables a customer managed key. You can use a command like this one to enable a KMS key that you temporarily disabled by using the disable-key command. You can also use it to enable a KMS key that is disabled because it was scheduled for deletion and the deletion was canceled.

To specify the KMS key, use the key-id parameter. This example uses an key ID value, but you can use a key ID or key ARN value in this command.

Before running this command, replace the example key ID with a valid one.

aws kms enable-key \ --key-id 1234abcd-12ab-34cd-56ef-1234567890ab

This command produces no output. To verify that the KMS key is enabled, use the describe-key command. See the values of the KeyState and Enabled fields in the describe-key output.

For more information, see Enabling and Disabling Keys in the Amazon Key Management Service Developer Guide.

  • For API details, see EnableKey in Amazon CLI Command Reference.

The following code example shows how to use encrypt.

Amazon CLI

Example 1: To encrypt the contents of a file on Linux or MacOS

The following encrypt command demonstrates the recommended way to encrypt data with the Amazon CLI.

aws kms encrypt \ --key-id 1234abcd-12ab-34cd-56ef-1234567890ab \ --plaintext fileb://ExamplePlaintextFile \ --output text \ --query CiphertextBlob | base64 \ --decode > ExampleEncryptedFile

The command does several things:

Uses the --plaintext parameter to indicate the data to encrypt. This parameter value must be base64-encoded.The value of the plaintext parameter must be base64-encoded, or you must use the fileb:// prefix, which tells the Amazon CLI to read binary data from the file.If the file is not in the current directory, type the full path to file. For example: fileb:///var/tmp/ExamplePlaintextFile or fileb://C:\Temp\ExamplePlaintextFile. For more information about reading Amazon CLI parameter values from a file, see Loading Parameters from a File in the Amazon Command Line Interface User Guide and Best Practices for Local File Parameters on the Amazon Command Line Tool Blog.Uses the --output and --query parameters to control the command's output.These parameters extract the encrypted data, called the ciphertext, from the command's output.For more information about controlling output, see Controlling Command Output in the Amazon Command Line Interface User Guide.Uses the base64 utility to decode the extracted output into binary data.The ciphertext that is returned by a successful encrypt command is base64-encoded text. You must decode this text before you can use the Amazon CLI to decrypt it.Saves the binary ciphertext to a file.The final part of the command (> ExampleEncryptedFile) saves the binary ciphertext to a file to make decryption easier. For an example command that uses the Amazon CLI to decrypt data, see the decrypt examples.

Example 2: Using the Amazon CLI to encrypt data on Windows

This example is the same as the previous one, except that it uses the certutil tool instead of base64. This procedure requires two commands, as shown in the following example.

aws kms encrypt \ --key-id 1234abcd-12ab-34cd-56ef-1234567890ab \ --plaintext fileb://ExamplePlaintextFile \ --output text \ --query CiphertextBlob > C:\Temp\ExampleEncryptedFile.base64 certutil -decode C:\Temp\ExampleEncryptedFile.base64 C:\Temp\ExampleEncryptedFile

Example 3: Encrypting with an asymmetric KMS key

The following encrypt command shows how to encrypt plaintext with an asymmetric KMS key. The --encryption-algorithm parameter is required. As in all encrypt CLI commands, the plaintext parameter must be base64-encoded, or you must use the fileb:// prefix, which tells the Amazon CLI to read binary data from the file.

aws kms encrypt \ --key-id 1234abcd-12ab-34cd-56ef-1234567890ab \ --encryption-algorithm RSAES_OAEP_SHA_256 \ --plaintext fileb://ExamplePlaintextFile \ --output text \ --query CiphertextBlob | base64 \ --decode > ExampleEncryptedFile

This command produces no output.

  • For API details, see Encrypt in Amazon CLI Command Reference.

The following code example shows how to use generate-data-key-pair-without-plaintext.

Amazon CLI

To generate an ECC NIST P384 asymmetric data key pair

The following generate-data-key-pair-without-plaintext example requests an ECC NIST P384 key pair for use outside of Amazon.

The command returns a plaintext public key and a copy of the private key encrypted under the specified KMS key. It does not return a plaintext private key. You can safely store the encrypted private key with the encrypted data, and call Amazon KMS to decrypt the private key when you need to use it.

To request an ECC NIST P384 asymmetric data key pair, use the key-pair-spec parameter with a value of ECC_NIST_P384.

The KMS key you specify must be a symmetric encryption KMS key, that is, a KMS key with a KeySpec value of SYMMETRIC_DEFAULT.

NOTE: The values in the output of this example are truncated for display.

aws kms generate-data-key-pair-without-plaintext \ --key-id 1234abcd-12ab-34cd-56ef-1234567890ab \ --key-pair-spec ECC_NIST_P384

Output:

{ "PrivateKeyCiphertextBlob": "AQIDAHi6LtupRpdKl2aJTzkK6FbhOtQkMlQJJH3PdtHvS/y+hAFFxmiD134doUDzMGmfCEtcAAAHaTCCB2UGCSqGSIb3DQEHBqCCB1...", "PublicKey": "MIIBojANBgkqhkiG9w0BAQEFAAOCAY8AMIIBigKCAYEA3A3eGMyPrvSn7+LdlJE1oUoQV5HpEuHAVbdOyND+NmYDH/mL1OSIEuLrcdZ5hrMH4pk83r40l...", "KeyId": "arn:aws:kms:us-west-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab", "KeyPairSpec": "ECC_NIST_P384" }

The PublicKey and PrivateKeyCiphertextBlob are returned in base64-encoded format.

For more information, see Data key pairs in the Amazon Key Management Service Developer Guide.

The following code example shows how to use generate-data-key-pair.

Amazon CLI

To generate an 2048-bit RSA asymmetric data key pair

The following generate-data-key-pair example requests a 2048-bit RSA asymmetric data key pair for use outside of Amazon. The command returns a plaintext public key and a plaintext private key for immediate use and deletion, and a copy of the private key encrypted under the specified KMS key. You can safely store the encrypted private key with the encrypted data.

To request a 2048-bit RSA asymmetric data key pair, use the key-pair-spec parameter with a value of RSA_2048.

The KMS key you specify must be a symmetric encryption KMS key, that is, a KMS key with a KeySpec value of SYMMETRIC_DEFAULT.

NOTE: The values in the output of this example are truncated for display.

aws kms generate-data-key-pair \ --key-id 1234abcd-12ab-34cd-56ef-1234567890ab \ --key-pair-spec RSA_2048

Output:

{ "PrivateKeyCiphertextBlob": "AQIDAHi6LtupRpdKl2aJTzkK6FbhOtQkMlQJJH3PdtHvS/y+hAFFxmiD134doUDzMGmfCEtcAAAHaTCCB2UGCSqGSIb3DQEHBqCCB1...", "PrivateKeyPlaintext": "MIIG/QIBADANBgkqhkiG9w0BAQEFAASCBucwggbjAgEAAoIBgQDcDd4YzI+u9Kfv4t2UkTWhShBXkekS4cBVt07I0P42ZgMf+YvU5IgS4ut...", "PublicKey": "MIIBojANBgkqhkiG9w0BAQEFAAOCAY8AMIIBigKCAYEA3A3eGMyPrvSn7+LdlJE1oUoQV5HpEuHAVbdOyND+NmYDH/mL1OSIEuLrcdZ5hrMH4pk83r40l...", "KeyId": "arn:aws:kms:us-west-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab", "KeyPairSpec": "RSA_2048" }

The PublicKey, PrivateKeyPlaintext, and PrivateKeyCiphertextBlob are returned in base64-encoded format.

For more information, see Data key pairs in the Amazon Key Management Service Developer Guide.

The following code example shows how to use generate-data-key-without-plaintext.

Amazon CLI

To generate a 256-bit symmetric data key without a plaintext key

The following generate-data-key-without-plaintext example requests an encrypted copy of a 256-bit symmetric data key for use outside of Amazon. You can call Amazon KMS to decrypt the data key when you are ready to use it.

To request a 256-bit data key, use the key-spec parameter with a value of AES_256. To request a 128-bit data key, use the key-spec parameter with a value of AES_128. For all other data key lengths, use the number-of-bytes parameter.

The KMS key you specify must be a symmetric encryption KMS key, that is, a KMS key with a key spec value of SYMMETRIC_DEFAULT.

aws kms generate-data-key-without-plaintext \ --key-id "arn:aws:kms:us-west-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab" \ --key-spec AES_256

Output:

{ "CiphertextBlob": "AQEDAHjRYf5WytIc0C857tFSnBaPn2F8DgfmThbJlGfR8P3WlwAAAH4wfAYJKoZIhvcNAQcGoG8wbQIBADBoBgkqhkiG9w0BBwEwHgYJYIZIAWUDBAEuMBEEDEFogL", "KeyId": "arn:aws:kms:us-east-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab" }

The CiphertextBlob (encrypted data key) is returned in base64-encoded format.

For more information, see Data keys in the Amazon Key Management Service Developer Guide.

The following code example shows how to use generate-data-key.

Amazon CLI

Example 1: To generate a 256-bit symmetric data key

The following generate-data-key example requests a 256-bit symmetric data key for use outside of Amazon. The command returns a plaintext data key for immediate use and deletion, and a copy of that data key encrypted under the specified KMS key. You can safely store the encrypted data key with the encrypted data.

To request a 256-bit data key, use the key-spec parameter with a value of AES_256. To request a 128-bit data key, use the key-spec parameter with a value of AES_128. For all other data key lengths, use the number-of-bytes parameter.

The KMS key you specify must be a symmetric encryption KMS key, that is, a KMS key with a key spec value of SYMMETRIC_DEFAULT.

aws kms generate-data-key \ --key-id alias/ExampleAlias \ --key-spec AES_256

Output:

{ "Plaintext": "VdzKNHGzUAzJeRBVY+uUmofUGGiDzyB3+i9fVkh3piw=", "KeyId": "arn:aws:kms:us-east-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab", "CiphertextBlob": "AQEDAHjRYf5WytIc0C857tFSnBaPn2F8DgfmThbJlGfR8P3WlwAAAH4wfAYJKoZIhvcNAQcGoG8wbQIBADBoBgkqhkiG9w0BBwEwHgYJYIZIAWUDBAEuMBEEDEFogLqPWZconQhwHAIBEIA7d9AC7GeJJM34njQvg4Wf1d5sw0NIo1MrBqZa+YdhV8MrkBQPeac0ReRVNDt9qleAt+SHgIRF8P0H+7U=" }

The Plaintext (plaintext data key) and the CiphertextBlob (encrypted data key) are returned in base64-encoded format.

For more information, see Data keys <https://docs.aws.amazon.com/kms/latest/developerguide/concepts.html#data-keys in the Amazon Key Management Service Developer Guide.

Example 2: To generate a 512-bit symmetric data key

The following generate-data-key example requests a 512-bit symmetric data key for encryption and decryption. The command returns a plaintext data key for immediate use and deletion, and a copy of that data key encrypted under the specified KMS key. You can safely store the encrypted data key with the encrypted data.

To request a key length other than 128 or 256 bits, use the number-of-bytes parameter. To request a 512-bit data key, the following example uses the number-of-bytes parameter with a value of 64 (bytes).

The KMS key you specify must be a symmetric encryption KMS key, that is, a KMS key with a key spec value of SYMMETRIC_DEFAULT.

NOTE: The values in the output of this example are truncated for display.

aws kms generate-data-key \ --key-id 1234abcd-12ab-34cd-56ef-1234567890ab \ --number-of-bytes 64

Output:

{ "CiphertextBlob": "AQIBAHi6LtupRpdKl2aJTzkK6FbhOtQkMlQJJH3PdtHvS/y+hAEnX/QQNmMwDfg2korNMEc8AAACaDCCAmQGCSqGSIb3DQEHBqCCAlUwggJRAgEAMIICSgYJKoZ...", "Plaintext": "ty8Lr0Bk6OF07M2BWt6qbFdNB+G00ZLtf5MSEb4al3R2UKWGOp06njAwy2n72VRm2m7z/Pm9Wpbvttz6a4lSo9hgPvKhZ5y6RTm4OovEXiVfBveyX3DQxDzRSwbKDPk/...", "KeyId": "arn:aws:kms:us-west-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab" }

The Plaintext (plaintext data key) and CiphertextBlob (encrypted data key) are returned in base64-encoded format.

For more information, see Data keys <https://docs.aws.amazon.com/kms/latest/developerguide/concepts.html#data-keys in the Amazon Key Management Service Developer Guide.

The following code example shows how to use generate-random.

Amazon CLI

Example 1: To generate a 256-bit random byte string (Linux or macOs)

The following generate-random example generates a 256-bit (32-byte), base64-encoded random byte string. The example decodes the byte string and saves it in the random file.

When you run this command, you must use the number-of-bytes parameter to specify the length of the random value in bytes.

You don't specify a KMS key when you run this command. The random byte string is unrelated to any KMS key.

By default, Amazon KMS generates the random number. However, if you specify a custom key store<https://docs.aws.amazon.com/kms/latest/developerguide/custom-key-store-overview.html>, the random byte string is generated in the Amazon CloudHSM cluster associated with the custom key store.

This example uses the following parameters and values:

It uses the required --number-of-bytes parameter with a value of 32 to request a 32-byte (256-bit) string.It uses the --output parameter with a value of text to direct the Amazon CLI to return the output as text, instead of JSON.It uses the --query parameter to extract the value of the Plaintext property from the response.It pipes ( | ) the output of the command to the base64 utility, which decodes the extracted output.It uses the redirection operator ( > ) to save decoded byte string to the ExampleRandom file.It uses the redirection operator ( > ) to save the binary ciphertext to a file.

aws kms generate-random \ --number-of-bytes 32 \ --output text \ --query Plaintext | base64 --decode > ExampleRandom

This command produces no output.

For more information, see GenerateRandom in the Amazon Key Management Service API Reference.

Example 2: To generate a 256-bit random number (Windows Command Prompt)

The following example uses the generate-random command to generate a 256-bit (32-byte), base64-encoded random byte string. The example decodes the byte string and saves it in the random file. This example is the same as the previous example, except that it uses the certutil utility in Windows to base64-decode the random byte string before saving it in a file.

First, generate a base64-encoded random byte string and saves it in a temporary file, ExampleRandom.base64.

aws kms generate-random \ --number-of-bytes 32 \ --output text \ --query Plaintext > ExampleRandom.base64

Because the output of the generate-random command is saved in a file, this example produces no output.

Now use the certutil -decode command to decode the base64-encoded byte string in the ExampleRandom.base64 file. Then, it saves the decoded byte string in the ExampleRandom file.

certutil -decode ExampleRandom.base64 ExampleRandom

Output:

Input Length = 18 Output Length = 12 CertUtil: -decode command completed successfully.

For more information, see GenerateRandom in the Amazon Key Management Service API Reference.

  • For API details, see GenerateRandom in Amazon CLI Command Reference.

The following code example shows how to use get-key-policy.

Amazon CLI

To copy a key policy from one KMS key to another KMS key

The following get-key-policy example gets the key policy from one KMS key and saves it in a text file. Then, it replaces the policy of a different KMS key using the text file as the policy input.

Because the --policy parameter of put-key-policy requires a string, you must use the --output text option to return the output as a text string instead of JSON.

aws kms get-key-policy \ --policy-name default \ --key-id 1234abcd-12ab-34cd-56ef-1234567890ab \ --query Policy \ --output text > policy.txt aws kms put-key-policy \ --policy-name default \ --key-id 0987dcba-09fe-87dc-65ba-ab0987654321 \ --policy file://policy.txt

This command produces no output.

For more information, see PutKeyPolicy in the Amazon KMS API Reference.

  • For API details, see GetKeyPolicy in Amazon CLI Command Reference.

The following code example shows how to use get-key-rotation-status.

Amazon CLI

To retrieve the rotation status for a KMS key.

The following get-key-rotation-status example returns information about the rotation status of the specified KMS key, including whether automatic rotation is enabled, the rotation period, and the next scheduled rotation date. You can use this command on customer managed KMS keys and Amazon managed KMS keys. However, all Amazon managed KMS keys are automatically rotated every year.

aws kms get-key-rotation-status \ --key-id 1234abcd-12ab-34cd-56ef-1234567890ab

Output:

{ "KeyId": "1234abcd-12ab-34cd-56ef-1234567890ab", "KeyRotationEnabled": true, "NextRotationDate": "2024-02-14T18:14:33.587000+00:00", "RotationPeriodInDays": 365 }

For more information, see Rotating keys in the Amazon Key Management Service Developer Guide.

The following code example shows how to use get-parameters-for-import.

Amazon CLI

To get the items required to import key material into a KMS key

The following get-parameters-for-import example gets the public key and import token that you need to import key material into a KMS key. When you use the import-key-material command, be sure to use the import token and key material encrypted by the public key that were returned in the same get-parameters-for-import command. Also, the wrapping algorithm that you specify in this command must be one that you use to encrypt the key material with the public key.

To specify the KMS key, use the key-id parameter. This example uses an key ID, but you can use a key ID or key ARN in this command.

aws kms get-parameters-for-import \ --key-id 1234abcd-12ab-34cd-56ef-1234567890ab \ --wrapping-algorithm RSAES_OAEP_SHA_256 \ --wrapping-key-spec RSA_2048

Output:

{ "KeyId": "arn:aws:kms:us-west-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab", "PublicKey": "<public key base64 encoded data>", "ImportToken": "<import token base64 encoded data>", "ParametersValidTo": 1593893322.32 }

For more information, see Download the public key and import token in the Amazon Key Management Service Developer Guide.

The following code example shows how to use get-public-key.

Amazon CLI

Example 1: To download the public key of an asymmetric KMS key

The following get-public-key example downloads the public key of an asymmetric KMS key.

In addition to returning the public key, the output includes information that you need to use the public key safely outside of Amazon KMS, including the key usage and supported encryption algorithms.

aws kms get-public-key \ --key-id 1234abcd-12ab-34cd-56ef-1234567890ab

Output:

{ "KeyId": "arn:aws:kms:us-west-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab", "PublicKey": "jANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAl5epvg1/QtJhxSi2g9SDEVg8QV/...", "CustomerMasterKeySpec": "RSA_4096", "KeyUsage": "ENCRYPT_DECRYPT", "EncryptionAlgorithms": [ "RSAES_OAEP_SHA_1", "RSAES_OAEP_SHA_256" ] }

For more information about using asymmetric KMS keys in Amazon KMS, see Using Symmetric and Asymmetric Keys in the Amazon Key Management Service API Reference.

Example 2: To convert a public key to DER format (Linux and macOS)

The following get-public-key example downloads the public key of an asymmetric KMS key and saves it in a DER file.

When you use the get-public-key command in the Amazon CLI, it returns a DER-encoded X.509 public key that is Base64-encoded. This example gets the value of the PublicKey property as text. It Base64-decodes the PublicKey and saves it in the public_key.der file. The output parameter returns the output as text, instead of JSON. The --query parameter gets only the PublicKey property, not the properties that you need to use the public key safely outside of Amazon KMS.

Before running this command, replace the example key ID with a valid key ID from your Amazon account.

aws kms get-public-key \ --key-id 1234abcd-12ab-34cd-56ef-1234567890ab \ --output text \ --query PublicKey | base64 --decode > public_key.der

This command produces no output.

For more information about using asymmetric KMS keys in Amazon KMS, see Using Symmetric and Asymmetric Keys in the Amazon Key Management Service API Reference.

  • For API details, see GetPublicKey in Amazon CLI Command Reference.

The following code example shows how to use import-key-material.

Amazon CLI

To import key material into a KMS key

The following import-key-material example uploads key material into a KMS key that was created with no key material. The key state of the KMS key must be PendingImport.

This command uses key material that you encrypted with the public key that the get-parameters-for-import command returned. It also uses the import token from the same get-parameters-for-import command.

The expiration-model parameter indicates that the key material automatically expires on the date and time specified by the valid-to parameter. When the key material expires, Amazon KMS deletes the key material, the key state of the KMS key changes to Pending import and the KMS key becomes unusable. To restore the KMS key, you must reimport the same key material. To use different key material, you must create a new KMS key.

Before running this command, replace the example key ID with a valid key ID or key ARN from your Amazon account.

aws kms import-key-material \ --key-id 1234abcd-12ab-34cd-56ef-1234567890ab \ --encrypted-key-material fileb://EncryptedKeyMaterial.bin \ --import-token fileb://ImportToken.bin \ --expiration-model KEY_MATERIAL_EXPIRES \ --valid-to 2021-09-21T19:00:00Z

This command produces no output.

For more information about importing key material, see Importing Key Material in the Amazon Key Management Service Developer Guide.

The following code example shows how to use list-aliases.

Amazon CLI

Example 1: To list all aliases in an Amazon account and Region

The following example uses the list-aliases command to list all aliases in the default Region of the Amazon account. The output includes aliases associated with Amazon managed KMS keys and customer managed KMS keys.

aws kms list-aliases

Output:

{ "Aliases": [ { "AliasArn": "arn:aws:kms:us-west-2:111122223333:alias/testKey", "AliasName": "alias/testKey", "TargetKeyId": "1234abcd-12ab-34cd-56ef-1234567890ab" }, { "AliasArn": "arn:aws:kms:us-west-2:111122223333:alias/FinanceDept", "AliasName": "alias/FinanceDept", "TargetKeyId": "0987dcba-09fe-87dc-65ba-ab0987654321" }, { "AliasArn": "arn:aws:kms:us-west-2:111122223333:alias/aws/dynamodb", "AliasName": "alias/aws/dynamodb", "TargetKeyId": "1a2b3c4d-5e6f-1a2b-3c4d-5e6f1a2b3c4d" }, { "AliasArn": "arn:aws:kms:us-west-2:111122223333:alias/aws/ebs", "AliasName": "alias/aws/ebs", "TargetKeyId": "0987ab65-43cd-21ef-09ab-87654321cdef" }, ... ] }

Example 2: To list all aliases for a particular KMS key

The following example uses the list-aliases command and its key-id parameter to list all aliases that are associated with a particular KMS key.

Each alias is associated with only one KMS key, but a KMS key can have multiple aliases. This command is very useful because the Amazon KMS console lists only one alias for each KMS key. To find all aliases for a KMS key, you must use the list-aliases command.

This example uses the key ID of the KMS key for the --key-id parameter, but you can use a key ID, key ARN, alias name, or alias ARN in this command.

aws kms list-aliases --key-id 1234abcd-12ab-34cd-56ef-1234567890ab

Output:

{ "Aliases": [ { "TargetKeyId": "1234abcd-12ab-34cd-56ef-1234567890ab", "AliasArn": "arn:aws:kms:us-west-2:111122223333:alias/oregon-test-key", "AliasName": "alias/oregon-test-key" }, { "TargetKeyId": "1234abcd-12ab-34cd-56ef-1234567890ab", "AliasArn": "arn:aws:kms:us-west-2:111122223333:alias/project121-test", "AliasName": "alias/project121-test" } ] }

For more information, see Working with Aliases in the Amazon Key Management Service Developer Guide.

  • For API details, see ListAliases in Amazon CLI Command Reference.

The following code example shows how to use list-grants.

Amazon CLI

To view the grants on an Amazon KMS key

The following list-grants example displays all of the grants on the specified Amazon managed KMS key for Amazon DynamoDB in your account. This grant allows DynamoDB to use the KMS key on your behalf to encrypt a DynamoDB table before writing it to disk. You can use a command like this one to view the grants on the Amazon managed KMS keys and customer managed KMS keys in the Amazon account and Region.

This command uses the key-id parameter with a key ID to identify the KMS key. You can use a key ID or key ARN to identify the KMS key. To get the key ID or key ARN of an Amazon managed KMS key, use the list-keys or list-aliases command.

aws kms list-grants \ --key-id 1234abcd-12ab-34cd-56ef-1234567890ab

The output shows that the grant gives Amazon DynamoDB permission to use the KMS key for cryptographic operations, and gives it permission to view details about the KMS key (DescribeKey) and to retire grants (RetireGrant). The EncryptionContextSubset constraint limits these permission to requests that include the specified encryption context pairs. As a result, the permissions in the grant are effective only on specified account and DynamoDB table.

{ "Grants": [ { "Constraints": { "EncryptionContextSubset": { "aws:dynamodb:subscriberId": "123456789012", "aws:dynamodb:tableName": "Services" } }, "IssuingAccount": "arn:aws:iam::123456789012:root", "Name": "8276b9a6-6cf0-46f1-b2f0-7993a7f8c89a", "Operations": [ "Decrypt", "Encrypt", "GenerateDataKey", "ReEncryptFrom", "ReEncryptTo", "RetireGrant", "DescribeKey" ], "GrantId": "1667b97d27cf748cf05b487217dd4179526c949d14fb3903858e25193253fe59", "KeyId": "arn:aws:kms:us-west-2:123456789012:key/1234abcd-12ab-34cd-56ef-1234567890ab", "RetiringPrincipal": "dynamodb.us-west-2.amazonaws.com", "GranteePrincipal": "dynamodb.us-west-2.amazonaws.com", "CreationDate": "2021-05-13T18:32:45.144000+00:00" } ] }

For more information, see Grants in Amazon KMS in the Amazon Key Management Service Developer Guide.

  • For API details, see ListGrants in Amazon CLI Command Reference.

The following code example shows how to use list-key-policies.

Amazon CLI

To get the names of key policies for a KMS key

The following list-key-policies example gets the names of the key policies for a customer managed key in the example account and Region. You can use this command to find the names of key policies for Amazon managed keys and customer managed keys.

Because the only valid key policy name is default, this command is not useful.

To specify the KMS key, use the key-id parameter. This example uses a key ID value, but you can use a key ID or key ARN in this command.

aws kms list-key-policies \ --key-id 1234abcd-12ab-34cd-56ef-1234567890ab

Output:

{ "PolicyNames": [ "default" ] }

For more information about Amazon KMS key policies, see Using Key Policies in Amazon KMS in the Amazon Key Management Service Developer Guide.

The following code example shows how to use list-key-rotations.

Amazon CLI

To retrieve information about all completed key material rotations

The following list-key-rotations example lists information about all completed key material rotations for the specified KMS key.

aws kms list-key-rotations \ --key-id 1234abcd-12ab-34cd-56ef-1234567890ab

Output:

{ "Rotations": [ { "KeyId": "1234abcd-12ab-34cd-56ef-1234567890ab", "RotationDate": "2024-03-02T10:11:36.564000+00:00", "RotationType": "AUTOMATIC" }, { "KeyId": "1234abcd-12ab-34cd-56ef-1234567890ab", "RotationDate": "2024-04-05T15:14:47.757000+00:00", "RotationType": "ON_DEMAND" } ], "Truncated": false }

For more information, see Rotating keys in the Amazon Key Management Service Developer Guide.

The following code example shows how to use list-keys.

Amazon CLI

To get the KMS keys in an account and Region

The following list-keys example gets the KMS keys in an account and Region. This command returns both Amazon managed keys and customer managed keys.

aws kms list-keys

Output:

{ "Keys": [ { "KeyArn": "arn:aws:kms:us-west-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab", "KeyId": "1234abcd-12ab-34cd-56ef-1234567890ab" }, { "KeyArn": "arn:aws:kms:us-west-2:111122223333:key/0987dcba-09fe-87dc-65ba-ab0987654321", "KeyId": "0987dcba-09fe-87dc-65ba-ab0987654321" }, { "KeyArn": "arn:aws:kms:us-east-2:111122223333:key/1a2b3c4d-5e6f-1a2b-3c4d-5e6f1a2b3c4d", "KeyId": "1a2b3c4d-5e6f-1a2b-3c4d-5e6f1a2b3c4d" } ] }

For more information, see Viewing Keys in the Amazon Key Management Service Developer Guide.

  • For API details, see ListKeys in Amazon CLI Command Reference.

The following code example shows how to use list-resource-tags.

Amazon CLI

To get the tags on a KMS key

The following list-resource-tags example gets the tags for a KMS key. To add or replace resource tags on KMS keys, use the tag-resource command. The output shows that this KMS key has two resource tags, each of which has a key and value.

To specify the KMS key, use the key-id parameter. This example uses a key ID value, but you can use a key ID or key ARN in this command.

aws kms list-resource-tags \ --key-id 1234abcd-12ab-34cd-56ef-1234567890ab

Output:

{ "Tags": [ { "TagKey": "Dept", "TagValue": "IT" }, { "TagKey": "Purpose", "TagValue": "Test" } ], "Truncated": false }

For more information about using tags in Amazon KMS, see Tagging keys in the Amazon Key Management Service Developer Guide.

The following code example shows how to use list-retirable-grants.

Amazon CLI

To view the grants that a principal can retire

The following list-retirable-grants example displays all of the grants that the ExampleAdmin user can retire on the KMS keys in an Amazon account and Region. You can use a command like this one to view the grants that any account principal can retire on KMS keys in the Amazon account and Region.

The value of the required retiring-principal parameter must be the Amazon Resource Name (ARN) of an account, user, or role.

You cannot specify a service for the value of retiring-principal in this command, even though a service can be the retiring principal. To find the grants in which a particular service is the retiring principal, use the list-grants command.

The output shows that ExampleAdmin user has permission to retire grants on two different KMS keys in the account and region. In addition to the retiring principal, the account has permission to retire any grant in the account.

aws kms list-retirable-grants \ --retiring-principal arn:aws:iam::111122223333:user/ExampleAdmin

Output:

{ "Grants": [ { "KeyId": "arn:aws:kms:us-west-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab", "GrantId": "156b69c63cb154aa21f59929ff19760717be8d9d82b99df53e18b94a15a5e88e", "Name": "", "CreationDate": 2021-01-14T20:17:36.419000+00:00, "GranteePrincipal": "arn:aws:iam::111122223333:user/ExampleUser", "RetiringPrincipal": "arn:aws:iam::111122223333:user/ExampleAdmin", "IssuingAccount": "arn:aws:iam::111122223333:root", "Operations": [ "Encrypt" ], "Constraints": { "EncryptionContextSubset": { "Department": "IT" } } }, { "KeyId": "arn:aws:kms:us-west-2:111122223333:key/0987dcba-09fe-87dc-65ba-ab0987654321", "GrantId": "8c94d1f12f5e69f440bae30eaec9570bb1fb7358824f9ddfa1aa5a0dab1a59b2", "Name": "", "CreationDate": "2021-02-02T19:49:49.638000+00:00", "GranteePrincipal": "arn:aws:iam::111122223333:role/ExampleRole", "RetiringPrincipal": "arn:aws:iam::111122223333:user/ExampleAdmin", "IssuingAccount": "arn:aws:iam::111122223333:root", "Operations": [ "Decrypt" ], "Constraints": { "EncryptionContextSubset": { "Department": "IT" } } } ], "Truncated": false }

For more information, see Grants in Amazon KMS in the Amazon Key Management Service Developer Guide.

The following code example shows how to use put-key-policy.

Amazon CLI

To change the key policy for a KMS key

The following put-key-policy example changes the key policy for a customer managed key.

To begin, create a key policy and save it in a local JSON file. In this example, the file is key_policy.json. You can also specify the key policy as a string value of the policy parameter.

The first statement in this key policy gives the Amazon account permission to use IAM policies to control access to the KMS key. The second statement gives the test-user user permission to run the describe-key and list-keys commands on the KMS key.

Contents of key_policy.json:

{ "Version" : "2012-10-17", "Id" : "key-default-1", "Statement" : [ { "Sid" : "Enable IAM User Permissions", "Effect" : "Allow", "Principal" : { "AWS" : "arn:aws:iam::111122223333:root" }, "Action" : "kms:*", "Resource" : "*" }, { "Sid" : "Allow Use of Key", "Effect" : "Allow", "Principal" : { "AWS" : "arn:aws:iam::111122223333:user/test-user" }, "Action" : [ "kms:DescribeKey", "kms:ListKeys" ], "Resource" : "*" } ] }

To identify the KMS key, this example uses the key ID, but you can also use a key ARN. To specify the key policy, the command uses the policy parameter. To indicate that the policy is in a file, it uses the required file:// prefix. This prefix is required to identify files on all supported operating systems. Finally, the command uses the policy-name parameter with a value of default. If no policy name is specified, the default value is default. The only valid value is default.

aws kms put-key-policy \ --policy-name default \ --key-id 1234abcd-12ab-34cd-56ef-1234567890ab \ --policy file://key_policy.json

This command does not produce any output. To verify that the command was effective, use the get-key-policy command. The following example command gets the key policy for the same KMS key. The output parameter with a value of text returns a text format that is easy to read.

aws kms get-key-policy \ --policy-name default \ --key-id 1234abcd-12ab-34cd-56ef-1234567890ab \ --output text

Output:

{ "Version" : "2012-10-17", "Id" : "key-default-1", "Statement" : [ { "Sid" : "Enable IAM User Permissions", "Effect" : "Allow", "Principal" : { "AWS" : "arn:aws:iam::111122223333:root" }, "Action" : "kms:*", "Resource" : "*" }, { "Sid" : "Allow Use of Key", "Effect" : "Allow", "Principal" : { "AWS" : "arn:aws:iam::111122223333:user/test-user" }, "Action" : [ "kms:Describe", "kms:List" ], "Resource" : "*" } ] }

For more information, see Changing a Key Policy in the Amazon Key Management Service Developer Guide.

  • For API details, see PutKeyPolicy in Amazon CLI Command Reference.

The following code example shows how to use re-encrypt.

Amazon CLI

Example 1: To re-encrypt an encrypted message under a different symmetric KMS key (Linux and macOS).

The following re-encrypt command example demonstrates the recommended way to re-encrypt data with the Amazon CLI.

Provide the ciphertext in a file.In the value of the --ciphertext-blob parameter, use the fileb:// prefix, which tells the CLI to read the data from a binary file. If the file is not in the current directory, type the full path to file. For more information about reading Amazon CLI parameter values from a file, see Loading Amazon CLI parameters from a file <https://docs.aws.amazon.com/cli/latest/userguide/cli-usage-parameters-file.html> in the Amazon Command Line Interface User Guide and Best Practices for Local File Parameters<https://aws.amazon.com/blogs/developer/best-practices-for-local-file-parameters/> in the Amazon Command Line Tool Blog.Specify the source KMS key, which decrypts the ciphertext.The --source-key-id parameter is not required when decrypting with symmetric encryption KMS keys. Amazon KMS can get the KMS key that was used to encrypt the data from the metadata in the ciphertext blob. But it's always a best practice to specify the KMS key you are using. This practice ensures that you use the KMS key that you intend, and prevents you from inadvertently decrypting a ciphertext using a KMS key you do not trust.Specify the destination KMS key, which re-encrypts the data.The --destination-key-id parameter is always required. This example uses a key ARN, but you can use any valid key identifier.Request the plaintext output as a text value.The --query parameter tells the CLI to get only the value of the Plaintext field from the output. The --output parameter returns the output as text.Base64-decode the plaintext and save it in a file.The following example pipes (|) the value of the Plaintext parameter to the Base64 utility, which decodes it. Then, it redirects (>) the decoded output to the ExamplePlaintext file.

Before running this command, replace the example key IDs with valid key identifiers from your Amazon account.

aws kms re-encrypt \ --ciphertext-blob fileb://ExampleEncryptedFile \ --source-key-id 1234abcd-12ab-34cd-56ef-1234567890ab \ --destination-key-id 0987dcba-09fe-87dc-65ba-ab0987654321 \ --query CiphertextBlob \ --output text | base64 --decode > ExampleReEncryptedFile

This command produces no output. The output from the re-encrypt command is base64-decoded and saved in a file.

For more information, see ReEncrypt <https://docs.aws.amazon.com/kms/latest/APIReference/API_ReEncrypt.html in the Amazon Key Management Service API Reference.

Example 2: To re-encrypt an encrypted message under a different symmetric KMS key (Windows command prompt).

The following re-encrypt command example is the same as the previous one except that it uses the certutil utility to Base64-decode the plaintext data. This procedure requires two commands, as shown in the following examples.

Before running this command, replace the example key ID with a valid key ID from your Amazon account.

aws kms re-encrypt ^ --ciphertext-blob fileb://ExampleEncryptedFile ^ --source-key-id 1234abcd-12ab-34cd-56ef-1234567890ab ^ --destination-key-id 0987dcba-09fe-87dc-65ba-ab0987654321 ^ --query CiphertextBlob ^ --output text > ExampleReEncryptedFile.base64

Then use the certutil utility

certutil -decode ExamplePlaintextFile.base64 ExamplePlaintextFile

Output:

Input Length = 18 Output Length = 12 CertUtil: -decode command completed successfully.

For more information, see ReEncrypt <https://docs.aws.amazon.com/kms/latest/APIReference/API_ReEncrypt.html in the Amazon Key Management Service API Reference.

  • For API details, see ReEncrypt in Amazon CLI Command Reference.

The following code example shows how to use retire-grant.

Amazon CLI

To retire a grant on a customer master key

The following retire-grant example deletes a grant from a KMS key.

The following example command specifies the grant-id and the key-id parameters. The value of the key-id parameter must be the key ARN of the KMS key.

aws kms retire-grant \ --grant-id 1234a2345b8a4e350500d432bccf8ecd6506710e1391880c4f7f7140160c9af3 \ --key-id arn:aws:kms:us-west-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab

This command produces no output. To confirm that the grant was retired, use the list-grants command.

For more information, see Retiring and revoking grants in the Amazon Key Management Service Developer Guide.

  • For API details, see RetireGrant in Amazon CLI Command Reference.

The following code example shows how to use revoke-grant.

Amazon CLI

To revoke a grant on a customer master key

The following revoke-grant example deletes a grant from a KMS key. The following example command specifies the grant-id and the key-id parameters. The value of the key-id parameter can be the key ID or key ARN of the KMS key.

aws kms revoke-grant \ --grant-id 1234a2345b8a4e350500d432bccf8ecd6506710e1391880c4f7f7140160c9af3 \ --key-id 1234abcd-12ab-34cd-56ef-1234567890ab

This command produces no output. To confirm that the grant was revoked, use the list-grants command.

For more information, see Retiring and revoking grants in the Amazon Key Management Service Developer Guide.

  • For API details, see RevokeGrant in Amazon CLI Command Reference.

The following code example shows how to use rotate-key-on-demand.

Amazon CLI

To perform on-demand rotation of a KMS key

The following rotate-key-on-demand example immediately initiates rotation of the key material for the specified KMS key.

aws kms rotate-key-on-demand \ --key-id 1234abcd-12ab-34cd-56ef-1234567890ab

Output:

{ "KeyId": "1234abcd-12ab-34cd-56ef-1234567890ab" }

For more information, see How to perform on-demand key rotation in the Amazon Key Management Service Developer Guide.

The following code example shows how to use schedule-key-deletion.

Amazon CLI

To schedule the deletion of a customer managed KMS key.

The following schedule-key-deletion example schedules the specified customer managed KMS key to be deleted in 15 days.

The --key-id parameter identifies the KMS key. This example uses a key ARN value, but you can use either the key ID or the ARN of the KMS key.The --pending-window-in-days parameter specifies the length of the 7-30 day waiting period. By default, the waiting period is 30 days. This example specifies a value of 15, which tells Amazon to permanently delete the KMS key 15 days after the command completes.

aws kms schedule-key-deletion \ --key-id arn:aws:kms:us-west-2:123456789012:key/1234abcd-12ab-34cd-56ef-1234567890ab \ --pending-window-in-days 15

The response includes the key ARN, key state, waiting period (PendingWindowInDays), and the deletion date in Unix time. To view the deletion date in local time, use the Amazon KMS console. KMS keys in the PendingDeletion key state cannot be used in cryptographic operations.

{ "KeyId": "arn:aws:kms:us-west-2:123456789012:key/1234abcd-12ab-34cd-56ef-1234567890ab", "DeletionDate": "2022-06-18T23:43:51.272000+00:00", "KeyState": "PendingDeletion", "PendingWindowInDays": 15 }

For more information, see Deleting keys in the Amazon Key Management Service Developer Guide.

The following code example shows how to use sign.

Amazon CLI

Example 1: To generate a digital signature for a message

The following sign example generates a cryptographic signature for a short message. The output of the command includes a base-64 encoded Signature field that you can verify by using the verify command.

You must specify a message to sign and a signing algorithm that your asymmetric KMS key supports. To get the signing algorithms for your KMS key, use the describe-key command.

In Amazon CLI 2.0, the value of the message parameter must be Base64-encoded. Or, you can save the message in a file and use the fileb:// prefix, which tells the Amazon CLI to read binary data from the file.

Before running this command, replace the example key ID with a valid key ID from your Amazon account. The key ID must represent an asymmetric KMS key with a key usage of SIGN_VERIFY.

msg=(echo 'Hello World' | base64) aws kms sign \ --key-id 1234abcd-12ab-34cd-56ef-1234567890ab \ --message fileb://UnsignedMessage \ --message-type RAW \ --signing-algorithm RSASSA_PKCS1_V1_5_SHA_256

Output:

{ "KeyId": "arn:aws:kms:us-west-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab", "Signature": "ABCDEFhpyVYyTxbafE74ccSvEJLJr3zuoV1Hfymz4qv+/fxmxNLA7SE1SiF8lHw80fKZZ3bJ...", "SigningAlgorithm": "RSASSA_PKCS1_V1_5_SHA_256" }

For more information about using asymmetric KMS keys in Amazon KMS, see Asymmetric keys in Amazon KMS in the Amazon Key Management Service Developer Guide.

Example 2: To save a digital signature in a file (Linux and macOs)

The following sign example generates a cryptographic signature for a short message stored in a local file. The command also gets the Signature property from the response, Base64-decodes it and saves it in the ExampleSignature file. You can use the signature file in a verify command that verifies the signature.

The sign command requires a Base64-encoded message and a signing algorithm that your asymmetric KMS key supports. To get the signing algorithms that your KMS key supports, use the describe-key command.

Before running this command, replace the example key ID with a valid key ID from your Amazon account. The key ID must represent an asymmetric KMS key with a key usage of SIGN_VERIFY.

echo 'hello world' | base64 > EncodedMessage aws kms sign \ --key-id 1234abcd-12ab-34cd-56ef-1234567890ab \ --message fileb://EncodedMessage \ --message-type RAW \ --signing-algorithm RSASSA_PKCS1_V1_5_SHA_256 \ --output text \ --query Signature | base64 --decode > ExampleSignature

This command produces no output. This example extracts the Signature property of the output and saves it in a file.

For more information about using asymmetric KMS keys in Amazon KMS, see Asymmetric keys in Amazon KMS in the Amazon Key Management Service Developer Guide.

  • For API details, see Sign in Amazon CLI Command Reference.

The following code example shows how to use tag-resource.

Amazon CLI

To add a tag to a KMS key

The following tag-resource example adds "Purpose":"Test" and "Dept":"IT" tags to a customer managed KMS key. You can use tags like these to label KMS keys and create categories of KMS keys for permissions and auditing.

To specify the KMS key, use the key-id parameter. This example uses a key ID value, but you can use a key ID or key ARN in this command.

aws kms tag-resource \ --key-id 1234abcd-12ab-34cd-56ef-1234567890ab \ --tags TagKey='Purpose',TagValue='Test' TagKey='Dept',TagValue='IT'

This command produces no output. To view the tags on an Amazon KMS KMS key, use the list-resource-tags command.

For more information about using tags in Amazon KMS, see Tagging keys in the Amazon Key Management Service Developer Guide.

  • For API details, see TagResource in Amazon CLI Command Reference.

The following code example shows how to use untag-resource.

Amazon CLI

To delete a tag from a KMS key

The following untag-resource example deletes the tag with the "Purpose" key from a customer managed KMS key.

To specify the KMS key, use the key-id parameter. This example uses a key ID value, but you can use a key ID or key ARN in this command. Before running this command, replace the example key ID with a valid key ID from your Amazon account.

aws kms untag-resource \ --key-id 1234abcd-12ab-34cd-56ef-1234567890ab \ --tag-key 'Purpose'

This command produces no output. To view the tags on an Amazon KMS KMS key, use the list-resource-tags command.

For more information about using tags in Amazon KMS, see Tagging keys in the Amazon Key Management Service Developer Guide.

  • For API details, see UntagResource in Amazon CLI Command Reference.

The following code example shows how to use update-alias.

Amazon CLI

To associate an alias with a different KMS key

The following update-alias example associates the alias alias/test-key with a different KMS key.

The --alias-name parameter specifies the alias. The alias name value must begin with alias/.The --target-key-id parameter specifies the KMS key to associate with the alias. You don't need to specify the current KMS key for the alias.

aws kms update-alias \ --alias-name alias/test-key \ --target-key-id 1234abcd-12ab-34cd-56ef-1234567890ab

This command produces no output. To find the alias, use the list-aliases command.

For more information, see Updating aliases in the Amazon Key Management Service Developer Guide.

  • For API details, see UpdateAlias in Amazon CLI Command Reference.

The following code example shows how to use update-custom-key-store.

Amazon CLI

Example 1: To edit the friendly name of a custom key store

The following update-custom-key-store example changes the name of the custom key store. This example works for an Amazon CloudHSM key store or an external key store.

Use the custom-key-store-id to identify the key store. Use the new-custom-key-store-name parameter to specify the new friendly name.

To update the friendly name of an Amazon CloudHSM key store, you must first disconnect the key store, such as by using the disconnect-custom-key-store command. You can update the friendly name of an external key store while it is connected or disconnected. To find the connection state of your custom key store, use the describe-custom-key-store command.

aws kms update-custom-key-store \ --custom-key-store-id cks-1234567890abcdef0 \ --new-custom-key-store-name ExampleKeyStore

This command does not return any data. To verify that the command worked, use a describe-custom-key-stores command.

For more information about updating an Amazon CloudHSM key store, see Editing Amazon CloudHSM key store settings in the Amazon Key Management Service Developer Guide.

For more information about updating an external key store, see Editing external key store properties in the Amazon Key Management Service Developer Guide.

Example 2: To edit the kmsuser password of an Amazon CloudHSM key store

The following update-custom-key-store example updates the value of the kmsuser password to the current password for the kmsuser in the CloudHSM cluster associated with the specified key store. This command doesn't change the kmsuser password it the cluster. It just tells Amazon KMS the current password. If KMS doesn't have the current kmsuser password, it cannot connect to the Amazon CloudHSM key store.

NOTE: Before updating an Amazon CloudHSM key store, you must disconnect it. Use the disconnect-custom-key-store command. After the command completes, you can reconnect the Amazon CloudHSM key store. Use the connect-custom-key-store command.

aws kms update-custom-key-store \ --custom-key-store-id cks-1234567890abcdef0 \ --key-store-password ExamplePassword

This command does not return any output. To verify that the change was effective, use a describe-custom-key-stores command.

For more information about updating an Amazon CloudHSM key store, see Editing Amazon CloudHSM key store settings in the Amazon Key Management Service Developer Guide.

Example 3: To edit the Amazon CloudHSM cluster of an Amazon CloudHSM key store

The following example changes the Amazon CloudHSM cluster that is associated with an Amazon CloudHSM key store to a related cluster, such as a different backup of the same cluster.

NOTE: Before updating an Amazon CloudHSM key store, you must disconnect it. Use the disconnect-custom-key-store command. After the command completes, you can reconnect the Amazon CloudHSM key store. Use the connect-custom-key-store command.

aws kms update-custom-key-store \ --custom-key-store-id cks-1234567890abcdef0 \ --cloud-hsm-cluster-id cluster-1a23b4cdefg

This command does not return any output. To verify that the change was effective, use a describe-custom-key-stores command.

For more information about updating an Amazon CloudHSM key store, see Editing Amazon CloudHSM key store settings in the Amazon Key Management Service Developer Guide.

Example 4: To edit the proxy authentication credential of an external key store

The following example updates the proxy authentication credential for your external key store. You must specify both the raw-secret-access-key and the access-key-id, even if you are changing only one of the values. You can use this feature to fix an invalid credential or to change the credential when the external key store proxy rotates it.

Establish the proxy authentication credential for Amazon KMS on your external key store. Then use this command to provide the credential to Amazon KMS. Amazon KMS uses this credential to sign its requests to your external key store proxy.

You can update the proxy authentication credential while the external key store is connected or disconnected. To find the connection state of your custom key store, use the describe-custom-key-store command.

aws kms update-custom-key-store \ --custom-key-store-id cks-1234567890abcdef0 \ --xks-proxy-authentication-credential "AccessKeyId=ABCDE12345670EXAMPLE, RawSecretAccessKey=DXjSUawnel2fr6SKC7G25CNxTyWKE5PF9XX6H/u9pSo="

This command does not return any output. To verify that the change was effective, use a describe-custom-key-stores command.

For more information about updating an external key store, see Editing external key store properties in the Amazon Key Management Service Developer Guide.

Example 5: To edit the proxy connectivity of an external key store

The following example changes the external key store proxy connectivity option from public endpoint connectivity to VPC endpoint service connectivity. In addition to changing the xks-proxy-connectivity value, you must change the xks-proxy-uri-endpoint value to reflect the private DNS name associated with the VPC endpoint service. You must also add an xks-proxy-vpc-endpoint-service-name value.

NOTE: Before updating the proxy connectivity of an external store, you must disconnect it. Use the disconnect-custom-key-store command. After the command completes, you can reconnect the external key store by using the connect-custom-key-store command.

aws kms update-custom-key-store \ --custom-key-store-id cks-1234567890abcdef0 \ --xks-proxy-connectivity VPC_ENDPOINT_SERVICE \ --xks-proxy-uri-endpoint "https://myproxy-private.xks.example.com" \ --xks-proxy-vpc-endpoint-service-name "com.amazonaws.vpce.us-east-1.vpce-svc-example"

This command does not return any output. To verify that the change was effective, use a describe-custom-key-stores command.

For more information about updating an external key store, see Editing external key store properties in the Amazon Key Management Service Developer Guide.

The following code example shows how to use update-key-description.

Amazon CLI

Example 1: To add or change a description to a customer managed KMS key

The following update-key-description example adds a description to a customer managed KMS key. You can use the same command to change an existing description.

The --key-id parameter identifies the KMS key in the command. This example uses a key ARN value, but you can use either the key ID or the key ARN of the KMS key.The --description parameter specifies the new description. The value of this parameter replaces the current description of the KMS key, if any.

aws kms update-key-description \ --key-id arn:aws:kms:us-west-2:123456789012:key/1234abcd-12ab-34cd-56ef-1234567890ab \ --description "IT Department test key"

This command produces no output. To view the description of a KMS key, use the describe-key command.

For more information, see UpdateKeyDescription in the Amazon Key Management Service API Reference.

Example 2: To delete the description of a customer managed KMS key

The following update-key-description example deletes the description to a customer managed KMS key.

The --key-id parameter identifies the KMS key in the command. This example uses a key ID value, but you can use either the key ID or the key ARN of the KMS key.The --description parameter with an empty string value ('') deletes the existing description.

aws kms update-key-description \ --key-id 0987dcba-09fe-87dc-65ba-ab0987654321 \ --description ''

This command produces no output. To view the description of a KMS key, use the the describe-key command.

For more information, see UpdateKeyDescription in the Amazon Key Management Service API Reference.

The following code example shows how to use verify.

Amazon CLI

To verify a digital signature

The following verify example verifies a cryptographic signature for a short, Base64-encoded message. The key ID, message, message type, and signing algorithm must be same ones that were used to sign the message. The signature that you specify cannot be base64-encoded. For help decoding the signature that the sign command returns, see the sign command examples.

The output of the command includes a Boolean SignatureValid field that indicates that the signature was verified. If the signature validation fails, the verify command fails, too.

Before running this command, replace the example key ID with a valid key ID from your Amazon account.

aws kms verify \ --key-id 1234abcd-12ab-34cd-56ef-1234567890ab \ --message fileb://EncodedMessage \ --message-type RAW \ --signing-algorithm RSASSA_PKCS1_V1_5_SHA_256 \ --signature fileb://ExampleSignature

Output:

{ "KeyId": "arn:aws:kms:us-west-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab", "SignatureValid": true, "SigningAlgorithm": "RSASSA_PKCS1_V1_5_SHA_256" }

For more information about using asymmetric KMS keys in Amazon KMS, see Using asymmetric keys in the Amazon Key Management Service Developer Guide.

  • For API details, see Verify in Amazon CLI Command Reference.