AWS KMS: Authenticate and Decrypt a KMS AES-GCM Envelope
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.
Reads the companion encryption example format. The configured key ARN and expected context are trusted application inputs, not freely selected by the envelope. Checks the nonce/tag lengths and writes plaintext only after successful GCM authentication. Do not use partial output on failure. Tampered ciphertext, tag, context or authenticated data must fail.
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 Node.js Downloads
NODEJS_PRELUDE
function chilkatExample() {
var success = false;
var stringCompare = new chilkat.StringBuilder();
// Assumes Chilkat is unlocked. See Global Unlock Sample.
// Keep this credentials file outside public web content and source control.
var credentials = new chilkat.JsonObject();
credentials.Strict = true;
success = credentials.LoadFile("qa_data/aws/kms.json");
if (success !== true) {
console.log("Could not load private KMS configuration.");
return;
}
stringCompare.SetString(credentials.StringOf("access_key"));
var stringMatch1 = stringCompare.ContentsEqual("",true);
if ((credentials.JsonTypeOf("access_key") !== 1) || (stringMatch1 == true)) {
console.log("Missing or invalid access_key.");
return;
}
stringCompare.SetString(credentials.StringOf("secret_key"));
var stringMatch2 = stringCompare.ContentsEqual("",true);
if ((credentials.JsonTypeOf("secret_key") !== 1) || (stringMatch2 == true)) {
console.log("Missing or invalid secret_key.");
return;
}
var region = "us-west-2";
var endpoint = new chilkat.StringBuilder();
endpoint.Append("kms.");
endpoint.Append(region);
endpoint.Append(".amazonaws.com");
var aws = new chilkat.AuthAws();
aws.AccessKey = credentials.StringOf("access_key");
aws.SecretKey = credentials.StringOf("secret_key");
aws.Region = region;
aws.ServiceName = "kms";
aws.SignatureVersion = 4;
var rest = new chilkat.Rest();
rest.ConnectTimeoutMs = 20000;
rest.IdleTimeoutMs = 60000;
rest.VerboseLogging = false;
success = rest.SetAuthAws(aws);
if (success !== true) {
console.log("Could not configure AWS signing.");
return;
}
if (credentials.HasMember("session_token") == true) {
stringCompare.SetString(credentials.StringOf("session_token"));
var stringMatch3 = stringCompare.ContentsEqual("",true);
if ((credentials.JsonTypeOf("session_token") !== 1) || (stringMatch3 == true)) {
console.log("Missing or invalid session_token.");
return;
}
}
var connection = new chilkat.Socket();
connection.RequireSslCertVerify = true;
connection.MaxReadIdleMs = 60000;
connection.MaxSendIdleMs = 60000;
success = connection.Connect(endpoint.GetAsString(),443,true,20000);
if (success !== true) {
console.log("TLS connection failed; inspect diagnostics privately.");
return;
}
success = rest.UseConnection(connection,true);
if (success !== true) {
console.log("Could not attach TLS connection.");
return;
}
// Keep connection alive while Rest uses it.
var body = new chilkat.JsonObject();
var result = new chilkat.JsonObject();
result.Strict = true;
var responseJson;
stringCompare.SetString(credentials.StringOf("key_id"));
var stringMatch4 = stringCompare.ContentsEqual("",true);
if ((credentials.JsonTypeOf("key_id") !== 1) || (stringMatch4 == true)) {
console.log("Missing or invalid key_id.");
return;
}
var keyId = credentials.StringOf("key_id");
var envelope = new chilkat.JsonObject();
envelope.Strict = true;
success = envelope.LoadFile("qa_output/kms_envelope.json");
if (success !== true) {
console.log("Could not load qa_output/kms_envelope.json.");
return;
}
stringCompare.SetString(envelope.StringOf("format"));
var stringMatch5 = stringCompare.ContentsEqual("",true);
if ((envelope.JsonTypeOf("format") !== 1) || (stringMatch5 == true)) {
console.log("Missing or invalid format.");
return;
}
stringCompare.SetString(envelope.StringOf("format"));
var stringMatch6 = stringCompare.ContentsEqual("chilkat-kms-aes256-gcm-v1",true);
if (stringMatch6 !== true) {
console.log("Unexpected format.");
return;
}
stringCompare.SetString(envelope.StringOf("context.Application"));
var stringMatch7 = stringCompare.ContentsEqual("",true);
if ((envelope.JsonTypeOf("context.Application") !== 1) || (stringMatch7 == true)) {
console.log("Missing or invalid context.Application.");
return;
}
stringCompare.SetString(envelope.StringOf("context.Application"));
var stringMatch8 = stringCompare.ContentsEqual("ChilkatKmsExamples",true);
if (stringMatch8 !== true) {
console.log("Unexpected context.Application.");
return;
}
stringCompare.SetString(envelope.StringOf("keyArn"));
var stringMatch9 = stringCompare.ContentsEqual("",true);
if ((envelope.JsonTypeOf("keyArn") !== 1) || (stringMatch9 == true)) {
console.log("Missing or invalid keyArn.");
return;
}
stringCompare.SetString(envelope.StringOf("keyArn"));
var stringMatch10 = stringCompare.ContentsEqual(keyId,true);
if (stringMatch10 !== true) {
console.log("Envelope key differs from the trusted configured key.");
return;
}
stringCompare.SetString(envelope.StringOf("encryptedDataKey"));
var stringMatch11 = stringCompare.ContentsEqual("",true);
if ((envelope.JsonTypeOf("encryptedDataKey") !== 1) || (stringMatch11 == true)) {
console.log("Missing or invalid encryptedDataKey.");
return;
}
var wrappedKey = new chilkat.BinData();
success = wrappedKey.AppendEncoded(envelope.StringOf("encryptedDataKey"),"base64");
if (success !== true) {
console.log("Invalid base64 encryptedDataKey.");
return;
}
if (wrappedKey.NumBytes == 0) {
console.log("Unexpected byte length for encryptedDataKey.");
return;
}
stringCompare.SetString(envelope.StringOf("iv"));
var stringMatch12 = stringCompare.ContentsEqual("",true);
if ((envelope.JsonTypeOf("iv") !== 1) || (stringMatch12 == true)) {
console.log("Missing or invalid iv.");
return;
}
var iv = new chilkat.BinData();
success = iv.AppendEncoded(envelope.StringOf("iv"),"base64");
if (success !== true) {
console.log("Invalid base64 iv.");
return;
}
if (iv.NumBytes !== 12) {
console.log("Unexpected byte length for iv.");
return;
}
stringCompare.SetString(envelope.StringOf("tag"));
var stringMatch13 = stringCompare.ContentsEqual("",true);
if ((envelope.JsonTypeOf("tag") !== 1) || (stringMatch13 == true)) {
console.log("Missing or invalid tag.");
return;
}
var tag = new chilkat.BinData();
success = tag.AppendEncoded(envelope.StringOf("tag"),"base64");
if (success !== true) {
console.log("Invalid base64 tag.");
return;
}
if (tag.NumBytes !== 16) {
console.log("Unexpected byte length for tag.");
return;
}
if (envelope.JsonTypeOf("ciphertext") !== 1) {
console.log("Missing or invalid ciphertext.");
return;
}
var payload = new chilkat.BinData();
success = payload.AppendEncoded(envelope.StringOf("ciphertext"),"base64");
if (success !== true) {
console.log("Invalid ciphertext encoding.");
return;
}
body.Clear();
success = body.UpdateString("KeyId",keyId);
if (success !== true) {
console.log("Could not set KeyId.");
return;
}
success = body.UpdateString("EncryptionContext.Application","ChilkatKmsExamples");
if (success !== true) {
console.log("Could not set EncryptionContext.Application.");
return;
}
success = body.UpdateString("EncryptionAlgorithm","SYMMETRIC_DEFAULT");
if (success !== true) {
console.log("Could not set EncryptionAlgorithm.");
return;
}
success = body.UpdateString("CiphertextBlob",wrappedKey.GetEncoded("base64"));
if (success !== true) {
console.log("Could not set CiphertextBlob.");
return;
}
success = rest.ClearAllQueryParams();
if (success !== true) {
console.log("Could not clear previous query parameters.");
return;
}
// 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) {
console.log("Could not set session token.");
return;
}
}
success = rest.AddHeader("X-Amz-Target","TrentService.Decrypt");
if (success !== true) {
console.log("Could not set operation.");
return;
}
success = rest.AddHeader("Content-Type","application/x-amz-json-1.1");
if (success !== true) {
console.log("Could not set content type.");
return;
}
responseJson = rest.FullRequestString("POST","/",body.Emit());
if (rest.LastMethodSuccess !== true) {
console.log("KMS request did not complete; inspect diagnostics privately. Reconcile any write before retrying.");
return;
}
if (rest.ResponseStatusCode !== 200) {
console.log("KMS HTTP status: " + rest.ResponseStatusCode);
success = result.Load(responseJson);
if (success == true) {
if (result.JsonTypeOf("__type") == 1) {
console.log("AWS error code: " + result.StringOf("__type"));
}
}
console.log("AWS request ID: " + rest.ResponseHdrByName("x-amzn-RequestId"));
// Do not print full bodies, headers, credentials, key material, or tokens.
return;
}
success = result.Load(responseJson);
if (success !== true) {
console.log("Expected a well-formed JSON response.");
return;
}
stringCompare.SetString(result.StringOf("KeyId"));
var stringMatch14 = stringCompare.ContentsEqual("",true);
if ((result.JsonTypeOf("KeyId") !== 1) || (stringMatch14 == true)) {
console.log("Missing or invalid KeyId.");
return;
}
stringCompare.SetString(result.StringOf("KeyId"));
var stringMatch15 = stringCompare.ContentsEqual(keyId,true);
if (stringMatch15 !== true) {
console.log("Response belongs to another key; use a fixed key ARN in configuration.");
return;
}
stringCompare.SetString(result.StringOf("EncryptionAlgorithm"));
var stringMatch16 = stringCompare.ContentsEqual("",true);
if ((result.JsonTypeOf("EncryptionAlgorithm") !== 1) || (stringMatch16 == true)) {
console.log("Missing or invalid EncryptionAlgorithm.");
return;
}
stringCompare.SetString(result.StringOf("EncryptionAlgorithm"));
var stringMatch17 = stringCompare.ContentsEqual("SYMMETRIC_DEFAULT",true);
if (stringMatch17 !== true) {
console.log("Unexpected EncryptionAlgorithm.");
return;
}
stringCompare.SetString(result.StringOf("Plaintext"));
var stringMatch18 = stringCompare.ContentsEqual("",true);
if ((result.JsonTypeOf("Plaintext") !== 1) || (stringMatch18 == true)) {
console.log("Missing or invalid Plaintext.");
return;
}
var dataKey = new chilkat.BinData();
success = dataKey.AppendEncoded(result.StringOf("Plaintext"),"base64");
if (success !== true) {
console.log("Invalid base64 Plaintext.");
return;
}
if (dataKey.NumBytes !== 32) {
console.log("Unexpected byte length for Plaintext.");
return;
}
var aes = new chilkat.Crypt2();
aes.CryptAlgorithm = "aes";
aes.CipherMode = "gcm";
aes.KeyLength = 256;
aes.SetEncodedKey(dataKey.GetEncoded("base64"),"base64");
var authenticatedData = new chilkat.BinData();
success = authenticatedData.AppendString("chilkat-kms-aes256-gcm-v1|Application=ChilkatKmsExamples","utf-8");
if (success !== true) {
console.log("Could not encode authenticated data.");
return;
}
aes.SetEncodedIV(iv.GetEncoded("base64"),"base64");
success = aes.SetEncodedAad(authenticatedData.GetEncoded("base64"),"base64");
if (success !== true) {
console.log("Could not set authenticated data.");
return;
}
success = aes.SetEncodedAuthTag(tag.GetEncoded("base64"),"base64");
if (success !== true) {
console.log("Could not set GCM tag.");
return;
}
success = aes.DecryptBd(payload);
if (success !== true) {
console.log("AES-GCM authentication failed; do not use or save plaintext.");
return;
}
success = payload.WriteFile("qa_output/kms_envelope_plaintext.bin");
if (success !== true) {
console.log("Could not write qa_output/kms_envelope_plaintext.bin.");
return;
}
success = dataKey.SecureClear();
if (success !== true) {
console.log("Could not clear data key buffer.");
return;
}
success = payload.SecureClear();
if (success !== true) {
console.log("Could not clear plaintext buffer.");
return;
}
console.log("Example completed.");
}
chilkatExample();