Sample code for 30+ languages & platforms
Ruby Requires Chilkat v11.6.0+

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.

GenerateDataKey

Chilkat Ruby Downloads

Ruby
require 'chilkat'

success = false

stringCompare = Chilkat::CkStringBuilder.new()
#  Assumes Chilkat is unlocked. See Global Unlock Sample.
#  Keep this credentials file outside public web content and source control.
credentials = Chilkat::CkJsonObject.new()
credentials.put_Strict(true)
success = credentials.LoadFile("qa_data/aws/kms.json")
if (success != true)
    print "Could not load private KMS configuration." + "\n";
    exit
end

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." + "\n";
    exit
end

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." + "\n";
    exit
end

region = "us-west-2"
endpoint = Chilkat::CkStringBuilder.new()
endpoint.Append("kms.")
endpoint.Append(region)
endpoint.Append(".amazonaws.com")
aws = Chilkat::CkAuthAws.new()
aws.put_AccessKey(credentials.stringOf("access_key"))
aws.put_SecretKey(credentials.stringOf("secret_key"))
aws.put_Region(region)
aws.put_ServiceName("kms")
aws.put_SignatureVersion(4)
rest = Chilkat::CkRest.new()
rest.put_ConnectTimeoutMs(20000)
rest.put_IdleTimeoutMs(60000)
rest.put_VerboseLogging(false)
success = rest.SetAuthAws(aws)
if (success != true)
    print "Could not configure AWS signing." + "\n";
    exit
end

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." + "\n";
        exit
    end

end

connection = Chilkat::CkSocket.new()
connection.put_RequireSslCertVerify(true)
connection.put_MaxReadIdleMs(60000)
connection.put_MaxSendIdleMs(60000)
success = connection.Connect(endpoint.getAsString(),443,true,20000)
if (success != true)
    print "TLS connection failed; inspect diagnostics privately." + "\n";
    exit
end

success = rest.UseConnection(connection,true)
if (success != true)
    print "Could not attach TLS connection." + "\n";
    exit
end

#  Keep connection alive while Rest uses it.
body = Chilkat::CkJsonObject.new()
result = Chilkat::CkJsonObject.new()
result.put_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." + "\n";
    exit
end

keyId = credentials.stringOf("key_id")
payload = Chilkat::CkBinData.new()
success = payload.LoadFile("qa_data/kms/plaintext.bin")
if (success != true)
    print "Could not load qa_data/kms/plaintext.bin." + "\n";
    exit
end

body.Clear()
success = body.UpdateString("KeyId",keyId)
if (success != true)
    print "Could not set KeyId." + "\n";
    exit
end

success = body.UpdateString("EncryptionContext.Application","ChilkatKmsExamples")
if (success != true)
    print "Could not set EncryptionContext.Application." + "\n";
    exit
end

success = body.UpdateString("KeySpec","AES_256")
if (success != true)
    print "Could not set KeySpec." + "\n";
    exit
end

success = rest.ClearAllQueryParams()
if (success != true)
    print "Could not clear previous query parameters." + "\n";
    exit
end

#  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." + "\n";
        exit
    end

end

success = rest.AddHeader("X-Amz-Target","TrentService.GenerateDataKey")
if (success != true)
    print "Could not set operation." + "\n";
    exit
end

success = rest.AddHeader("Content-Type","application/x-amz-json-1.1")
if (success != true)
    print "Could not set content type." + "\n";
    exit
end

responseJson = rest.fullRequestString("POST","/",body.emit())
if (rest.get_LastMethodSuccess() != true)
    print "KMS request did not complete; inspect diagnostics privately. Reconcile any write before retrying." + "\n";
    exit
end

if (rest.get_ResponseStatusCode() != 200)
    print "KMS HTTP status: " + rest.get_ResponseStatusCode().to_s() + "\n";
    success = result.Load(responseJson)
    if (success == true)
        if (result.JsonTypeOf("__type") == 1)
            print "AWS error code: " + result.stringOf("__type") + "\n";
        end

    end

    print "AWS request ID: " + rest.responseHdrByName("x-amzn-RequestId") + "\n";
    #  Do not print full bodies, headers, credentials, key material, or tokens.
    exit
end

success = result.Load(responseJson)
if (success != true)
    print "Expected a well-formed JSON response." + "\n";
    exit
end

stringCompare.SetString(result.stringOf("KeyId"))
stringMatch5 = stringCompare.ContentsEqual("",true)
if ((result.JsonTypeOf("KeyId") != 1) or (stringMatch5 == true))
    print "Missing or invalid KeyId." + "\n";
    exit
end

stringCompare.SetString(result.stringOf("KeyId"))
stringMatch6 = stringCompare.ContentsEqual(keyId,true)
if (stringMatch6 != true)
    print "Response belongs to another key; use a fixed key ARN in configuration." + "\n";
    exit
end

stringCompare.SetString(result.stringOf("Plaintext"))
stringMatch7 = stringCompare.ContentsEqual("",true)
if ((result.JsonTypeOf("Plaintext") != 1) or (stringMatch7 == true))
    print "Missing or invalid Plaintext." + "\n";
    exit
end

dataKey = Chilkat::CkBinData.new()
success = dataKey.AppendEncoded(result.stringOf("Plaintext"),"base64")
if (success != true)
    print "Invalid base64 Plaintext." + "\n";
    exit
end

if (dataKey.get_NumBytes() != 32)
    print "Unexpected byte length for Plaintext." + "\n";
    exit
end

stringCompare.SetString(result.stringOf("CiphertextBlob"))
stringMatch8 = stringCompare.ContentsEqual("",true)
if ((result.JsonTypeOf("CiphertextBlob") != 1) or (stringMatch8 == true))
    print "Missing or invalid CiphertextBlob." + "\n";
    exit
end

envelope = Chilkat::CkJsonObject.new()
success = envelope.UpdateString("format","chilkat-kms-aes256-gcm-v1")
if (success != true)
    print "Could not set format." + "\n";
    exit
end

success = envelope.UpdateString("keyArn",keyId)
if (success != true)
    print "Could not set keyArn." + "\n";
    exit
end

success = envelope.UpdateString("encryptedDataKey",result.stringOf("CiphertextBlob"))
if (success != true)
    print "Could not set encryptedDataKey." + "\n";
    exit
end

success = envelope.UpdateString("context.Application","ChilkatKmsExamples")
if (success != true)
    print "Could not set context.Application." + "\n";
    exit
end

prng = Chilkat::CkPrng.new()
ivBase64 = prng.genRandom(12,"base64")
if (prng.get_LastMethodSuccess() != true)
    print "Could not generate GCM nonce." + "\n";
    exit
end

aes = Chilkat::CkCrypt2.new()
aes.put_CryptAlgorithm("aes")
aes.put_CipherMode("gcm")
aes.put_KeyLength(256)
aes.SetEncodedKey(dataKey.getEncoded("base64"),"base64")
authenticatedData = Chilkat::CkBinData.new()
success = authenticatedData.AppendString("chilkat-kms-aes256-gcm-v1|Application=ChilkatKmsExamples","utf-8")
if (success != true)
    print "Could not encode authenticated data." + "\n";
    exit
end

aes.SetEncodedIV(ivBase64,"base64")
success = aes.SetEncodedAad(authenticatedData.getEncoded("base64"),"base64")
if (success != true)
    print "Could not set authenticated data." + "\n";
    exit
end

success = aes.EncryptBd(payload)
if (success != true)
    print "AES-GCM encryption failed." + "\n";
    exit
end

tagBase64 = aes.getEncodedAuthTag("base64")
if (aes.get_LastMethodSuccess() != true)
    print "Could not obtain GCM tag." + "\n";
    exit
end

success = envelope.UpdateString("iv",ivBase64)
if (success != true)
    print "Could not set iv." + "\n";
    exit
end

success = envelope.UpdateString("tag",tagBase64)
if (success != true)
    print "Could not set tag." + "\n";
    exit
end

success = envelope.UpdateString("ciphertext",payload.getEncoded("base64"))
if (success != true)
    print "Could not set ciphertext." + "\n";
    exit
end

success = envelope.WriteFile("qa_output/kms_envelope.json")
if (success != true)
    print "Could not save qa_output/kms_envelope.json." + "\n";
    exit
end

success = dataKey.SecureClear()
if (success != true)
    print "Could not clear data key buffer." + "\n";
    exit
end

print "Example completed." + "\n";