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 Java Downloads
import com.chilkatsoft.chilkat2.AuthAws;
import com.chilkatsoft.chilkat2.BinData;
import com.chilkatsoft.chilkat2.Cert;
import com.chilkatsoft.chilkat2.ChilkatException;
import com.chilkatsoft.chilkat2.Crypt2;
import com.chilkatsoft.chilkat2.DateTime;
import com.chilkatsoft.chilkat2.JsonObject;
import com.chilkatsoft.chilkat2.PrivateKey;
import com.chilkatsoft.chilkat2.Prng;
import com.chilkatsoft.chilkat2.PublicKey;
import com.chilkatsoft.chilkat2.Rest;
import com.chilkatsoft.chilkat2.Rsa;
import com.chilkatsoft.chilkat2.Socket;
import com.chilkatsoft.chilkat2.StringBuilder;
public class ChilkatExample {
public static void main(String[] args) {
boolean success = false;
StringBuilder stringCompare = new StringBuilder();
// Assumes Chilkat is unlocked. See Global Unlock Sample.
// Keep this credentials file outside public web content and source control.
JsonObject credentials = new JsonObject();
credentials.setStrict(true);
try {
credentials.loadFile("qa_data/aws/kms.json");
} catch (ChilkatException e) {
System.out.println("Could not load private KMS configuration.");
return;
}
stringCompare.setString(credentials.stringOf("access_key"));
boolean stringMatch1 = stringCompare.contentsEqual("", true);
if ((credentials.jsonTypeOf("access_key") != 1) || (stringMatch1)) {
System.out.println("Missing or invalid access_key.");
return;
}
stringCompare.setString(credentials.stringOf("secret_key"));
boolean stringMatch2 = stringCompare.contentsEqual("", true);
if ((credentials.jsonTypeOf("secret_key") != 1) || (stringMatch2)) {
System.out.println("Missing or invalid secret_key.");
return;
}
String region = "us-west-2";
StringBuilder endpoint = new StringBuilder();
endpoint.append("kms.");
endpoint.append(region);
endpoint.append(".amazonaws.com");
AuthAws aws = new AuthAws();
aws.setAccessKey(credentials.stringOf("access_key"));
aws.setSecretKey(credentials.stringOf("secret_key"));
aws.setRegion(region);
aws.setServiceName("kms");
aws.setSignatureVersion(4);
Rest rest = new Rest();
rest.setConnectTimeoutMs(20000);
rest.setIdleTimeoutMs(60000);
rest.setVerboseLogging(false);
try {
rest.setAuthAws(aws);
} catch (ChilkatException e) {
System.out.println("Could not configure AWS signing.");
return;
}
if (credentials.hasMember("session_token")) {
stringCompare.setString(credentials.stringOf("session_token"));
boolean stringMatch3 = stringCompare.contentsEqual("", true);
if ((credentials.jsonTypeOf("session_token") != 1) || (stringMatch3)) {
System.out.println("Missing or invalid session_token.");
return;
}
}
Socket connection = new Socket();
connection.setRequireSslCertVerify(true);
connection.setMaxReadIdleMs(60000);
connection.setMaxSendIdleMs(60000);
try {
connection.connect(endpoint.getAsString(), 443, true, 20000);
} catch (ChilkatException e) {
System.out.println("TLS connection failed; inspect diagnostics privately.");
return;
}
try {
rest.useConnection(connection, true);
} catch (ChilkatException e) {
System.out.println("Could not attach TLS connection.");
return;
}
// Keep connection alive while Rest uses it.
JsonObject body = new JsonObject();
JsonObject result = new JsonObject();
result.setStrict(true);
String responseJson = "";
// pfx_password is a string; an empty string is allowed for an unprotected PFX.
if (credentials.jsonTypeOf("pfx_password") != 1) {
System.out.println("Missing or invalid pfx_password.");
return;
}
Cert cert = new Cert();
try {
cert.loadPfxFile("qa_data/pfx/myCertAndKey.pfx", credentials.stringOf("pfx_password"));
} catch (ChilkatException e) {
System.out.println("Could not load PFX; inspect diagnostics privately.");
return;
}
PrivateKey privKey = new PrivateKey();
try {
cert.getPrivateKey(privKey);
} catch (ChilkatException e) {
System.out.println("PFX does not contain a usable private key.");
return;
}
// Only inspect the PUBLIC JWK to identify a supported key type and curve.
PublicKey sourcePublic = new PublicKey();
try {
privKey.toPublicKey(sourcePublic);
} catch (ChilkatException e) {
System.out.println("Could not get the public key.");
return;
}
String publicJwk;
try {
publicJwk = sourcePublic.getJwk();
} catch (ChilkatException e) {
System.out.println("Could not inspect public key type.");
return;
}
JsonObject keyInfo = new JsonObject();
keyInfo.setStrict(true);
try {
keyInfo.load(publicJwk);
} catch (ChilkatException e) {
System.out.println("Could not parse public key description.");
return;
}
String keySpec = "";
stringCompare.setString(keyInfo.stringOf("kty"));
boolean stringMatch4 = stringCompare.contentsEqual("RSA", true);
if (stringMatch4) {
if (privKey.getBitLength() == 2048) {
keySpec = "RSA_2048";
}
if (privKey.getBitLength() == 3072) {
keySpec = "RSA_3072";
}
if (privKey.getBitLength() == 4096) {
keySpec = "RSA_4096";
}
}
stringCompare.setString(keyInfo.stringOf("kty"));
boolean stringMatch5 = stringCompare.contentsEqual("EC", true);
if (stringMatch5) {
stringCompare.setString(keyInfo.stringOf("crv"));
boolean stringMatch6 = stringCompare.contentsEqual("P-256", true);
if (stringMatch6) {
keySpec = "ECC_NIST_P256";
}
stringCompare.setString(keyInfo.stringOf("crv"));
boolean stringMatch7 = stringCompare.contentsEqual("P-384", true);
if (stringMatch7) {
keySpec = "ECC_NIST_P384";
}
stringCompare.setString(keyInfo.stringOf("crv"));
boolean stringMatch8 = stringCompare.contentsEqual("P-521", true);
if (stringMatch8) {
keySpec = "ECC_NIST_P521";
}
}
stringCompare.setString(keySpec);
boolean stringMatch9 = stringCompare.contentsEqual("", true);
if (stringMatch9) {
System.out.println("Use RSA 2048/3072/4096 or a NIST P-256/P-384/P-521 EC private key.");
return;
}
stringCompare.setString(credentials.stringOf("key_id"));
boolean stringMatch10 = stringCompare.contentsEqual("", true);
if ((credentials.jsonTypeOf("key_id") != 1) || (stringMatch10)) {
System.out.println("Missing or invalid key_id.");
return;
}
String keyId = credentials.stringOf("key_id");
try {
body.updateString("KeyId", keyId);
} catch (ChilkatException e) {
System.out.println("Could not set KeyId.");
return;
}
try {
rest.clearAllQueryParams();
} catch (ChilkatException e) {
System.out.println("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")) {
try {
rest.addQueryParam("X-Amz-Security-Token", credentials.stringOf("session_token"));
} catch (ChilkatException e) {
System.out.println("Could not set session token.");
return;
}
}
try {
rest.addHeader("X-Amz-Target", "TrentService.DescribeKey");
} catch (ChilkatException e) {
System.out.println("Could not set operation.");
return;
}
try {
rest.addHeader("Content-Type", "application/x-amz-json-1.1");
} catch (ChilkatException e) {
System.out.println("Could not set content type.");
return;
}
try {
responseJson = rest.fullRequestString("POST", "/", body.emit());
} catch (ChilkatException e) {
System.out.println("KMS request did not complete; inspect diagnostics privately. Reconcile any write before retrying.");
return;
}
if (rest.getResponseStatusCode() != 200) {
System.out.println("KMS HTTP status: " + rest.getResponseStatusCode());
try {
result.load(responseJson);
success = true;
} catch (ChilkatException e) {
success = false;
}
if (success) {
if (result.jsonTypeOf("__type") == 1) {
System.out.println("AWS error code: " + result.stringOf("__type"));
}
}
System.out.println("AWS request ID: " + rest.responseHdrByName("x-amzn-RequestId"));
// Do not print full bodies, headers, credentials, key material, or tokens.
return;
}
try {
result.load(responseJson);
} catch (ChilkatException e) {
System.out.println("Expected a well-formed JSON response.");
return;
}
stringCompare.setString(result.stringOf("KeyMetadata.KeyId"));
boolean stringMatch11 = stringCompare.contentsEqual("", true);
if ((result.jsonTypeOf("KeyMetadata.KeyId") != 1) || (stringMatch11)) {
System.out.println("Missing or invalid KeyMetadata.KeyId.");
return;
}
stringCompare.setString(result.stringOf("KeyMetadata.Arn"));
boolean stringMatch12 = stringCompare.contentsEqual("", true);
if ((result.jsonTypeOf("KeyMetadata.Arn") != 1) || (stringMatch12)) {
System.out.println("Missing or invalid KeyMetadata.Arn.");
return;
}
stringCompare.setString(result.stringOf("KeyMetadata.Origin"));
boolean stringMatch13 = stringCompare.contentsEqual("EXTERNAL", true);
if (!stringMatch13) {
System.out.println("Destination must have EXTERNAL origin.");
return;
}
stringCompare.setString(result.stringOf("KeyMetadata.KeyState"));
boolean stringMatch21 = stringCompare.contentsEqual("PendingImport", true);
stringCompare.setString(result.stringOf("KeyMetadata.KeyState"));
boolean stringMatch22 = stringCompare.contentsEqual("Enabled", true);
if ((!stringMatch21) && (!stringMatch22)) {
System.out.println("Reimport requires PendingImport or Enabled.");
return;
}
stringCompare.setString(result.stringOf("KeyMetadata.KeyUsage"));
boolean stringMatch15 = stringCompare.contentsEqual("SIGN_VERIFY", true);
if (!stringMatch15) {
System.out.println("Destination must have SIGN_VERIFY usage.");
return;
}
stringCompare.setString(result.stringOf("KeyMetadata.KeySpec"));
boolean stringMatch16 = stringCompare.contentsEqual(keySpec, true);
if (!stringMatch16) {
System.out.println("PFX private key does not match the destination KeySpec.");
return;
}
// Pin subsequent requests to the resolved ARN, not a mutable alias.
keyId = result.stringOf("KeyMetadata.Arn");
body.clear();
try {
body.updateString("KeyId", keyId);
} catch (ChilkatException e) {
System.out.println("Could not set KeyId.");
return;
}
try {
body.updateString("WrappingAlgorithm", "RSA_AES_KEY_WRAP_SHA_256");
} catch (ChilkatException e) {
System.out.println("Could not set WrappingAlgorithm.");
return;
}
try {
body.updateString("WrappingKeySpec", "RSA_4096");
} catch (ChilkatException e) {
System.out.println("Could not set WrappingKeySpec.");
return;
}
try {
rest.clearAllQueryParams();
} catch (ChilkatException e) {
System.out.println("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")) {
try {
rest.addQueryParam("X-Amz-Security-Token", credentials.stringOf("session_token"));
} catch (ChilkatException e) {
System.out.println("Could not set session token.");
return;
}
}
try {
rest.addHeader("X-Amz-Target", "TrentService.GetParametersForImport");
} catch (ChilkatException e) {
System.out.println("Could not set operation.");
return;
}
try {
rest.addHeader("Content-Type", "application/x-amz-json-1.1");
} catch (ChilkatException e) {
System.out.println("Could not set content type.");
return;
}
try {
responseJson = rest.fullRequestString("POST", "/", body.emit());
} catch (ChilkatException e) {
System.out.println("KMS request did not complete; inspect diagnostics privately. Reconcile any write before retrying.");
return;
}
if (rest.getResponseStatusCode() != 200) {
System.out.println("KMS HTTP status: " + rest.getResponseStatusCode());
try {
result.load(responseJson);
success = true;
} catch (ChilkatException e) {
success = false;
}
if (success) {
if (result.jsonTypeOf("__type") == 1) {
System.out.println("AWS error code: " + result.stringOf("__type"));
}
}
System.out.println("AWS request ID: " + rest.responseHdrByName("x-amzn-RequestId"));
// Do not print full bodies, headers, credentials, key material, or tokens.
return;
}
try {
result.load(responseJson);
} catch (ChilkatException e) {
System.out.println("Expected a well-formed JSON response.");
return;
}
stringCompare.setString(result.stringOf("KeyId"));
boolean stringMatch17 = stringCompare.contentsEqual("", true);
if ((result.jsonTypeOf("KeyId") != 1) || (stringMatch17)) {
System.out.println("Missing or invalid KeyId.");
return;
}
stringCompare.setString(result.stringOf("KeyId"));
boolean stringMatch18 = stringCompare.contentsEqual(keyId, true);
if (!stringMatch18) {
System.out.println("Import parameters belong to another key.");
return;
}
stringCompare.setString(result.stringOf("ImportToken"));
boolean stringMatch19 = stringCompare.contentsEqual("", true);
if ((result.jsonTypeOf("ImportToken") != 1) || (stringMatch19)) {
System.out.println("Missing or invalid ImportToken.");
return;
}
stringCompare.setString(result.stringOf("PublicKey"));
boolean stringMatch20 = stringCompare.contentsEqual("", true);
if ((result.jsonTypeOf("PublicKey") != 1) || (stringMatch20)) {
System.out.println("Missing or invalid PublicKey.");
return;
}
if (result.jsonTypeOf("ParametersValidTo") != 2) {
System.out.println("Missing import-parameter expiration.");
return;
}
DateTime now = new DateTime();
DateTime expires = new DateTime();
try {
now.setFromCurrentSystemTime();
} catch (ChilkatException e) {
System.out.println("Could not read current time.");
return;
}
try {
result.dateOf("ParametersValidTo", expires);
} catch (ChilkatException e) {
System.out.println("Invalid import-parameter expiration.");
return;
}
if (expires.diffSeconds(now) <= 0) {
System.out.println("Import parameters have expired; obtain a fresh token and wrapping key together.");
return;
}
String importToken = result.stringOf("ImportToken");
PublicKey wrappingKey = new PublicKey();
try {
wrappingKey.loadBase64(result.stringOf("PublicKey"));
} catch (ChilkatException e) {
System.out.println("Could not load the RSA wrapping key.");
return;
}
if (wrappingKey.getKeySize() != 4096) {
System.out.println("Expected the requested 4096-bit RSA wrapping key.");
return;
}
// Export PKCS#8 DER in memory only; never print or write unencrypted key material.
String pkcs8Base64;
try {
pkcs8Base64 = privKey.getPkcs8ENC("base64");
} catch (ChilkatException e) {
System.out.println("Could not encode the private key as PKCS#8.");
return;
}
Prng prng = new Prng();
// A fresh 32-byte (256-bit) AES key, not a 32-bit key.
String aesKeyBase64;
try {
aesKeyBase64 = prng.genRandom(32, "base64");
} catch (ChilkatException e) {
System.out.println("Could not generate wrapping key.");
return;
}
Crypt2 crypt = new Crypt2();
String wrappedPrivateKey;
try {
wrappedPrivateKey = crypt.aesKeyWrapWithPadding(aesKeyBase64, pkcs8Base64, "base64");
} catch (ChilkatException e) {
System.out.println("AES key wrapping failed.");
return;
}
BinData wrappedAesKey = new BinData();
try {
wrappedAesKey.appendEncoded(aesKeyBase64, "base64");
} catch (ChilkatException e) {
System.out.println("Could not decode AES key.");
return;
}
Rsa rsa = new Rsa();
try {
rsa.usePublicKey(wrappingKey);
} catch (ChilkatException e) {
System.out.println("Could not select the RSA wrapping key.");
return;
}
rsa.setPkcsPadding(false);
rsa.setOaepHash("sha256");
rsa.setOaepMgfHash("sha256");
try {
rsa.encryptBd(wrappedAesKey, false);
} catch (ChilkatException e) {
System.out.println("RSA-OAEP AES-key wrapping failed.");
return;
}
// Wire order is RSA-wrapped AES key FIRST, followed by AES-wrapped PKCS#8.
BinData encryptedMaterial = new BinData();
try {
encryptedMaterial.appendBd(wrappedAesKey);
} catch (ChilkatException e) {
System.out.println("Could not assemble encrypted material.");
return;
}
try {
encryptedMaterial.appendEncoded(wrappedPrivateKey, "base64");
} catch (ChilkatException e) {
System.out.println("Could not append wrapped private key.");
return;
}
body.clear();
try {
body.updateString("KeyId", keyId);
} catch (ChilkatException e) {
System.out.println("Could not set KeyId.");
return;
}
try {
body.updateString("ImportToken", importToken);
} catch (ChilkatException e) {
System.out.println("Could not set ImportToken.");
return;
}
try {
body.updateString("EncryptedKeyMaterial", encryptedMaterial.getEncoded("base64"));
} catch (ChilkatException e) {
System.out.println("Could not set EncryptedKeyMaterial.");
return;
}
DateTime validTo = new DateTime();
try {
validTo.setFromCurrentSystemTime();
} catch (ChilkatException e) {
System.out.println("Could not set expiration time.");
return;
}
try {
validTo.addDays(30);
} catch (ChilkatException e) {
System.out.println("Could not compute expiration.");
return;
}
try {
body.updateNumber("ValidTo", validTo.getAsUnixTimeStr(false));
} catch (ChilkatException e) {
System.out.println("Could not set material expiration.");
return;
}
try {
body.updateString("ExpirationModel", "KEY_MATERIAL_EXPIRES");
} catch (ChilkatException e) {
System.out.println("Could not set ExpirationModel.");
return;
}
try {
rest.clearAllQueryParams();
} catch (ChilkatException e) {
System.out.println("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")) {
try {
rest.addQueryParam("X-Amz-Security-Token", credentials.stringOf("session_token"));
} catch (ChilkatException e) {
System.out.println("Could not set session token.");
return;
}
}
try {
rest.addHeader("X-Amz-Target", "TrentService.ImportKeyMaterial");
} catch (ChilkatException e) {
System.out.println("Could not set operation.");
return;
}
try {
rest.addHeader("Content-Type", "application/x-amz-json-1.1");
} catch (ChilkatException e) {
System.out.println("Could not set content type.");
return;
}
try {
responseJson = rest.fullRequestString("POST", "/", body.emit());
} catch (ChilkatException e) {
System.out.println("KMS request did not complete; inspect diagnostics privately. Reconcile any write before retrying.");
return;
}
if (rest.getResponseStatusCode() != 200) {
System.out.println("KMS HTTP status: " + rest.getResponseStatusCode());
try {
result.load(responseJson);
success = true;
} catch (ChilkatException e) {
success = false;
}
if (success) {
if (result.jsonTypeOf("__type") == 1) {
System.out.println("AWS error code: " + result.stringOf("__type"));
}
}
System.out.println("AWS request ID: " + rest.responseHdrByName("x-amzn-RequestId"));
// Do not print full bodies, headers, credentials, key material, or tokens.
return;
}
// HTTP 200 indicates acceptance; response content can be empty.
System.out.println("Key material import accepted for: " + keyId);
System.out.println("Use DescribeKey to confirm Enabled before signing; KMS is eventually consistent.");
// This does not securely erase copies of sensitive strings from managed memory.
System.out.println("Example completed.");
}
}