AWS KMS: Import a PFX Signing Key with a 30-Day 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 an EXTERNAL PendingImport signing key matching the PFX key specification. 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 B4X Downloads
Dim success As Boolean = False
Dim stringCompare As ChilkatStringBuilder
stringCompare.Initialize
' Assumes Chilkat is unlocked. See Global Unlock Sample.
' Keep this credentials file outside public web content and source control.
Dim credentials As ChilkatJsonObject
credentials.Initialize
credentials.Strict = True
success = credentials.LoadFile("qa_data/aws/kms.json")
If success <> True Then
Log("Could not load private KMS configuration.")
Return
End If
stringCompare.SetString(credentials.StringOf("access_key"))
Dim stringMatch1 As Boolean = stringCompare.ContentsEqual("", True)
If (credentials.JsonTypeOf("access_key") <> 1) Or (stringMatch1 = True) Then
Log("Missing or invalid access_key.")
Return
End If
stringCompare.SetString(credentials.StringOf("secret_key"))
Dim stringMatch2 As Boolean = stringCompare.ContentsEqual("", True)
If (credentials.JsonTypeOf("secret_key") <> 1) Or (stringMatch2 = True) Then
Log("Missing or invalid secret_key.")
Return
End If
Dim region As String = "us-west-2"
Dim endpoint As ChilkatStringBuilder
endpoint.Initialize
endpoint.Append("kms.")
endpoint.Append(region)
endpoint.Append(".amazonaws.com")
Dim aws As ChilkatAuthAws
aws.Initialize
aws.AccessKey = credentials.StringOf("access_key")
aws.SecretKey = credentials.StringOf("secret_key")
aws.Region = region
aws.ServiceName = "kms"
aws.SignatureVersion = 4
Dim rest As ChilkatRest
rest.Initialize("rest")
rest.ConnectTimeoutMs = 20000
rest.IdleTimeoutMs = 60000
rest.VerboseLogging = False
success = rest.SetAuthAws(aws)
If success <> True Then
Log("Could not configure AWS signing.")
Return
End If
If credentials.HasMember("session_token") = True Then
stringCompare.SetString(credentials.StringOf("session_token"))
Dim stringMatch3 As Boolean = stringCompare.ContentsEqual("", True)
If (credentials.JsonTypeOf("session_token") <> 1) Or (stringMatch3 = True) Then
Log("Missing or invalid session_token.")
Return
End If
End If
Dim connection As ChilkatSocket
connection.Initialize("connection")
connection.RequireSslCertVerify = True
connection.MaxReadIdleMs = 60000
connection.MaxSendIdleMs = 60000
success = connection.Connect(endpoint.GetAsString, 443, True, 20000)
If success <> True Then
Log("TLS connection failed; inspect diagnostics privately.")
Return
End If
success = rest.UseConnection(connection, True)
If success <> True Then
Log("Could not attach TLS connection.")
Return
End If
' Keep connection alive while Rest uses it.
Dim body As ChilkatJsonObject
body.Initialize
Dim result As ChilkatJsonObject
result.Initialize
result.Strict = True
Dim responseJson As String
' pfx_password is a string; an empty string is allowed for an unprotected PFX.
If credentials.JsonTypeOf("pfx_password") <> 1 Then
Log("Missing or invalid pfx_password.")
Return
End If
Dim cert As ChilkatCert
cert.Initialize("cert")
success = cert.LoadPfxFile("qa_data/pfx/myCertAndKey.pfx", credentials.StringOf("pfx_password"))
If success <> True Then
Log("Could not load PFX; inspect diagnostics privately.")
Return
End If
Dim privKey As ChilkatPrivateKey
privKey.Initialize("privKey")
success = cert.GetPrivateKey(privKey)
If success <> True Then
Log("PFX does not contain a usable private key.")
Return
End If
' Only inspect the PUBLIC JWK to identify a supported key type and curve.
Dim sourcePublic As ChilkatPublicKey
sourcePublic.Initialize
success = privKey.ToPublicKey(sourcePublic)
If success <> True Then
Log("Could not get the public key.")
Return
End If
Dim publicJwk As String = sourcePublic.GetJwk
If sourcePublic.LastMethodSuccess <> True Then
Log("Could not inspect public key type.")
Return
End If
Dim keyInfo As ChilkatJsonObject
keyInfo.Initialize
keyInfo.Strict = True
success = keyInfo.Load(publicJwk)
If success <> True Then
Log("Could not parse public key description.")
Return
End If
Dim keySpec As String = ""
stringCompare.SetString(keyInfo.StringOf("kty"))
Dim stringMatch4 As Boolean = stringCompare.ContentsEqual("RSA", True)
If stringMatch4 = True Then
If privKey.BitLength = 2048 Then
keySpec = "RSA_2048"
End If
If privKey.BitLength = 3072 Then
keySpec = "RSA_3072"
End If
If privKey.BitLength = 4096 Then
keySpec = "RSA_4096"
End If
End If
stringCompare.SetString(keyInfo.StringOf("kty"))
Dim stringMatch5 As Boolean = stringCompare.ContentsEqual("EC", True)
If stringMatch5 = True Then
stringCompare.SetString(keyInfo.StringOf("crv"))
Dim stringMatch6 As Boolean = stringCompare.ContentsEqual("P-256", True)
If stringMatch6 = True Then
keySpec = "ECC_NIST_P256"
End If
stringCompare.SetString(keyInfo.StringOf("crv"))
Dim stringMatch7 As Boolean = stringCompare.ContentsEqual("P-384", True)
If stringMatch7 = True Then
keySpec = "ECC_NIST_P384"
End If
stringCompare.SetString(keyInfo.StringOf("crv"))
Dim stringMatch8 As Boolean = stringCompare.ContentsEqual("P-521", True)
If stringMatch8 = True Then
keySpec = "ECC_NIST_P521"
End If
End If
stringCompare.SetString(keySpec)
Dim stringMatch9 As Boolean = stringCompare.ContentsEqual("", True)
If stringMatch9 = True Then
Log("Use RSA 2048/3072/4096 or a NIST P-256/P-384/P-521 EC private key.")
Return
End If
stringCompare.SetString(credentials.StringOf("key_id"))
Dim stringMatch10 As Boolean = stringCompare.ContentsEqual("", True)
If (credentials.JsonTypeOf("key_id") <> 1) Or (stringMatch10 = True) Then
Log("Missing or invalid key_id.")
Return
End If
Dim keyId As String = credentials.StringOf("key_id")
success = body.UpdateString("KeyId", keyId)
If success <> True Then
Log("Could not set KeyId.")
Return
End If
success = rest.ClearAllQueryParams
If success <> True Then
Log("Could not clear previous query parameters.")
Return
End If
' 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 Then
success = rest.AddQueryParam("X-Amz-Security-Token", credentials.StringOf("session_token"))
If success <> True Then
Log("Could not set session token.")
Return
End If
End If
success = rest.AddHeader("X-Amz-Target", "TrentService.DescribeKey")
If success <> True Then
Log("Could not set operation.")
Return
End If
success = rest.AddHeader("Content-Type", "application/x-amz-json-1.1")
If success <> True Then
Log("Could not set content type.")
Return
End If
responseJson = rest.FullRequestString("POST", "/", body.Emit)
If rest.LastMethodSuccess <> True Then
Log("KMS request did not complete; inspect diagnostics privately. Reconcile any write before retrying.")
Return
End If
If rest.ResponseStatusCode <> 200 Then
Log("KMS HTTP status: " & rest.ResponseStatusCode)
success = result.Load(responseJson)
If success = True Then
If result.JsonTypeOf("__type") = 1 Then
Log("AWS error code: " & result.StringOf("__type"))
End If
End If
Log("AWS request ID: " & rest.ResponseHdrByName("x-amzn-RequestId"))
' Do not print full bodies, headers, credentials, key material, or tokens.
Return
End If
success = result.Load(responseJson)
If success <> True Then
Log("Expected a well-formed JSON response.")
Return
End If
stringCompare.SetString(result.StringOf("KeyMetadata.KeyId"))
Dim stringMatch11 As Boolean = stringCompare.ContentsEqual("", True)
If (result.JsonTypeOf("KeyMetadata.KeyId") <> 1) Or (stringMatch11 = True) Then
Log("Missing or invalid KeyMetadata.KeyId.")
Return
End If
stringCompare.SetString(result.StringOf("KeyMetadata.Arn"))
Dim stringMatch12 As Boolean = stringCompare.ContentsEqual("", True)
If (result.JsonTypeOf("KeyMetadata.Arn") <> 1) Or (stringMatch12 = True) Then
Log("Missing or invalid KeyMetadata.Arn.")
Return
End If
stringCompare.SetString(result.StringOf("KeyMetadata.Origin"))
Dim stringMatch13 As Boolean = stringCompare.ContentsEqual("EXTERNAL", True)
If stringMatch13 <> True Then
Log("Destination must have EXTERNAL origin.")
Return
End If
stringCompare.SetString(result.StringOf("KeyMetadata.KeyState"))
Dim stringMatch14 As Boolean = stringCompare.ContentsEqual("PendingImport", True)
If stringMatch14 <> True Then
Log("This initial-import sample requires PendingImport; it does not replace existing material.")
Return
End If
stringCompare.SetString(result.StringOf("KeyMetadata.KeyUsage"))
Dim stringMatch15 As Boolean = stringCompare.ContentsEqual("SIGN_VERIFY", True)
If stringMatch15 <> True Then
Log("Destination must have SIGN_VERIFY usage.")
Return
End If
stringCompare.SetString(result.StringOf("KeyMetadata.KeySpec"))
Dim stringMatch16 As Boolean = stringCompare.ContentsEqual(keySpec, True)
If stringMatch16 <> True Then
Log("PFX private key does not match the destination KeySpec.")
Return
End If
' Pin subsequent requests to the resolved ARN, not a mutable alias.
keyId = result.StringOf("KeyMetadata.Arn")
body.Clear
success = body.UpdateString("KeyId", keyId)
If success <> True Then
Log("Could not set KeyId.")
Return
End If
success = body.UpdateString("WrappingAlgorithm", "RSA_AES_KEY_WRAP_SHA_256")
If success <> True Then
Log("Could not set WrappingAlgorithm.")
Return
End If
success = body.UpdateString("WrappingKeySpec", "RSA_4096")
If success <> True Then
Log("Could not set WrappingKeySpec.")
Return
End If
success = rest.ClearAllQueryParams
If success <> True Then
Log("Could not clear previous query parameters.")
Return
End If
' 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 Then
success = rest.AddQueryParam("X-Amz-Security-Token", credentials.StringOf("session_token"))
If success <> True Then
Log("Could not set session token.")
Return
End If
End If
success = rest.AddHeader("X-Amz-Target", "TrentService.GetParametersForImport")
If success <> True Then
Log("Could not set operation.")
Return
End If
success = rest.AddHeader("Content-Type", "application/x-amz-json-1.1")
If success <> True Then
Log("Could not set content type.")
Return
End If
responseJson = rest.FullRequestString("POST", "/", body.Emit)
If rest.LastMethodSuccess <> True Then
Log("KMS request did not complete; inspect diagnostics privately. Reconcile any write before retrying.")
Return
End If
If rest.ResponseStatusCode <> 200 Then
Log("KMS HTTP status: " & rest.ResponseStatusCode)
success = result.Load(responseJson)
If success = True Then
If result.JsonTypeOf("__type") = 1 Then
Log("AWS error code: " & result.StringOf("__type"))
End If
End If
Log("AWS request ID: " & rest.ResponseHdrByName("x-amzn-RequestId"))
' Do not print full bodies, headers, credentials, key material, or tokens.
Return
End If
success = result.Load(responseJson)
If success <> True Then
Log("Expected a well-formed JSON response.")
Return
End If
stringCompare.SetString(result.StringOf("KeyId"))
Dim stringMatch17 As Boolean = stringCompare.ContentsEqual("", True)
If (result.JsonTypeOf("KeyId") <> 1) Or (stringMatch17 = True) Then
Log("Missing or invalid KeyId.")
Return
End If
stringCompare.SetString(result.StringOf("KeyId"))
Dim stringMatch18 As Boolean = stringCompare.ContentsEqual(keyId, True)
If stringMatch18 <> True Then
Log("Import parameters belong to another key.")
Return
End If
stringCompare.SetString(result.StringOf("ImportToken"))
Dim stringMatch19 As Boolean = stringCompare.ContentsEqual("", True)
If (result.JsonTypeOf("ImportToken") <> 1) Or (stringMatch19 = True) Then
Log("Missing or invalid ImportToken.")
Return
End If
stringCompare.SetString(result.StringOf("PublicKey"))
Dim stringMatch20 As Boolean = stringCompare.ContentsEqual("", True)
If (result.JsonTypeOf("PublicKey") <> 1) Or (stringMatch20 = True) Then
Log("Missing or invalid PublicKey.")
Return
End If
If result.JsonTypeOf("ParametersValidTo") <> 2 Then
Log("Missing import-parameter expiration.")
Return
End If
Dim now As ChilkatDateTime
now.Initialize
Dim expires As ChilkatDateTime
expires.Initialize
success = now.SetFromCurrentSystemTime
If success <> True Then
Log("Could not read current time.")
Return
End If
success = result.DateOf("ParametersValidTo", expires)
If success <> True Then
Log("Invalid import-parameter expiration.")
Return
End If
If expires.DiffSeconds(now) <= 0 Then
Log("Import parameters have expired; obtain a fresh token and wrapping key together.")
Return
End If
Dim importToken As String = result.StringOf("ImportToken")
Dim wrappingKey As ChilkatPublicKey
wrappingKey.Initialize
success = wrappingKey.LoadBase64(result.StringOf("PublicKey"))
If success <> True Then
Log("Could not load the RSA wrapping key.")
Return
End If
If wrappingKey.KeySize <> 4096 Then
Log("Expected the requested 4096-bit RSA wrapping key.")
Return
End If
' Export PKCS#8 DER in memory only; never print or write unencrypted key material.
Dim pkcs8Base64 As String = privKey.GetPkcs8ENC("base64")
If privKey.LastMethodSuccess <> True Then
Log("Could not encode the private key as PKCS#8.")
Return
End If
Dim prng As ChilkatPrng
prng.Initialize
' A fresh 32-byte (256-bit) AES key, not a 32-bit key.
Dim aesKeyBase64 As String = prng.GenRandom(32, "base64")
If prng.LastMethodSuccess <> True Then
Log("Could not generate wrapping key.")
Return
End If
Dim crypt As ChilkatCrypt2
crypt.Initialize("crypt")
Dim wrappedPrivateKey As String = crypt.AesKeyWrapWithPadding(aesKeyBase64, pkcs8Base64, "base64")
If crypt.LastMethodSuccess <> True Then
Log("AES key wrapping failed.")
Return
End If
Dim wrappedAesKey As ChilkatBinData
wrappedAesKey.Initialize
success = wrappedAesKey.AppendEncoded(aesKeyBase64, "base64")
If success <> True Then
Log("Could not decode AES key.")
Return
End If
Dim rsa As ChilkatRsa
rsa.Initialize
success = rsa.UsePublicKey(wrappingKey)
If success <> True Then
Log("Could not select the RSA wrapping key.")
Return
End If
rsa.PkcsPadding = False
rsa.OaepHash = "sha256"
rsa.OaepMgfHash = "sha256"
success = rsa.EncryptBd(wrappedAesKey, False)
If success <> True Then
Log("RSA-OAEP AES-key wrapping failed.")
Return
End If
' Wire order is RSA-wrapped AES key FIRST, followed by AES-wrapped PKCS#8.
Dim encryptedMaterial As ChilkatBinData
encryptedMaterial.Initialize
success = encryptedMaterial.AppendBd(wrappedAesKey)
If success <> True Then
Log("Could not assemble encrypted material.")
Return
End If
success = encryptedMaterial.AppendEncoded(wrappedPrivateKey, "base64")
If success <> True Then
Log("Could not append wrapped private key.")
Return
End If
body.Clear
success = body.UpdateString("KeyId", keyId)
If success <> True Then
Log("Could not set KeyId.")
Return
End If
success = body.UpdateString("ImportToken", importToken)
If success <> True Then
Log("Could not set ImportToken.")
Return
End If
success = body.UpdateString("EncryptedKeyMaterial", encryptedMaterial.GetEncoded("base64"))
If success <> True Then
Log("Could not set EncryptedKeyMaterial.")
Return
End If
Dim validTo As ChilkatDateTime
validTo.Initialize
success = validTo.SetFromCurrentSystemTime
If success <> True Then
Log("Could not set expiration time.")
Return
End If
success = validTo.AddDays(30)
If success <> True Then
Log("Could not compute expiration.")
Return
End If
success = body.UpdateNumber("ValidTo", validTo.GetAsUnixTimeStr(False))
If success <> True Then
Log("Could not set material expiration.")
Return
End If
success = body.UpdateString("ExpirationModel", "KEY_MATERIAL_EXPIRES")
If success <> True Then
Log("Could not set ExpirationModel.")
Return
End If
success = rest.ClearAllQueryParams
If success <> True Then
Log("Could not clear previous query parameters.")
Return
End If
' 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 Then
success = rest.AddQueryParam("X-Amz-Security-Token", credentials.StringOf("session_token"))
If success <> True Then
Log("Could not set session token.")
Return
End If
End If
success = rest.AddHeader("X-Amz-Target", "TrentService.ImportKeyMaterial")
If success <> True Then
Log("Could not set operation.")
Return
End If
success = rest.AddHeader("Content-Type", "application/x-amz-json-1.1")
If success <> True Then
Log("Could not set content type.")
Return
End If
responseJson = rest.FullRequestString("POST", "/", body.Emit)
If rest.LastMethodSuccess <> True Then
Log("KMS request did not complete; inspect diagnostics privately. Reconcile any write before retrying.")
Return
End If
If rest.ResponseStatusCode <> 200 Then
Log("KMS HTTP status: " & rest.ResponseStatusCode)
success = result.Load(responseJson)
If success = True Then
If result.JsonTypeOf("__type") = 1 Then
Log("AWS error code: " & result.StringOf("__type"))
End If
End If
Log("AWS request ID: " & rest.ResponseHdrByName("x-amzn-RequestId"))
' Do not print full bodies, headers, credentials, key material, or tokens.
Return
End If
' HTTP 200 indicates acceptance; response content can be empty.
Log("Key material import accepted for: " & keyId)
Log("Use DescribeKey to confirm Enabled before signing; KMS is eventually consistent.")
' This does not securely erase copies of sensitive strings from managed memory.
Log("Example completed.")