AWS KMS API Guide

Use Chilkat with AWS Key Management Service to encrypt data, sign documents and messages, manage key access, import key material, and control key lifecycles. This guide connects 63 complete examples, from a first encrypted message to envelope encryption, post-quantum operations, and multi-Region key management.

Before making requests

The examples require Chilkat 11.6.0 or later and an unlocked library. Direct API examples use Chilkat.Rest and AuthAws with a regional endpoint such as kms.us-west-2.amazonaws.com. Configure the region for the intended key. Other AWS partitions, FIPS endpoints, and dual-stack endpoints require their documented endpoint configuration. Replace illustrative identifiers and local paths, and create output directories before running file-writing examples.

Read credentials from private qa_data/aws/kms.json, with nonempty strings access_key and secret_key, plus session_token for temporary credentials. Prefer short-lived role credentials. The examples read this file; they do not discover profiles, assume roles, or refresh credentials. Where required, set key_id to the intended fixed key ARN. Each example describes additional fields and input files. Keep credentials, private keys, plaintext, and full signing diagnostics outside public web content and source control.

How the examples call KMS

Direct API requests and convenience methods
StepChilkat configuration
Sign a direct requestSet AuthAws.ServiceName="kms", the matching region, credentials, and SignatureVersion=4. Attach it with Rest.SetAuthAws.
Send the operationUse POST /, Content-Type: application/x-amz-json-1.1, and an X-Amz-Target such as TrentService.Encrypt. Build the JSON body with JsonObject, then call FullRequestString.
Use temporary credentialsThe Rest examples clear previous query parameters and add X-Amz-Security-Token to the signed query on every request. Keep request URLs private. The token is not an operation field in the JSON body.
Check the responseA Socket explicitly verifies the TLS certificate before supplying the connection to Rest. Check transport completion, HTTP status, JSON parsing where a response body is expected, and operation-specific fields. Some successful mutations have an empty body.
Use cloud helpersCert.SetCloudSigner configures remote document signing; PrivateKey.UploadToCloud imports into a newly created key. Their configuration and credential limitations are described in the document-signing and import sections.

KMS uses a JSON protocol; do not copy the Action/Version form fields from AWS Query API examples. Binary request and response values are base64 in JSON. Preserve capitalization, use raw values before JSON serialization, and rebuild the request when changing operations. See the AWS KMS API introduction, Rest reference, and AuthAws reference.

Key Inventory

Start with ListKeys for IDs and ARNs, then DescribeKey for state, origin, specification and usage. ListAliases maps names to target key IDs; a predefined AWS alias may have no target yet. Tags provide application metadata. These listings operate in the selected account and region, not across the entire organization.

The paginated examples follow Truncated and NextMarker, including after empty pages. Markers are opaque. Repetition or a reached page bound produces an incomplete-result message. Changing inventory is not an atomic snapshot. See ListKeys and DescribeKey.

GetKeyLastUsage includes a tracking start time. An empty usage result does not prove an older key was never used. Multi-Region members track usage independently. Review application dependencies and CloudTrail before lifecycle decisions.

Creation, Aliases, and Metadata

Select the key specification and usage for the application: SYMMETRIC_DEFAULT with ENCRYPT_DECRYPT, RSA with SIGN_VERIFY, or HMAC with GENERATE_VERIFY_MAC. The creation examples use KMS-generated material. External-origin and multi-Region creation appear in their own sections.

CreateKey can create another key each time it runs. Record the returned ARN and reconcile an uncertain response before retrying. The examples omit an explicit policy to request the API default, then leave policy review to a separate workflow. Tags and descriptions are visible metadata; avoid secrets. See CreateKey.

Customer aliases begin with alias/; alias/aws/ is reserved. Updating an alias changes future alias-based requests and requires an eligible target in the same account and region. Deleting an alias does not delete its key. Use a fixed key ARN when a workflow must not follow alias retargeting. Tag changes can affect attribute-based authorization.

Encryption and ReEncryption

The direct encryption examples use a symmetric key and a nonsecret context, Application=ChilkatKmsExamples. The UTF-8 or binary plaintext must fit the 4096-byte symmetric Encrypt limit. Decrypt supplies the expected key ARN and the exact, case-sensitive original context. An incorrect context is a failure; do not retry by dropping it. Asymmetric encryption has different algorithms and smaller limits and is outside these direct-encryption examples. See Encrypt.

ReEncrypt moves a ciphertext to a selected destination key and context without returning plaintext to the application. Set destination_key_id to its ARN. The example changes the destination context to Application=ChilkatKmsExamplesV2; use that new context for later decryption. Authorization requires kms:ReEncryptFrom on the source and kms:ReEncryptTo on the destination. See ReEncrypt.

Data Keys and Envelope Encryption

Use envelope encryption for files that exceed the direct Encrypt limit. GenerateDataKey returns both a plaintext data key for local cryptography and a KMS-encrypted copy to retain with the ciphertext. GenerateDataKeyWithoutPlaintext returns only the encrypted copy; a separately authorized consumer can later call Decrypt to recover it. Never print or store the plaintext key alongside the envelope. See GenerateDataKey.

The paired file examples use a fresh AES-256 key, a random 96-bit GCM nonce, a 128-bit authentication tag, and fixed authenticated context. The envelope stores the encrypted data key and nonsecret parameters. Decryption checks the configured key ARN and expected context, then writes plaintext only after GCM authentication succeeds. Never reuse a nonce with the same key.

Use the paired envelope format. These examples define a teaching format, not the AWS Encryption SDK format. They load the file in memory. Clearing a binary buffer does not guarantee that copies held in strings, JSON objects, or runtime memory have been erased.

Signatures and HMAC

For a compatible asymmetric SIGN_VERIFY key, Sign accepts a raw message or a digest. The RSA examples use SHA-256: RAW lets KMS hash a message of up to 4096 bytes, while DIGEST sends a locally computed digest of a potentially larger message. Keep the same message type and algorithm for Verify; do not hash a digest again unintentionally. Check returned key identifiers and algorithms. See Sign.

GetPublicKey returns a DER SubjectPublicKeyInfo key. The local RSA and ECDSA examples obtain it through the authenticated KMS endpoint for the selected key, then verify locally. ECDSA signatures are ASN.1 DER. The ML-DSA example uses ML_DSA_65, ML_DSA_SHAKE_256, and RAW, with both Sign and Verify in KMS. Its EXTERNAL_MU alternative requires an algorithm-specific representative; it is not an ordinary SHA-256 digest.

HMAC uses a GENERATE_VERIFY_MAC key. GenerateMac and VerifyMac both require access to that secret key; there is no downloadable public verification key. Verification exceptions or false result flags mean failure. Applications must provide freshness and replay protection where needed. See GenerateMac.

PDF, XML, and CAdES Signing

Load the public certificate locally and configure its matching KMS private key through Cert.SetCloudSigner. The key must be an enabled compatible RSA or NIST EC signing key, and the caller needs permission to sign. Chilkat builds the PDF, XMLDSig, or attached CAdES-BES file locally and sends the digest for remote signing.

The PDF example does not claim a trusted timestamp or LTV evidence. The SOAP example signs the Body using SHA-256 and verifies its reference and signature before saving; it creates XMLDSig, not XAdES, and does not cover unsigned headers. The CAdES example creates an attached .p7m with SHA-256 and signingCertificateV2. Signature validity alone does not establish certificate trust or revocation status.

Credential scope of the convenience examples: the three document-signing examples and the UploadToCloud import example configure an access-key/secret-key pair. They explicitly reject a supplied session token because token support for those helper configurations has not been established in these examples. This is a sample limitation, not a claim about all library capabilities. The direct Rest examples support temporary credentials.

SetCloudSigner uses service value aws_kms with an underscore. Check its result before attempting document signing. See the SetCloudSigner reference.

ECDH and ML-KEM

The ECDH example uses a NIST P-256 KEY_AGREEMENT key, a fresh local peer key, and DeriveSharedSecret. It obtains the KMS public key through the authenticated endpoint, compares the two peers' results, and applies HKDF-SHA256 with a public salt and context. A production exchange must authenticate remote public keys and bind identities and the protocol transcript into its key derivation. See DeriveSharedSecret.

The post-quantum example uses an ML_KEM_768 key with ENCAPSULATE_DECAPSULATE usage. Encapsulate returns a shared secret and its encapsulated form; Decapsulate recovers the secret. Both operations run in KMS, so the example assumes no local Chilkat ML-KEM implementation. Use an authenticated application protocol and appropriate key derivation. Check regional availability; Encapsulate is unavailable in China Regions. See Encapsulate.

Policies and Grants

Key policies, IAM permissions, and grants participate in authorization. ListKeyPolicies and GetKeyPolicy retrieve the policy names and the JSON-encoded policy string. The update example reads a separately reviewed replacement file, backs up the existing policy, and leaves BypassPolicyLockoutSafetyCheck=false. JSON validation is not a security review. Preserve administrative access, review every principal and action, and coordinate writers because policy replacement has no optimistic concurrency check. See PutKeyPolicy.

The constrained grant allows only Decrypt with the exact sample context. Set grantee_principal to an existing intended IAM principal. Save its GrantId and GrantToken privately. The grantee uses its own AWS credentials and can supply GrantTokens before the grant has fully propagated. A grant token is neither an identity credential nor permission for an unrelated caller. See CreateGrant.

Use the paginated grant listings to inspect grants on a key or grants a principal can retire. RevokeGrant is administrative removal; RetireGrant is the eligible principal's retirement workflow. Their authorization requirements differ, and removal can take time to propagate.

Import and Reimport

For explicit asymmetric import, first create an EXTERNAL signing key with the specification matching the PFX private key. The low-level example checks PendingImport, usage and specification, then pins the ARN. It exports PKCS#8 only in memory and obtains a linked wrapping key/token pair. The hybrid payload places the RSA-OAEP-SHA256-wrapped AES key before the AES-wrapped private key. Use both import parameters before their expiration; hybrid RSA/AES wrapping is unavailable in China Regions. See GetParametersForImport.

The convenience PrivateKey.UploadToCloud example uses service value aws-kms with a hyphen and creates a new KMS key. Rerunning can create additional keys. The explicit examples operate on the selected existing key. PFX examples read pfx_password from private configuration. Keep a protected original backup; imported private material cannot be exported from KMS.

The expiring example sets a 30-day material lifetime, distinct from the wrapping-token lifetime. Asymmetric reimport must use the same original material; it omits ImportType, which applies to symmetric encryption keys. Symmetric rotation preparation imports a backed-up 32-byte file, using NEW_KEY_MATERIAL on the primary and EXISTING_KEY_MATERIAL for the same material in each replica. Record the material identifier. See ImportKeyMaterial.

Material deletion can make data inaccessible. The separate deletion example selects one imported symmetric material identifier. It does not delete the KMS key. Recovery depends on retaining the original bytes and being able to reimport them under the applicable key and material rules.

Key Rotation

Automatic rotation examples target an enabled customer-managed symmetric encryption key with AWS_KMS origin. The enable example chooses 180 days. Automatic rotation is not supported for asymmetric, HMAC, imported, or custom-key-store keys; configure a multi-Region set through its primary. See EnableKeyRotation.

On-demand rotation is a separate request and does not change the automatic schedule. The examples distinguish KMS-generated material from imported symmetric material. For the latter, prepare PENDING_ROTATION material; for multi-Region keys, import the same new material in every replica first. Acceptance is not completion. Inspect GetKeyRotationStatus and ListKeyRotations after propagation. The listing uses ALL_KEY_MATERIAL to include initial and pending material as well as completed rotations. See RotateKeyOnDemand and ListKeyRotations.

Multi-Region Keys

Create a multi-Region primary, then replicate it to another enabled region in the same partition. Related keys share key material and key ID, but policies, grants, aliases and tags are regional settings. Inspect each replica at its own endpoint. External-origin replicas need the matching material imported separately. See ReplicateKey.

UpdatePrimaryRegion promotes an existing replica and demotes the old primary. It does not create a new replica. The example verifies that the requested region appears in the current replica list. Allow the transient Updating state to settle before subsequent management operations, and ensure permissions on both affected keys. See UpdatePrimaryRegion.

Enable, Disable, and Delete

EnableKey and DisableKey are explicit state changes on a selected customer-managed key. Disabling can interrupt applications that depend on it. DescribeKey preflight checks help catch a wrong target or state, but do not lock out concurrent management changes.

The deletion example is deliberately limited to single-Region keys and uses a 30-day wait. Scheduling stops cryptographic use; final deletion is irreversible. Review dependent data and workloads first. CancelKeyDeletion must run during the waiting period and leaves the key Disabled; enabling it is a separate operation. No example invokes deletion automatically as cleanup. See ScheduleKeyDeletion and CancelKeyDeletion.

Troubleshooting

Separate transport, authorization, key state, and cryptographic failures
SymptomWhat to check
TLS or transport failureCheck the endpoint, trust store, connectivity and timeouts. A mutation might have completed before its response was lost; reconcile before retrying.
AccessDenied or expired credentialsCheck the signing region, credential lifetime and session token, IAM/key policies, grant constraints and cross-account permissions. Keep the AWS request ID.
Invalid key usage or stateInspect DescribeKey. Match KeySpec, KeyUsage, origin and current state to the operation. Allow eventual consistency after changes.
Invalid ciphertext or failed GCM authenticationCheck the original key, exact context, format, nonce, ciphertext and tag. Do not weaken checks or save unauthenticated plaintext.
Signature or MAC mismatchCheck the original message bytes, RAW versus DIGEST, algorithm, key identity, and signature encoding. An error or false result is not successful verification.
Import rejectedCheck the key specification, origin, original material for reimport, wrapping algorithm, payload order, and the matching unexpired wrapping-key/token pair.
Throttling or service failureUse bounded backoff with jitter when retry is appropriate. Creation, import, rotation and policy writes need operation-specific reconciliation rather than blind retries.

The examples report status, error codes, and selected identifiers without dumping plaintext or secrets. They do not provide credential refresh or a general retry framework. See the AWS KMS action reference for additional operations, including asymmetric data-key pairs, random generation, and custom key stores.