AWS KMS: Use a New Grant Token for Decrypt
See more AWS KMS Examples
Uses the current AWS KMS API. Configure the region and keep credentials in private qa_data/aws/kms.json, with nonempty string fields access_key and secret_key. The examples do not obtain or refresh credentials. Keep diagnostics private; they may contain credentials or sensitive key data. Create the output directory before running file-writing examples.
Uses the AWS JSON 1.1 protocol with TrentService targets, service kms, HTTPS certificate verification, and Signature Version 4. When using temporary credentials, also provide a nonempty session_token; this Rest example includes it in the signed query on each request. Never log that URL. The endpoint shown is for the commercial AWS partition; use the appropriate endpoint for other partitions. Failures stop the sample; production retry policies should use bounded backoff with jitter and reconcile uncertain writes.
Where a key is required, set string key_id to its fixed key ARN in the configured region. Additional named fields and input files are described below. Keep output files private when they contain plaintext or policies. The code does not automatically retry mutations, refresh credentials, or create output directories. A successful request can precede propagation of a state change. Discard sensitive objects promptly; clearing one buffer does not erase copies held in strings, JSON, or runtime memory.
Run as the grantee using its own credentials and the grant file passed through a private channel. Includes GrantTokens in the request while the new grant propagates. The exact context still applies. The token is not a substitute for AWS authentication.
API actions used: kms:Decrypt. IAM permissions and key policies must allow the actual resources; grant and multi-Region workflows can need permissions in more than one region/account.
Chilkat Python Downloads
import sys
import chilkat2
success = False
stringCompare = chilkat2.StringBuilder()
# Assumes Chilkat is unlocked. See Global Unlock Sample.
# Keep this credentials file outside public web content and source control.
credentials = chilkat2.JsonObject()
credentials.Strict = True
success = credentials.LoadFile("qa_data/aws/kms.json")
if (success != True):
print("Could not load private KMS configuration.")
sys.exit()
stringCompare.SetString(credentials.StringOf("access_key"))
stringMatch1 = stringCompare.ContentsEqual("",True)
if ((credentials.JsonTypeOf("access_key") != 1) or (stringMatch1 == True)):
print("Missing or invalid access_key.")
sys.exit()
stringCompare.SetString(credentials.StringOf("secret_key"))
stringMatch2 = stringCompare.ContentsEqual("",True)
if ((credentials.JsonTypeOf("secret_key") != 1) or (stringMatch2 == True)):
print("Missing or invalid secret_key.")
sys.exit()
region = "us-west-2"
endpoint = chilkat2.StringBuilder()
endpoint.Append("kms.")
endpoint.Append(region)
endpoint.Append(".amazonaws.com")
aws = chilkat2.AuthAws()
aws.AccessKey = credentials.StringOf("access_key")
aws.SecretKey = credentials.StringOf("secret_key")
aws.Region = region
aws.ServiceName = "kms"
aws.SignatureVersion = 4
rest = chilkat2.Rest()
rest.ConnectTimeoutMs = 20000
rest.IdleTimeoutMs = 60000
rest.VerboseLogging = False
success = rest.SetAuthAws(aws)
if (success != True):
print("Could not configure AWS signing.")
sys.exit()
if (credentials.HasMember("session_token") == True):
stringCompare.SetString(credentials.StringOf("session_token"))
stringMatch3 = stringCompare.ContentsEqual("",True)
if ((credentials.JsonTypeOf("session_token") != 1) or (stringMatch3 == True)):
print("Missing or invalid session_token.")
sys.exit()
connection = chilkat2.Socket()
connection.RequireSslCertVerify = True
connection.MaxReadIdleMs = 60000
connection.MaxSendIdleMs = 60000
success = connection.Connect(endpoint.GetAsString(),443,True,20000)
if (success != True):
print("TLS connection failed; inspect diagnostics privately.")
sys.exit()
success = rest.UseConnection(connection,True)
if (success != True):
print("Could not attach TLS connection.")
sys.exit()
# Keep connection alive while Rest uses it.
body = chilkat2.JsonObject()
result = chilkat2.JsonObject()
result.Strict = True
stringCompare.SetString(credentials.StringOf("key_id"))
stringMatch4 = stringCompare.ContentsEqual("",True)
if ((credentials.JsonTypeOf("key_id") != 1) or (stringMatch4 == True)):
print("Missing or invalid key_id.")
sys.exit()
keyId = credentials.StringOf("key_id")
grant = chilkat2.JsonObject()
grant.Strict = True
success = grant.LoadFile("qa_output/kms_grant.json")
if (success != True):
print("Could not load qa_output/kms_grant.json.")
sys.exit()
stringCompare.SetString(grant.StringOf("GrantToken"))
stringMatch5 = stringCompare.ContentsEqual("",True)
if ((grant.JsonTypeOf("GrantToken") != 1) or (stringMatch5 == True)):
print("Missing or invalid GrantToken.")
sys.exit()
stringCompare.SetString(grant.StringOf("KeyId"))
stringMatch6 = stringCompare.ContentsEqual("",True)
if ((grant.JsonTypeOf("KeyId") != 1) or (stringMatch6 == True)):
print("Missing or invalid KeyId.")
sys.exit()
stringCompare.SetString(grant.StringOf("KeyId"))
stringMatch7 = stringCompare.ContentsEqual(keyId,True)
if (stringMatch7 != True):
print("Grant file is for another key.")
sys.exit()
ciphertext = chilkat2.BinData()
success = ciphertext.LoadFile("qa_output/kms_ciphertext.bin")
if (success != True):
print("Could not load qa_output/kms_ciphertext.bin.")
sys.exit()
if ((ciphertext.NumBytes == 0) or (ciphertext.NumBytes > 6144)):
print("Input byte length is outside the sample limit.")
sys.exit()
body.Clear()
success = body.UpdateString("KeyId",keyId)
if (success != True):
print("Could not set KeyId.")
sys.exit()
success = body.UpdateString("EncryptionContext.Application","ChilkatKmsExamples")
if (success != True):
print("Could not set EncryptionContext.Application.")
sys.exit()
success = body.UpdateString("EncryptionAlgorithm","SYMMETRIC_DEFAULT")
if (success != True):
print("Could not set EncryptionAlgorithm.")
sys.exit()
success = body.UpdateString("CiphertextBlob",ciphertext.GetEncoded("base64"))
if (success != True):
print("Could not set CiphertextBlob.")
sys.exit()
success = body.UpdateString("GrantTokens[0]",grant.StringOf("GrantToken"))
if (success != True):
print("Could not set GrantTokens[0].")
sys.exit()
success = rest.ClearAllQueryParams()
if (success != True):
print("Could not clear previous query parameters.")
sys.exit()
# Keep the JSON operation body separate from authentication parameters.
# Include STS credentials in the signed query; never log the request URL.
if (credentials.HasMember("session_token") == True):
success = rest.AddQueryParam("X-Amz-Security-Token",credentials.StringOf("session_token"))
if (success != True):
print("Could not set session token.")
sys.exit()
success = rest.AddHeader("X-Amz-Target","TrentService.Decrypt")
if (success != True):
print("Could not set operation.")
sys.exit()
success = rest.AddHeader("Content-Type","application/x-amz-json-1.1")
if (success != True):
print("Could not set content type.")
sys.exit()
responseJson = rest.FullRequestString("POST","/",body.Emit())
if (rest.LastMethodSuccess != True):
print("KMS request did not complete; inspect diagnostics privately. Reconcile any write before retrying.")
sys.exit()
if (rest.ResponseStatusCode != 200):
print("KMS HTTP status: " + str(rest.ResponseStatusCode))
success = result.Load(responseJson)
if (success == True):
if (result.JsonTypeOf("__type") == 1):
print("AWS error code: " + result.StringOf("__type"))
print("AWS request ID: " + rest.ResponseHdrByName("x-amzn-RequestId"))
# Do not print full bodies, headers, credentials, key material, or tokens.
sys.exit()
success = result.Load(responseJson)
if (success != True):
print("Expected a well-formed JSON response.")
sys.exit()
stringCompare.SetString(result.StringOf("KeyId"))
stringMatch8 = stringCompare.ContentsEqual("",True)
if ((result.JsonTypeOf("KeyId") != 1) or (stringMatch8 == True)):
print("Missing or invalid KeyId.")
sys.exit()
stringCompare.SetString(result.StringOf("KeyId"))
stringMatch9 = stringCompare.ContentsEqual(keyId,True)
if (stringMatch9 != True):
print("Response belongs to another key; use a fixed key ARN in configuration.")
sys.exit()
stringCompare.SetString(result.StringOf("Plaintext"))
stringMatch10 = stringCompare.ContentsEqual("",True)
if ((result.JsonTypeOf("Plaintext") != 1) or (stringMatch10 == True)):
print("Missing or invalid Plaintext.")
sys.exit()
plaintext = chilkat2.BinData()
success = plaintext.AppendEncoded(result.StringOf("Plaintext"),"base64")
if (success != True):
print("Invalid base64 Plaintext.")
sys.exit()
if (plaintext.NumBytes == 0):
print("Unexpected byte length for Plaintext.")
sys.exit()
success = plaintext.WriteFile("qa_output/kms_grant_plaintext.bin")
if (success != True):
print("Could not write qa_output/kms_grant_plaintext.bin.")
sys.exit()
success = plaintext.SecureClear()
if (success != True):
print("Could not clear plaintext buffer.")
sys.exit()
print("Example completed.")