AWS KMS: Reimport the Same PFX Key Material with a New Expiration
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 the same checked RSA/AES wrapping flow as the existing low-level import example. Provide pfx_password and key_id and the private qa_data/pfx/myCertAndKey.pfx. Requires the exact original private key for this asymmetric KMS key; new material cannot replace it. Allows Enabled or PendingImport. ImportType is omitted because that field applies only to symmetric encryption keys. Material expires 30 days from execution (distinct from the wrapping-token lifetime). Expiration disables cryptographic use until the same material is reimported. Retain a protected original backup. Hybrid wrapping is unavailable in China Regions.
API actions used: kms:DescribeKey, kms:GetParametersForImport, kms:ImportKeyMaterial. IAM permissions and key policies must allow the actual resources; grant and multi-Region workflows can need permissions in more than one region/account.
DescribeKey | GetParametersForImport | ImportKeyMaterial
Chilkat Unicode C++ Downloads
#include <CkStringBuilderW.h>
#include <CkJsonObjectW.h>
#include <CkAuthAwsW.h>
#include <CkRestW.h>
#include <CkSocketW.h>
#include <CkCertW.h>
#include <CkPrivateKeyW.h>
#include <CkPublicKeyW.h>
#include <CkDateTimeW.h>
#include <CkPrngW.h>
#include <CkCrypt2W.h>
#include <CkBinDataW.h>
#include <CkRsaW.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;
// pfx_password is a string; an empty string is allowed for an unprotected PFX.
if (credentials.JsonTypeOf(L"pfx_password") != 1) {
wprintf(L"Missing or invalid pfx_password.\n");
return;
}
CkCertW cert;
success = cert.LoadPfxFile(L"qa_data/pfx/myCertAndKey.pfx",credentials.stringOf(L"pfx_password"));
if (success != true) {
wprintf(L"Could not load PFX; inspect diagnostics privately.\n");
return;
}
CkPrivateKeyW privKey;
success = cert.GetPrivateKey(privKey);
if (success != true) {
wprintf(L"PFX does not contain a usable private key.\n");
return;
}
// Only inspect the PUBLIC JWK to identify a supported key type and curve.
CkPublicKeyW sourcePublic;
success = privKey.ToPublicKey(sourcePublic);
if (success != true) {
wprintf(L"Could not get the public key.\n");
return;
}
const wchar_t *publicJwk = sourcePublic.getJwk();
if (sourcePublic.get_LastMethodSuccess() != true) {
wprintf(L"Could not inspect public key type.\n");
return;
}
CkJsonObjectW keyInfo;
keyInfo.put_Strict(true);
success = keyInfo.Load(publicJwk);
if (success != true) {
wprintf(L"Could not parse public key description.\n");
return;
}
const wchar_t *keySpec = L"";
stringCompare.SetString(keyInfo.stringOf(L"kty"));
bool stringMatch4 = stringCompare.ContentsEqual(L"RSA",true);
if (stringMatch4 == true) {
if (privKey.get_BitLength() == 2048) {
keySpec = L"RSA_2048";
}
if (privKey.get_BitLength() == 3072) {
keySpec = L"RSA_3072";
}
if (privKey.get_BitLength() == 4096) {
keySpec = L"RSA_4096";
}
}
stringCompare.SetString(keyInfo.stringOf(L"kty"));
bool stringMatch5 = stringCompare.ContentsEqual(L"EC",true);
if (stringMatch5 == true) {
stringCompare.SetString(keyInfo.stringOf(L"crv"));
bool stringMatch6 = stringCompare.ContentsEqual(L"P-256",true);
if (stringMatch6 == true) {
keySpec = L"ECC_NIST_P256";
}
stringCompare.SetString(keyInfo.stringOf(L"crv"));
bool stringMatch7 = stringCompare.ContentsEqual(L"P-384",true);
if (stringMatch7 == true) {
keySpec = L"ECC_NIST_P384";
}
stringCompare.SetString(keyInfo.stringOf(L"crv"));
bool stringMatch8 = stringCompare.ContentsEqual(L"P-521",true);
if (stringMatch8 == true) {
keySpec = L"ECC_NIST_P521";
}
}
stringCompare.SetString(keySpec);
bool stringMatch9 = stringCompare.ContentsEqual(L"",true);
if (stringMatch9 == true) {
wprintf(L"Use RSA 2048/3072/4096 or a NIST P-256/P-384/P-521 EC private key.\n");
return;
}
stringCompare.SetString(credentials.stringOf(L"key_id"));
bool stringMatch10 = stringCompare.ContentsEqual(L"",true);
if ((credentials.JsonTypeOf(L"key_id") != 1) || (stringMatch10 == true)) {
wprintf(L"Missing or invalid key_id.\n");
return;
}
const wchar_t *keyId = credentials.stringOf(L"key_id");
success = body.UpdateString(L"KeyId",keyId);
if (success != true) {
wprintf(L"Could not set KeyId.\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.DescribeKey");
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"KeyMetadata.KeyId"));
bool stringMatch11 = stringCompare.ContentsEqual(L"",true);
if ((result.JsonTypeOf(L"KeyMetadata.KeyId") != 1) || (stringMatch11 == true)) {
wprintf(L"Missing or invalid KeyMetadata.KeyId.\n");
return;
}
stringCompare.SetString(result.stringOf(L"KeyMetadata.Arn"));
bool stringMatch12 = stringCompare.ContentsEqual(L"",true);
if ((result.JsonTypeOf(L"KeyMetadata.Arn") != 1) || (stringMatch12 == true)) {
wprintf(L"Missing or invalid KeyMetadata.Arn.\n");
return;
}
stringCompare.SetString(result.stringOf(L"KeyMetadata.Origin"));
bool stringMatch13 = stringCompare.ContentsEqual(L"EXTERNAL",true);
if (stringMatch13 != true) {
wprintf(L"Destination must have EXTERNAL origin.\n");
return;
}
stringCompare.SetString(result.stringOf(L"KeyMetadata.KeyState"));
bool stringMatch21 = stringCompare.ContentsEqual(L"PendingImport",true);
stringCompare.SetString(result.stringOf(L"KeyMetadata.KeyState"));
bool stringMatch22 = stringCompare.ContentsEqual(L"Enabled",true);
if ((stringMatch21 != true) && (stringMatch22 != true)) {
wprintf(L"Reimport requires PendingImport or Enabled.\n");
return;
}
stringCompare.SetString(result.stringOf(L"KeyMetadata.KeyUsage"));
bool stringMatch15 = stringCompare.ContentsEqual(L"SIGN_VERIFY",true);
if (stringMatch15 != true) {
wprintf(L"Destination must have SIGN_VERIFY usage.\n");
return;
}
stringCompare.SetString(result.stringOf(L"KeyMetadata.KeySpec"));
bool stringMatch16 = stringCompare.ContentsEqual(keySpec,true);
if (stringMatch16 != true) {
wprintf(L"PFX private key does not match the destination KeySpec.\n");
return;
}
// Pin subsequent requests to the resolved ARN, not a mutable alias.
keyId = result.stringOf(L"KeyMetadata.Arn");
body.Clear();
success = body.UpdateString(L"KeyId",keyId);
if (success != true) {
wprintf(L"Could not set KeyId.\n");
return;
}
success = body.UpdateString(L"WrappingAlgorithm",L"RSA_AES_KEY_WRAP_SHA_256");
if (success != true) {
wprintf(L"Could not set WrappingAlgorithm.\n");
return;
}
success = body.UpdateString(L"WrappingKeySpec",L"RSA_4096");
if (success != true) {
wprintf(L"Could not set WrappingKeySpec.\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.GetParametersForImport");
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 stringMatch17 = stringCompare.ContentsEqual(L"",true);
if ((result.JsonTypeOf(L"KeyId") != 1) || (stringMatch17 == true)) {
wprintf(L"Missing or invalid KeyId.\n");
return;
}
stringCompare.SetString(result.stringOf(L"KeyId"));
bool stringMatch18 = stringCompare.ContentsEqual(keyId,true);
if (stringMatch18 != true) {
wprintf(L"Import parameters belong to another key.\n");
return;
}
stringCompare.SetString(result.stringOf(L"ImportToken"));
bool stringMatch19 = stringCompare.ContentsEqual(L"",true);
if ((result.JsonTypeOf(L"ImportToken") != 1) || (stringMatch19 == true)) {
wprintf(L"Missing or invalid ImportToken.\n");
return;
}
stringCompare.SetString(result.stringOf(L"PublicKey"));
bool stringMatch20 = stringCompare.ContentsEqual(L"",true);
if ((result.JsonTypeOf(L"PublicKey") != 1) || (stringMatch20 == true)) {
wprintf(L"Missing or invalid PublicKey.\n");
return;
}
if (result.JsonTypeOf(L"ParametersValidTo") != 2) {
wprintf(L"Missing import-parameter expiration.\n");
return;
}
CkDateTimeW now;
CkDateTimeW expires;
success = now.SetFromCurrentSystemTime();
if (success != true) {
wprintf(L"Could not read current time.\n");
return;
}
success = result.DateOf(L"ParametersValidTo",expires);
if (success != true) {
wprintf(L"Invalid import-parameter expiration.\n");
return;
}
if (expires.DiffSeconds(now) <= 0) {
wprintf(L"Import parameters have expired; obtain a fresh token and wrapping key together.\n");
return;
}
const wchar_t *importToken = result.stringOf(L"ImportToken");
CkPublicKeyW wrappingKey;
success = wrappingKey.LoadBase64(result.stringOf(L"PublicKey"));
if (success != true) {
wprintf(L"Could not load the RSA wrapping key.\n");
return;
}
if (wrappingKey.get_KeySize() != 4096) {
wprintf(L"Expected the requested 4096-bit RSA wrapping key.\n");
return;
}
// Export PKCS#8 DER in memory only; never print or write unencrypted key material.
const wchar_t *pkcs8Base64 = privKey.getPkcs8ENC(L"base64");
if (privKey.get_LastMethodSuccess() != true) {
wprintf(L"Could not encode the private key as PKCS#8.\n");
return;
}
CkPrngW prng;
// A fresh 32-byte (256-bit) AES key, not a 32-bit key.
const wchar_t *aesKeyBase64 = prng.genRandom(32,L"base64");
if (prng.get_LastMethodSuccess() != true) {
wprintf(L"Could not generate wrapping key.\n");
return;
}
CkCrypt2W crypt;
const wchar_t *wrappedPrivateKey = crypt.aesKeyWrapWithPadding(aesKeyBase64,pkcs8Base64,L"base64");
if (crypt.get_LastMethodSuccess() != true) {
wprintf(L"AES key wrapping failed.\n");
return;
}
CkBinDataW wrappedAesKey;
success = wrappedAesKey.AppendEncoded(aesKeyBase64,L"base64");
if (success != true) {
wprintf(L"Could not decode AES key.\n");
return;
}
CkRsaW rsa;
success = rsa.UsePublicKey(wrappingKey);
if (success != true) {
wprintf(L"Could not select the RSA wrapping key.\n");
return;
}
rsa.put_PkcsPadding(false);
rsa.put_OaepHash(L"sha256");
rsa.put_OaepMgfHash(L"sha256");
success = rsa.EncryptBd(wrappedAesKey,false);
if (success != true) {
wprintf(L"RSA-OAEP AES-key wrapping failed.\n");
return;
}
// Wire order is RSA-wrapped AES key FIRST, followed by AES-wrapped PKCS#8.
CkBinDataW encryptedMaterial;
success = encryptedMaterial.AppendBd(wrappedAesKey);
if (success != true) {
wprintf(L"Could not assemble encrypted material.\n");
return;
}
success = encryptedMaterial.AppendEncoded(wrappedPrivateKey,L"base64");
if (success != true) {
wprintf(L"Could not append wrapped private key.\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"ImportToken",importToken);
if (success != true) {
wprintf(L"Could not set ImportToken.\n");
return;
}
success = body.UpdateString(L"EncryptedKeyMaterial",encryptedMaterial.getEncoded(L"base64"));
if (success != true) {
wprintf(L"Could not set EncryptedKeyMaterial.\n");
return;
}
CkDateTimeW validTo;
success = validTo.SetFromCurrentSystemTime();
if (success != true) {
wprintf(L"Could not set expiration time.\n");
return;
}
success = validTo.AddDays(30);
if (success != true) {
wprintf(L"Could not compute expiration.\n");
return;
}
success = body.UpdateNumber(L"ValidTo",validTo.getAsUnixTimeStr(false));
if (success != true) {
wprintf(L"Could not set material expiration.\n");
return;
}
success = body.UpdateString(L"ExpirationModel",L"KEY_MATERIAL_EXPIRES");
if (success != true) {
wprintf(L"Could not set ExpirationModel.\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.ImportKeyMaterial");
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;
}
// HTTP 200 indicates acceptance; response content can be empty.
wprintf(L"Key material import accepted for: %s\n",keyId);
wprintf(L"Use DescribeKey to confirm Enabled before signing; KMS is eventually consistent.\n");
// This does not securely erase copies of sensitive strings from managed memory.
wprintf(L"Example completed.\n");
}