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

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.

Decrypt

Chilkat Unicode C++ Downloads

Unicode C++
#include <CkStringBuilderW.h>
#include <CkJsonObjectW.h>
#include <CkAuthAwsW.h>
#include <CkRestW.h>
#include <CkSocketW.h>
#include <CkBinDataW.h>
#include <CkCrypt2W.h>

void ChilkatSample(void)
    {
    bool success = false;

    CkStringBuilderW stringCompare;
    //  Assumes Chilkat is unlocked. See Global Unlock Sample.
    //  Keep this credentials file outside public web content and source control.
    CkJsonObjectW credentials;
    credentials.put_Strict(true);
    success = credentials.LoadFile(L"qa_data/aws/kms.json");
    if (success != true) {
        wprintf(L"Could not load private KMS configuration.\n");
        return;
    }

    stringCompare.SetString(credentials.stringOf(L"access_key"));
    bool stringMatch1 = stringCompare.ContentsEqual(L"",true);
    if ((credentials.JsonTypeOf(L"access_key") != 1) || (stringMatch1 == true)) {
        wprintf(L"Missing or invalid access_key.\n");
        return;
    }

    stringCompare.SetString(credentials.stringOf(L"secret_key"));
    bool stringMatch2 = stringCompare.ContentsEqual(L"",true);
    if ((credentials.JsonTypeOf(L"secret_key") != 1) || (stringMatch2 == true)) {
        wprintf(L"Missing or invalid secret_key.\n");
        return;
    }

    const wchar_t *region = L"us-west-2";
    CkStringBuilderW endpoint;
    endpoint.Append(L"kms.");
    endpoint.Append(region);
    endpoint.Append(L".amazonaws.com");
    CkAuthAwsW aws;
    aws.put_AccessKey(credentials.stringOf(L"access_key"));
    aws.put_SecretKey(credentials.stringOf(L"secret_key"));
    aws.put_Region(region);
    aws.put_ServiceName(L"kms");
    aws.put_SignatureVersion(4);
    CkRestW rest;
    rest.put_ConnectTimeoutMs(20000);
    rest.put_IdleTimeoutMs(60000);
    rest.put_VerboseLogging(false);
    success = rest.SetAuthAws(aws);
    if (success != true) {
        wprintf(L"Could not configure AWS signing.\n");
        return;
    }

    if (credentials.HasMember(L"session_token") == true) {
        stringCompare.SetString(credentials.stringOf(L"session_token"));
        bool stringMatch3 = stringCompare.ContentsEqual(L"",true);
        if ((credentials.JsonTypeOf(L"session_token") != 1) || (stringMatch3 == true)) {
            wprintf(L"Missing or invalid session_token.\n");
            return;
        }

    }

    CkSocketW connection;
    connection.put_RequireSslCertVerify(true);
    connection.put_MaxReadIdleMs(60000);
    connection.put_MaxSendIdleMs(60000);
    success = connection.Connect(endpoint.getAsString(),443,true,20000);
    if (success != true) {
        wprintf(L"TLS connection failed; inspect diagnostics privately.\n");
        return;
    }

    success = rest.UseConnection(connection,true);
    if (success != true) {
        wprintf(L"Could not attach TLS connection.\n");
        return;
    }

    //  Keep connection alive while Rest uses it.
    CkJsonObjectW body;
    CkJsonObjectW result;
    result.put_Strict(true);
    const wchar_t *responseJson = 0;
    stringCompare.SetString(credentials.stringOf(L"key_id"));
    bool stringMatch4 = stringCompare.ContentsEqual(L"",true);
    if ((credentials.JsonTypeOf(L"key_id") != 1) || (stringMatch4 == true)) {
        wprintf(L"Missing or invalid key_id.\n");
        return;
    }

    const wchar_t *keyId = credentials.stringOf(L"key_id");
    CkJsonObjectW envelope;
    envelope.put_Strict(true);
    success = envelope.LoadFile(L"qa_output/kms_envelope.json");
    if (success != true) {
        wprintf(L"Could not load qa_output/kms_envelope.json.\n");
        return;
    }

    stringCompare.SetString(envelope.stringOf(L"format"));
    bool stringMatch5 = stringCompare.ContentsEqual(L"",true);
    if ((envelope.JsonTypeOf(L"format") != 1) || (stringMatch5 == true)) {
        wprintf(L"Missing or invalid format.\n");
        return;
    }

    stringCompare.SetString(envelope.stringOf(L"format"));
    bool stringMatch6 = stringCompare.ContentsEqual(L"chilkat-kms-aes256-gcm-v1",true);
    if (stringMatch6 != true) {
        wprintf(L"Unexpected format.\n");
        return;
    }

    stringCompare.SetString(envelope.stringOf(L"context.Application"));
    bool stringMatch7 = stringCompare.ContentsEqual(L"",true);
    if ((envelope.JsonTypeOf(L"context.Application") != 1) || (stringMatch7 == true)) {
        wprintf(L"Missing or invalid context.Application.\n");
        return;
    }

    stringCompare.SetString(envelope.stringOf(L"context.Application"));
    bool stringMatch8 = stringCompare.ContentsEqual(L"ChilkatKmsExamples",true);
    if (stringMatch8 != true) {
        wprintf(L"Unexpected context.Application.\n");
        return;
    }

    stringCompare.SetString(envelope.stringOf(L"keyArn"));
    bool stringMatch9 = stringCompare.ContentsEqual(L"",true);
    if ((envelope.JsonTypeOf(L"keyArn") != 1) || (stringMatch9 == true)) {
        wprintf(L"Missing or invalid keyArn.\n");
        return;
    }

    stringCompare.SetString(envelope.stringOf(L"keyArn"));
    bool stringMatch10 = stringCompare.ContentsEqual(keyId,true);
    if (stringMatch10 != true) {
        wprintf(L"Envelope key differs from the trusted configured key.\n");
        return;
    }

    stringCompare.SetString(envelope.stringOf(L"encryptedDataKey"));
    bool stringMatch11 = stringCompare.ContentsEqual(L"",true);
    if ((envelope.JsonTypeOf(L"encryptedDataKey") != 1) || (stringMatch11 == true)) {
        wprintf(L"Missing or invalid encryptedDataKey.\n");
        return;
    }

    CkBinDataW wrappedKey;
    success = wrappedKey.AppendEncoded(envelope.stringOf(L"encryptedDataKey"),L"base64");
    if (success != true) {
        wprintf(L"Invalid base64 encryptedDataKey.\n");
        return;
    }

    if (wrappedKey.get_NumBytes() == 0) {
        wprintf(L"Unexpected byte length for encryptedDataKey.\n");
        return;
    }

    stringCompare.SetString(envelope.stringOf(L"iv"));
    bool stringMatch12 = stringCompare.ContentsEqual(L"",true);
    if ((envelope.JsonTypeOf(L"iv") != 1) || (stringMatch12 == true)) {
        wprintf(L"Missing or invalid iv.\n");
        return;
    }

    CkBinDataW iv;
    success = iv.AppendEncoded(envelope.stringOf(L"iv"),L"base64");
    if (success != true) {
        wprintf(L"Invalid base64 iv.\n");
        return;
    }

    if (iv.get_NumBytes() != 12) {
        wprintf(L"Unexpected byte length for iv.\n");
        return;
    }

    stringCompare.SetString(envelope.stringOf(L"tag"));
    bool stringMatch13 = stringCompare.ContentsEqual(L"",true);
    if ((envelope.JsonTypeOf(L"tag") != 1) || (stringMatch13 == true)) {
        wprintf(L"Missing or invalid tag.\n");
        return;
    }

    CkBinDataW tag;
    success = tag.AppendEncoded(envelope.stringOf(L"tag"),L"base64");
    if (success != true) {
        wprintf(L"Invalid base64 tag.\n");
        return;
    }

    if (tag.get_NumBytes() != 16) {
        wprintf(L"Unexpected byte length for tag.\n");
        return;
    }

    if (envelope.JsonTypeOf(L"ciphertext") != 1) {
        wprintf(L"Missing or invalid ciphertext.\n");
        return;
    }

    CkBinDataW payload;
    success = payload.AppendEncoded(envelope.stringOf(L"ciphertext"),L"base64");
    if (success != true) {
        wprintf(L"Invalid ciphertext encoding.\n");
        return;
    }

    body.Clear();
    success = body.UpdateString(L"KeyId",keyId);
    if (success != true) {
        wprintf(L"Could not set KeyId.\n");
        return;
    }

    success = body.UpdateString(L"EncryptionContext.Application",L"ChilkatKmsExamples");
    if (success != true) {
        wprintf(L"Could not set EncryptionContext.Application.\n");
        return;
    }

    success = body.UpdateString(L"EncryptionAlgorithm",L"SYMMETRIC_DEFAULT");
    if (success != true) {
        wprintf(L"Could not set EncryptionAlgorithm.\n");
        return;
    }

    success = body.UpdateString(L"CiphertextBlob",wrappedKey.getEncoded(L"base64"));
    if (success != true) {
        wprintf(L"Could not set CiphertextBlob.\n");
        return;
    }

    success = rest.ClearAllQueryParams();
    if (success != true) {
        wprintf(L"Could not clear previous query parameters.\n");
        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(L"session_token") == true) {
        success = rest.AddQueryParam(L"X-Amz-Security-Token",credentials.stringOf(L"session_token"));
        if (success != true) {
            wprintf(L"Could not set session token.\n");
            return;
        }

    }

    success = rest.AddHeader(L"X-Amz-Target",L"TrentService.Decrypt");
    if (success != true) {
        wprintf(L"Could not set operation.\n");
        return;
    }

    success = rest.AddHeader(L"Content-Type",L"application/x-amz-json-1.1");
    if (success != true) {
        wprintf(L"Could not set content type.\n");
        return;
    }

    responseJson = rest.fullRequestString(L"POST",L"/",body.emit());
    if (rest.get_LastMethodSuccess() != true) {
        wprintf(L"KMS request did not complete; inspect diagnostics privately. Reconcile any write before retrying.\n");
        return;
    }

    if (rest.get_ResponseStatusCode() != 200) {
        wprintf(L"KMS HTTP status: %d\n",rest.get_ResponseStatusCode());
        success = result.Load(responseJson);
        if (success == true) {
            if (result.JsonTypeOf(L"__type") == 1) {
                wprintf(L"AWS error code: %s\n",result.stringOf(L"__type"));
            }

        }

        wprintf(L"AWS request ID: %s\n",rest.responseHdrByName(L"x-amzn-RequestId"));
        //  Do not print full bodies, headers, credentials, key material, or tokens.
        return;
    }

    success = result.Load(responseJson);
    if (success != true) {
        wprintf(L"Expected a well-formed JSON response.\n");
        return;
    }

    stringCompare.SetString(result.stringOf(L"KeyId"));
    bool stringMatch14 = stringCompare.ContentsEqual(L"",true);
    if ((result.JsonTypeOf(L"KeyId") != 1) || (stringMatch14 == true)) {
        wprintf(L"Missing or invalid KeyId.\n");
        return;
    }

    stringCompare.SetString(result.stringOf(L"KeyId"));
    bool stringMatch15 = stringCompare.ContentsEqual(keyId,true);
    if (stringMatch15 != true) {
        wprintf(L"Response belongs to another key; use a fixed key ARN in configuration.\n");
        return;
    }

    stringCompare.SetString(result.stringOf(L"EncryptionAlgorithm"));
    bool stringMatch16 = stringCompare.ContentsEqual(L"",true);
    if ((result.JsonTypeOf(L"EncryptionAlgorithm") != 1) || (stringMatch16 == true)) {
        wprintf(L"Missing or invalid EncryptionAlgorithm.\n");
        return;
    }

    stringCompare.SetString(result.stringOf(L"EncryptionAlgorithm"));
    bool stringMatch17 = stringCompare.ContentsEqual(L"SYMMETRIC_DEFAULT",true);
    if (stringMatch17 != true) {
        wprintf(L"Unexpected EncryptionAlgorithm.\n");
        return;
    }

    stringCompare.SetString(result.stringOf(L"Plaintext"));
    bool stringMatch18 = stringCompare.ContentsEqual(L"",true);
    if ((result.JsonTypeOf(L"Plaintext") != 1) || (stringMatch18 == true)) {
        wprintf(L"Missing or invalid Plaintext.\n");
        return;
    }

    CkBinDataW dataKey;
    success = dataKey.AppendEncoded(result.stringOf(L"Plaintext"),L"base64");
    if (success != true) {
        wprintf(L"Invalid base64 Plaintext.\n");
        return;
    }

    if (dataKey.get_NumBytes() != 32) {
        wprintf(L"Unexpected byte length for Plaintext.\n");
        return;
    }

    CkCrypt2W aes;
    aes.put_CryptAlgorithm(L"aes");
    aes.put_CipherMode(L"gcm");
    aes.put_KeyLength(256);
    aes.SetEncodedKey(dataKey.getEncoded(L"base64"),L"base64");
    CkBinDataW authenticatedData;
    success = authenticatedData.AppendString(L"chilkat-kms-aes256-gcm-v1|Application=ChilkatKmsExamples",L"utf-8");
    if (success != true) {
        wprintf(L"Could not encode authenticated data.\n");
        return;
    }

    aes.SetEncodedIV(iv.getEncoded(L"base64"),L"base64");
    success = aes.SetEncodedAad(authenticatedData.getEncoded(L"base64"),L"base64");
    if (success != true) {
        wprintf(L"Could not set authenticated data.\n");
        return;
    }

    success = aes.SetEncodedAuthTag(tag.getEncoded(L"base64"),L"base64");
    if (success != true) {
        wprintf(L"Could not set GCM tag.\n");
        return;
    }

    success = aes.DecryptBd(payload);
    if (success != true) {
        wprintf(L"AES-GCM authentication failed; do not use or save plaintext.\n");
        return;
    }

    success = payload.WriteFile(L"qa_output/kms_envelope_plaintext.bin");
    if (success != true) {
        wprintf(L"Could not write qa_output/kms_envelope_plaintext.bin.\n");
        return;
    }

    success = dataKey.SecureClear();
    if (success != true) {
        wprintf(L"Could not clear data key buffer.\n");
        return;
    }

    success = payload.SecureClear();
    if (success != true) {
        wprintf(L"Could not clear plaintext buffer.\n");
        return;
    }

    wprintf(L"Example completed.\n");
    }