AWS KMS: Encrypt a File with a KMS Data Key and AES-GCM
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.
Uses a symmetric ENCRYPT_DECRYPT key and the case-sensitive context Application=ChilkatKmsExamples. Context is visible metadata, not a place for secrets. AWS must receive the exact same context on decryption. The sample handles binary data; UTF-8 text can be stored in the same input file. Direct symmetric Encrypt accepts up to 4096 bytes; larger data should use envelope encryption.
Generates a fresh AES-256 data key per envelope and a random 96-bit GCM nonce. Saves only the encrypted data key, ciphertext, nonce, tag and nonsecret context. The format uses a fixed authenticated-data string; it is a teaching format, not the AWS Encryption SDK format. Loads the file in memory. Never reuse a nonce with the same data key.
API actions used: kms:GenerateDataKey. 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 PowerBuilder Downloads
integer li_rc
long li_Success
oleobject loo_StringCompare
oleobject loo_Credentials
long li_StringMatch1
long li_StringMatch2
string ls_Region
oleobject loo_Endpoint
oleobject loo_Aws
oleobject loo_Rest
long li_StringMatch3
oleobject loo_Connection
oleobject loo_Body
oleobject loo_Result
string ls_ResponseJson
long li_StringMatch4
string ls_KeyId
oleobject loo_Payload
long li_StringMatch5
long li_StringMatch6
long li_StringMatch7
oleobject loo_DataKey
long li_StringMatch8
oleobject loo_Envelope
oleobject loo_Prng
string ls_IvBase64
oleobject loo_Aes
oleobject loo_AuthenticatedData
string ls_TagBase64
li_Success = 0
loo_StringCompare = create oleobject
li_rc = loo_StringCompare.ConnectToNewObject("Chilkat.StringBuilder")
if li_rc < 0 then
destroy loo_StringCompare
MessageBox("Error","Connecting to COM object failed")
return
end if
// Assumes Chilkat is unlocked. See Global Unlock Sample.
// Keep this credentials file outside public web content and source control.
loo_Credentials = create oleobject
li_rc = loo_Credentials.ConnectToNewObject("Chilkat.JsonObject")
loo_Credentials.Strict = 1
li_Success = loo_Credentials.LoadFile("qa_data/aws/kms.json")
if li_Success <> 1 then
Write-Debug "Could not load private KMS configuration."
destroy loo_StringCompare
destroy loo_Credentials
return
end if
loo_StringCompare.SetString(loo_Credentials.StringOf("access_key"))
li_StringMatch1 = loo_StringCompare.ContentsEqual("",1)
if (loo_Credentials.JsonTypeOf("access_key") <> 1) OR (li_StringMatch1 = 1) then
Write-Debug "Missing or invalid access_key."
destroy loo_StringCompare
destroy loo_Credentials
return
end if
loo_StringCompare.SetString(loo_Credentials.StringOf("secret_key"))
li_StringMatch2 = loo_StringCompare.ContentsEqual("",1)
if (loo_Credentials.JsonTypeOf("secret_key") <> 1) OR (li_StringMatch2 = 1) then
Write-Debug "Missing or invalid secret_key."
destroy loo_StringCompare
destroy loo_Credentials
return
end if
ls_Region = "us-west-2"
loo_Endpoint = create oleobject
li_rc = loo_Endpoint.ConnectToNewObject("Chilkat.StringBuilder")
loo_Endpoint.Append("kms.")
loo_Endpoint.Append(ls_Region)
loo_Endpoint.Append(".amazonaws.com")
loo_Aws = create oleobject
li_rc = loo_Aws.ConnectToNewObject("Chilkat.AuthAws")
loo_Aws.AccessKey = loo_Credentials.StringOf("access_key")
loo_Aws.SecretKey = loo_Credentials.StringOf("secret_key")
loo_Aws.Region = ls_Region
loo_Aws.ServiceName = "kms"
loo_Aws.SignatureVersion = 4
loo_Rest = create oleobject
li_rc = loo_Rest.ConnectToNewObject("Chilkat.Rest")
loo_Rest.ConnectTimeoutMs = 20000
loo_Rest.IdleTimeoutMs = 60000
loo_Rest.VerboseLogging = 0
li_Success = loo_Rest.SetAuthAws(loo_Aws)
if li_Success <> 1 then
Write-Debug "Could not configure AWS signing."
destroy loo_StringCompare
destroy loo_Credentials
destroy loo_Endpoint
destroy loo_Aws
destroy loo_Rest
return
end if
if loo_Credentials.HasMember("session_token") = 1 then
loo_StringCompare.SetString(loo_Credentials.StringOf("session_token"))
li_StringMatch3 = loo_StringCompare.ContentsEqual("",1)
if (loo_Credentials.JsonTypeOf("session_token") <> 1) OR (li_StringMatch3 = 1) then
Write-Debug "Missing or invalid session_token."
destroy loo_StringCompare
destroy loo_Credentials
destroy loo_Endpoint
destroy loo_Aws
destroy loo_Rest
return
end if
end if
loo_Connection = create oleobject
li_rc = loo_Connection.ConnectToNewObject("Chilkat.Socket")
loo_Connection.RequireSslCertVerify = 1
loo_Connection.MaxReadIdleMs = 60000
loo_Connection.MaxSendIdleMs = 60000
li_Success = loo_Connection.Connect(loo_Endpoint.GetAsString(),443,1,20000)
if li_Success <> 1 then
Write-Debug "TLS connection failed; inspect diagnostics privately."
destroy loo_StringCompare
destroy loo_Credentials
destroy loo_Endpoint
destroy loo_Aws
destroy loo_Rest
destroy loo_Connection
return
end if
li_Success = loo_Rest.UseConnection(loo_Connection,1)
if li_Success <> 1 then
Write-Debug "Could not attach TLS connection."
destroy loo_StringCompare
destroy loo_Credentials
destroy loo_Endpoint
destroy loo_Aws
destroy loo_Rest
destroy loo_Connection
return
end if
// Keep connection alive while Rest uses it.
loo_Body = create oleobject
li_rc = loo_Body.ConnectToNewObject("Chilkat.JsonObject")
loo_Result = create oleobject
li_rc = loo_Result.ConnectToNewObject("Chilkat.JsonObject")
loo_Result.Strict = 1
loo_StringCompare.SetString(loo_Credentials.StringOf("key_id"))
li_StringMatch4 = loo_StringCompare.ContentsEqual("",1)
if (loo_Credentials.JsonTypeOf("key_id") <> 1) OR (li_StringMatch4 = 1) then
Write-Debug "Missing or invalid key_id."
destroy loo_StringCompare
destroy loo_Credentials
destroy loo_Endpoint
destroy loo_Aws
destroy loo_Rest
destroy loo_Connection
destroy loo_Body
destroy loo_Result
return
end if
ls_KeyId = loo_Credentials.StringOf("key_id")
loo_Payload = create oleobject
li_rc = loo_Payload.ConnectToNewObject("Chilkat.BinData")
li_Success = loo_Payload.LoadFile("qa_data/kms/plaintext.bin")
if li_Success <> 1 then
Write-Debug "Could not load qa_data/kms/plaintext.bin."
destroy loo_StringCompare
destroy loo_Credentials
destroy loo_Endpoint
destroy loo_Aws
destroy loo_Rest
destroy loo_Connection
destroy loo_Body
destroy loo_Result
destroy loo_Payload
return
end if
loo_Body.Clear()
li_Success = loo_Body.UpdateString("KeyId",ls_KeyId)
if li_Success <> 1 then
Write-Debug "Could not set KeyId."
destroy loo_StringCompare
destroy loo_Credentials
destroy loo_Endpoint
destroy loo_Aws
destroy loo_Rest
destroy loo_Connection
destroy loo_Body
destroy loo_Result
destroy loo_Payload
return
end if
li_Success = loo_Body.UpdateString("EncryptionContext.Application","ChilkatKmsExamples")
if li_Success <> 1 then
Write-Debug "Could not set EncryptionContext.Application."
destroy loo_StringCompare
destroy loo_Credentials
destroy loo_Endpoint
destroy loo_Aws
destroy loo_Rest
destroy loo_Connection
destroy loo_Body
destroy loo_Result
destroy loo_Payload
return
end if
li_Success = loo_Body.UpdateString("KeySpec","AES_256")
if li_Success <> 1 then
Write-Debug "Could not set KeySpec."
destroy loo_StringCompare
destroy loo_Credentials
destroy loo_Endpoint
destroy loo_Aws
destroy loo_Rest
destroy loo_Connection
destroy loo_Body
destroy loo_Result
destroy loo_Payload
return
end if
li_Success = loo_Rest.ClearAllQueryParams()
if li_Success <> 1 then
Write-Debug "Could not clear previous query parameters."
destroy loo_StringCompare
destroy loo_Credentials
destroy loo_Endpoint
destroy loo_Aws
destroy loo_Rest
destroy loo_Connection
destroy loo_Body
destroy loo_Result
destroy loo_Payload
return
end if
// Keep the JSON operation body separate from authentication parameters.
// Include STS credentials in the signed query; never log the request URL.
if loo_Credentials.HasMember("session_token") = 1 then
li_Success = loo_Rest.AddQueryParam("X-Amz-Security-Token",loo_Credentials.StringOf("session_token"))
if li_Success <> 1 then
Write-Debug "Could not set session token."
destroy loo_StringCompare
destroy loo_Credentials
destroy loo_Endpoint
destroy loo_Aws
destroy loo_Rest
destroy loo_Connection
destroy loo_Body
destroy loo_Result
destroy loo_Payload
return
end if
end if
li_Success = loo_Rest.AddHeader("X-Amz-Target","TrentService.GenerateDataKey")
if li_Success <> 1 then
Write-Debug "Could not set operation."
destroy loo_StringCompare
destroy loo_Credentials
destroy loo_Endpoint
destroy loo_Aws
destroy loo_Rest
destroy loo_Connection
destroy loo_Body
destroy loo_Result
destroy loo_Payload
return
end if
li_Success = loo_Rest.AddHeader("Content-Type","application/x-amz-json-1.1")
if li_Success <> 1 then
Write-Debug "Could not set content type."
destroy loo_StringCompare
destroy loo_Credentials
destroy loo_Endpoint
destroy loo_Aws
destroy loo_Rest
destroy loo_Connection
destroy loo_Body
destroy loo_Result
destroy loo_Payload
return
end if
ls_ResponseJson = loo_Rest.FullRequestString("POST","/",loo_Body.Emit())
if loo_Rest.LastMethodSuccess <> 1 then
Write-Debug "KMS request did not complete; inspect diagnostics privately. Reconcile any write before retrying."
destroy loo_StringCompare
destroy loo_Credentials
destroy loo_Endpoint
destroy loo_Aws
destroy loo_Rest
destroy loo_Connection
destroy loo_Body
destroy loo_Result
destroy loo_Payload
return
end if
if loo_Rest.ResponseStatusCode <> 200 then
Write-Debug "KMS HTTP status: " + string(loo_Rest.ResponseStatusCode)
li_Success = loo_Result.Load(ls_ResponseJson)
if li_Success = 1 then
if loo_Result.JsonTypeOf("__type") = 1 then
Write-Debug "AWS error code: " + loo_Result.StringOf("__type")
end if
end if
Write-Debug "AWS request ID: " + loo_Rest.ResponseHdrByName("x-amzn-RequestId")
// Do not print full bodies, headers, credentials, key material, or tokens.
destroy loo_StringCompare
destroy loo_Credentials
destroy loo_Endpoint
destroy loo_Aws
destroy loo_Rest
destroy loo_Connection
destroy loo_Body
destroy loo_Result
destroy loo_Payload
return
end if
li_Success = loo_Result.Load(ls_ResponseJson)
if li_Success <> 1 then
Write-Debug "Expected a well-formed JSON response."
destroy loo_StringCompare
destroy loo_Credentials
destroy loo_Endpoint
destroy loo_Aws
destroy loo_Rest
destroy loo_Connection
destroy loo_Body
destroy loo_Result
destroy loo_Payload
return
end if
loo_StringCompare.SetString(loo_Result.StringOf("KeyId"))
li_StringMatch5 = loo_StringCompare.ContentsEqual("",1)
if (loo_Result.JsonTypeOf("KeyId") <> 1) OR (li_StringMatch5 = 1) then
Write-Debug "Missing or invalid KeyId."
destroy loo_StringCompare
destroy loo_Credentials
destroy loo_Endpoint
destroy loo_Aws
destroy loo_Rest
destroy loo_Connection
destroy loo_Body
destroy loo_Result
destroy loo_Payload
return
end if
loo_StringCompare.SetString(loo_Result.StringOf("KeyId"))
li_StringMatch6 = loo_StringCompare.ContentsEqual(ls_KeyId,1)
if li_StringMatch6 <> 1 then
Write-Debug "Response belongs to another key; use a fixed key ARN in configuration."
destroy loo_StringCompare
destroy loo_Credentials
destroy loo_Endpoint
destroy loo_Aws
destroy loo_Rest
destroy loo_Connection
destroy loo_Body
destroy loo_Result
destroy loo_Payload
return
end if
loo_StringCompare.SetString(loo_Result.StringOf("Plaintext"))
li_StringMatch7 = loo_StringCompare.ContentsEqual("",1)
if (loo_Result.JsonTypeOf("Plaintext") <> 1) OR (li_StringMatch7 = 1) then
Write-Debug "Missing or invalid Plaintext."
destroy loo_StringCompare
destroy loo_Credentials
destroy loo_Endpoint
destroy loo_Aws
destroy loo_Rest
destroy loo_Connection
destroy loo_Body
destroy loo_Result
destroy loo_Payload
return
end if
loo_DataKey = create oleobject
li_rc = loo_DataKey.ConnectToNewObject("Chilkat.BinData")
li_Success = loo_DataKey.AppendEncoded(loo_Result.StringOf("Plaintext"),"base64")
if li_Success <> 1 then
Write-Debug "Invalid base64 Plaintext."
destroy loo_StringCompare
destroy loo_Credentials
destroy loo_Endpoint
destroy loo_Aws
destroy loo_Rest
destroy loo_Connection
destroy loo_Body
destroy loo_Result
destroy loo_Payload
destroy loo_DataKey
return
end if
if loo_DataKey.NumBytes <> 32 then
Write-Debug "Unexpected byte length for Plaintext."
destroy loo_StringCompare
destroy loo_Credentials
destroy loo_Endpoint
destroy loo_Aws
destroy loo_Rest
destroy loo_Connection
destroy loo_Body
destroy loo_Result
destroy loo_Payload
destroy loo_DataKey
return
end if
loo_StringCompare.SetString(loo_Result.StringOf("CiphertextBlob"))
li_StringMatch8 = loo_StringCompare.ContentsEqual("",1)
if (loo_Result.JsonTypeOf("CiphertextBlob") <> 1) OR (li_StringMatch8 = 1) then
Write-Debug "Missing or invalid CiphertextBlob."
destroy loo_StringCompare
destroy loo_Credentials
destroy loo_Endpoint
destroy loo_Aws
destroy loo_Rest
destroy loo_Connection
destroy loo_Body
destroy loo_Result
destroy loo_Payload
destroy loo_DataKey
return
end if
loo_Envelope = create oleobject
li_rc = loo_Envelope.ConnectToNewObject("Chilkat.JsonObject")
li_Success = loo_Envelope.UpdateString("format","chilkat-kms-aes256-gcm-v1")
if li_Success <> 1 then
Write-Debug "Could not set format."
destroy loo_StringCompare
destroy loo_Credentials
destroy loo_Endpoint
destroy loo_Aws
destroy loo_Rest
destroy loo_Connection
destroy loo_Body
destroy loo_Result
destroy loo_Payload
destroy loo_DataKey
destroy loo_Envelope
return
end if
li_Success = loo_Envelope.UpdateString("keyArn",ls_KeyId)
if li_Success <> 1 then
Write-Debug "Could not set keyArn."
destroy loo_StringCompare
destroy loo_Credentials
destroy loo_Endpoint
destroy loo_Aws
destroy loo_Rest
destroy loo_Connection
destroy loo_Body
destroy loo_Result
destroy loo_Payload
destroy loo_DataKey
destroy loo_Envelope
return
end if
li_Success = loo_Envelope.UpdateString("encryptedDataKey",loo_Result.StringOf("CiphertextBlob"))
if li_Success <> 1 then
Write-Debug "Could not set encryptedDataKey."
destroy loo_StringCompare
destroy loo_Credentials
destroy loo_Endpoint
destroy loo_Aws
destroy loo_Rest
destroy loo_Connection
destroy loo_Body
destroy loo_Result
destroy loo_Payload
destroy loo_DataKey
destroy loo_Envelope
return
end if
li_Success = loo_Envelope.UpdateString("context.Application","ChilkatKmsExamples")
if li_Success <> 1 then
Write-Debug "Could not set context.Application."
destroy loo_StringCompare
destroy loo_Credentials
destroy loo_Endpoint
destroy loo_Aws
destroy loo_Rest
destroy loo_Connection
destroy loo_Body
destroy loo_Result
destroy loo_Payload
destroy loo_DataKey
destroy loo_Envelope
return
end if
loo_Prng = create oleobject
li_rc = loo_Prng.ConnectToNewObject("Chilkat.Prng")
ls_IvBase64 = loo_Prng.GenRandom(12,"base64")
if loo_Prng.LastMethodSuccess <> 1 then
Write-Debug "Could not generate GCM nonce."
destroy loo_StringCompare
destroy loo_Credentials
destroy loo_Endpoint
destroy loo_Aws
destroy loo_Rest
destroy loo_Connection
destroy loo_Body
destroy loo_Result
destroy loo_Payload
destroy loo_DataKey
destroy loo_Envelope
destroy loo_Prng
return
end if
loo_Aes = create oleobject
li_rc = loo_Aes.ConnectToNewObject("Chilkat.Crypt2")
loo_Aes.CryptAlgorithm = "aes"
loo_Aes.CipherMode = "gcm"
loo_Aes.KeyLength = 256
loo_Aes.SetEncodedKey(loo_DataKey.GetEncoded("base64"),"base64")
loo_AuthenticatedData = create oleobject
li_rc = loo_AuthenticatedData.ConnectToNewObject("Chilkat.BinData")
li_Success = loo_AuthenticatedData.AppendString("chilkat-kms-aes256-gcm-v1|Application=ChilkatKmsExamples","utf-8")
if li_Success <> 1 then
Write-Debug "Could not encode authenticated data."
destroy loo_StringCompare
destroy loo_Credentials
destroy loo_Endpoint
destroy loo_Aws
destroy loo_Rest
destroy loo_Connection
destroy loo_Body
destroy loo_Result
destroy loo_Payload
destroy loo_DataKey
destroy loo_Envelope
destroy loo_Prng
destroy loo_Aes
destroy loo_AuthenticatedData
return
end if
loo_Aes.SetEncodedIV(ls_IvBase64,"base64")
li_Success = loo_Aes.SetEncodedAad(loo_AuthenticatedData.GetEncoded("base64"),"base64")
if li_Success <> 1 then
Write-Debug "Could not set authenticated data."
destroy loo_StringCompare
destroy loo_Credentials
destroy loo_Endpoint
destroy loo_Aws
destroy loo_Rest
destroy loo_Connection
destroy loo_Body
destroy loo_Result
destroy loo_Payload
destroy loo_DataKey
destroy loo_Envelope
destroy loo_Prng
destroy loo_Aes
destroy loo_AuthenticatedData
return
end if
li_Success = loo_Aes.EncryptBd(loo_Payload)
if li_Success <> 1 then
Write-Debug "AES-GCM encryption failed."
destroy loo_StringCompare
destroy loo_Credentials
destroy loo_Endpoint
destroy loo_Aws
destroy loo_Rest
destroy loo_Connection
destroy loo_Body
destroy loo_Result
destroy loo_Payload
destroy loo_DataKey
destroy loo_Envelope
destroy loo_Prng
destroy loo_Aes
destroy loo_AuthenticatedData
return
end if
ls_TagBase64 = loo_Aes.GetEncodedAuthTag("base64")
if loo_Aes.LastMethodSuccess <> 1 then
Write-Debug "Could not obtain GCM tag."
destroy loo_StringCompare
destroy loo_Credentials
destroy loo_Endpoint
destroy loo_Aws
destroy loo_Rest
destroy loo_Connection
destroy loo_Body
destroy loo_Result
destroy loo_Payload
destroy loo_DataKey
destroy loo_Envelope
destroy loo_Prng
destroy loo_Aes
destroy loo_AuthenticatedData
return
end if
li_Success = loo_Envelope.UpdateString("iv",ls_IvBase64)
if li_Success <> 1 then
Write-Debug "Could not set iv."
destroy loo_StringCompare
destroy loo_Credentials
destroy loo_Endpoint
destroy loo_Aws
destroy loo_Rest
destroy loo_Connection
destroy loo_Body
destroy loo_Result
destroy loo_Payload
destroy loo_DataKey
destroy loo_Envelope
destroy loo_Prng
destroy loo_Aes
destroy loo_AuthenticatedData
return
end if
li_Success = loo_Envelope.UpdateString("tag",ls_TagBase64)
if li_Success <> 1 then
Write-Debug "Could not set tag."
destroy loo_StringCompare
destroy loo_Credentials
destroy loo_Endpoint
destroy loo_Aws
destroy loo_Rest
destroy loo_Connection
destroy loo_Body
destroy loo_Result
destroy loo_Payload
destroy loo_DataKey
destroy loo_Envelope
destroy loo_Prng
destroy loo_Aes
destroy loo_AuthenticatedData
return
end if
li_Success = loo_Envelope.UpdateString("ciphertext",loo_Payload.GetEncoded("base64"))
if li_Success <> 1 then
Write-Debug "Could not set ciphertext."
destroy loo_StringCompare
destroy loo_Credentials
destroy loo_Endpoint
destroy loo_Aws
destroy loo_Rest
destroy loo_Connection
destroy loo_Body
destroy loo_Result
destroy loo_Payload
destroy loo_DataKey
destroy loo_Envelope
destroy loo_Prng
destroy loo_Aes
destroy loo_AuthenticatedData
return
end if
li_Success = loo_Envelope.WriteFile("qa_output/kms_envelope.json")
if li_Success <> 1 then
Write-Debug "Could not save qa_output/kms_envelope.json."
destroy loo_StringCompare
destroy loo_Credentials
destroy loo_Endpoint
destroy loo_Aws
destroy loo_Rest
destroy loo_Connection
destroy loo_Body
destroy loo_Result
destroy loo_Payload
destroy loo_DataKey
destroy loo_Envelope
destroy loo_Prng
destroy loo_Aes
destroy loo_AuthenticatedData
return
end if
li_Success = loo_DataKey.SecureClear()
if li_Success <> 1 then
Write-Debug "Could not clear data key buffer."
destroy loo_StringCompare
destroy loo_Credentials
destroy loo_Endpoint
destroy loo_Aws
destroy loo_Rest
destroy loo_Connection
destroy loo_Body
destroy loo_Result
destroy loo_Payload
destroy loo_DataKey
destroy loo_Envelope
destroy loo_Prng
destroy loo_Aes
destroy loo_AuthenticatedData
return
end if
Write-Debug "Example completed."
destroy loo_StringCompare
destroy loo_Credentials
destroy loo_Endpoint
destroy loo_Aws
destroy loo_Rest
destroy loo_Connection
destroy loo_Body
destroy loo_Result
destroy loo_Payload
destroy loo_DataKey
destroy loo_Envelope
destroy loo_Prng
destroy loo_Aes
destroy loo_AuthenticatedData