AWS KMS: Import a PFX Key into an Existing External Signing Key
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.
Loads the certificate's private key from qa_data/pfx/myCertAndKey.pfx using string field pfx_password from the private configuration. Supports RSA 2048/3072/4096 and NIST P-256/P-384/P-521 in this sample. Keep a protected backup of the original material: KMS cannot export it. RSA material must satisfy AWS's current key-material requirements. Tags are visible metadata; do not put passwords or sensitive certificate identity data in them.
First create a compatible Origin=EXTERNAL, KeyUsage=SIGN_VERIFY KMS key with the correct KeySpec and provide its ID or ARN in key_id. This example requires PendingImport, checks metadata, pins the resolved ARN, obtains a fresh wrapping key/token pair, and imports PKCS#8 using RSA_AES_KEY_WRAP_SHA_256 and RSA_4096. It creates no new KMS key and makes no automatic retries. Required actions: kms:DescribeKey, kms:GetParametersForImport, and kms:ImportKeyMaterial.
Uses RFC 5649 AES key wrap with padding and RSA-OAEP with SHA-256 for both OAEP and MGF1. Hybrid RSA/AES wrapping is not supported in China Regions. The token and wrapping key must come from the same response for the same key and be used before ParametersValidTo (normally 24 hours). The sample chooses KEY_MATERIAL_DOES_NOT_EXPIRE explicitly; applications needing expiration must use KEY_MATERIAL_EXPIRES and a valid future ValidTo. Acceptance is not an immediate Enabled-state guarantee. Reimports and imported symmetric-key rotation require separate handling; this sample is for an initial asymmetric import.
AWS ImportKeyMaterial reference
Chilkat Visual Basic 6.0 Downloads
Dim success As Long
success = 0
Dim stringCompare As New ChilkatStringBuilder
' Assumes Chilkat is unlocked. See Global Unlock Sample.
' Keep this credentials file outside public web content and source control.
Dim credentials As New ChilkatJsonObject
credentials.Strict = 1
success = credentials.LoadFile("qa_data/aws/kms.json")
If (success <> 1) Then
Debug.Print "Could not load private KMS configuration."
Exit Sub
End If
success = stringCompare.SetString(credentials.StringOf("access_key"))
Dim stringMatch1 As Long
stringMatch1 = stringCompare.ContentsEqual("",1)
If ((credentials.JsonTypeOf("access_key") <> 1) Or (stringMatch1 = 1)) Then
Debug.Print "Missing or invalid access_key."
Exit Sub
End If
success = stringCompare.SetString(credentials.StringOf("secret_key"))
Dim stringMatch2 As Long
stringMatch2 = stringCompare.ContentsEqual("",1)
If ((credentials.JsonTypeOf("secret_key") <> 1) Or (stringMatch2 = 1)) Then
Debug.Print "Missing or invalid secret_key."
Exit Sub
End If
Dim region As String
region = "us-west-2"
Dim endpoint As New ChilkatStringBuilder
success = endpoint.Append("kms.")
success = endpoint.Append(region)
success = endpoint.Append(".amazonaws.com")
Dim aws As New ChilkatAuthAws
aws.AccessKey = credentials.StringOf("access_key")
aws.SecretKey = credentials.StringOf("secret_key")
aws.Region = region
aws.ServiceName = "kms"
aws.SignatureVersion = 4
Dim rest As New ChilkatRest
rest.ConnectTimeoutMs = 20000
rest.IdleTimeoutMs = 60000
rest.VerboseLogging = 0
success = rest.SetAuthAws(aws)
If (success <> 1) Then
Debug.Print "Could not configure AWS signing."
Exit Sub
End If
If (credentials.HasMember("session_token") = 1) Then
success = stringCompare.SetString(credentials.StringOf("session_token"))
Dim stringMatch3 As Long
stringMatch3 = stringCompare.ContentsEqual("",1)
If ((credentials.JsonTypeOf("session_token") <> 1) Or (stringMatch3 = 1)) Then
Debug.Print "Missing or invalid session_token."
Exit Sub
End If
End If
Dim connection As New ChilkatSocket
connection.RequireSslCertVerify = 1
connection.MaxReadIdleMs = 60000
connection.MaxSendIdleMs = 60000
success = connection.Connect(endpoint.GetAsString(),443,1,20000)
If (success <> 1) Then
Debug.Print "TLS connection failed; inspect diagnostics privately."
Exit Sub
End If
success = rest.UseConnection(connection,1)
If (success <> 1) Then
Debug.Print "Could not attach TLS connection."
Exit Sub
End If
' Keep connection alive while Rest uses it.
Dim body As New ChilkatJsonObject
Dim result As New ChilkatJsonObject
result.Strict = 1
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
Debug.Print "Missing or invalid pfx_password."
Exit Sub
End If
Dim cert As New ChilkatCert
success = cert.LoadPfxFile("qa_data/pfx/myCertAndKey.pfx",credentials.StringOf("pfx_password"))
If (success <> 1) Then
Debug.Print "Could not load PFX; inspect diagnostics privately."
Exit Sub
End If
Dim privKey As New PrivateKey
success = cert.GetPrivateKey(privKey)
If (success <> 1) Then
Debug.Print "PFX does not contain a usable private key."
Exit Sub
End If
' Only inspect the PUBLIC JWK to identify a supported key type and curve.
Dim sourcePublic As New PublicKey
success = privKey.ToPublicKey(sourcePublic)
If (success <> 1) Then
Debug.Print "Could not get the public key."
Exit Sub
End If
Dim publicJwk As String
publicJwk = sourcePublic.GetJwk()
If (sourcePublic.LastMethodSuccess <> 1) Then
Debug.Print "Could not inspect public key type."
Exit Sub
End If
Dim keyInfo As New ChilkatJsonObject
keyInfo.Strict = 1
success = keyInfo.Load(publicJwk)
If (success <> 1) Then
Debug.Print "Could not parse public key description."
Exit Sub
End If
Dim keySpec As String
keySpec = ""
success = stringCompare.SetString(keyInfo.StringOf("kty"))
Dim stringMatch4 As Long
stringMatch4 = stringCompare.ContentsEqual("RSA",1)
If (stringMatch4 = 1) 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
success = stringCompare.SetString(keyInfo.StringOf("kty"))
Dim stringMatch5 As Long
stringMatch5 = stringCompare.ContentsEqual("EC",1)
If (stringMatch5 = 1) Then
success = stringCompare.SetString(keyInfo.StringOf("crv"))
Dim stringMatch6 As Long
stringMatch6 = stringCompare.ContentsEqual("P-256",1)
If (stringMatch6 = 1) Then
keySpec = "ECC_NIST_P256"
End If
success = stringCompare.SetString(keyInfo.StringOf("crv"))
Dim stringMatch7 As Long
stringMatch7 = stringCompare.ContentsEqual("P-384",1)
If (stringMatch7 = 1) Then
keySpec = "ECC_NIST_P384"
End If
success = stringCompare.SetString(keyInfo.StringOf("crv"))
Dim stringMatch8 As Long
stringMatch8 = stringCompare.ContentsEqual("P-521",1)
If (stringMatch8 = 1) Then
keySpec = "ECC_NIST_P521"
End If
End If
success = stringCompare.SetString(keySpec)
Dim stringMatch9 As Long
stringMatch9 = stringCompare.ContentsEqual("",1)
If (stringMatch9 = 1) Then
Debug.Print "Use RSA 2048/3072/4096 or a NIST P-256/P-384/P-521 EC private key."
Exit Sub
End If
success = stringCompare.SetString(credentials.StringOf("key_id"))
Dim stringMatch10 As Long
stringMatch10 = stringCompare.ContentsEqual("",1)
If ((credentials.JsonTypeOf("key_id") <> 1) Or (stringMatch10 = 1)) Then
Debug.Print "Missing or invalid key_id."
Exit Sub
End If
Dim keyId As String
keyId = credentials.StringOf("key_id")
success = body.UpdateString("KeyId",keyId)
If (success <> 1) Then
Debug.Print "Could not set KeyId."
Exit Sub
End If
success = rest.ClearAllQueryParams()
If (success <> 1) Then
Debug.Print "Could not clear previous query parameters."
Exit Sub
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") = 1) Then
success = rest.AddQueryParam("X-Amz-Security-Token",credentials.StringOf("session_token"))
If (success <> 1) Then
Debug.Print "Could not set session token."
Exit Sub
End If
End If
success = rest.AddHeader("X-Amz-Target","TrentService.DescribeKey")
If (success <> 1) Then
Debug.Print "Could not set operation."
Exit Sub
End If
success = rest.AddHeader("Content-Type","application/x-amz-json-1.1")
If (success <> 1) Then
Debug.Print "Could not set content type."
Exit Sub
End If
responseJson = rest.FullRequestString("POST","/",body.Emit())
If (rest.LastMethodSuccess <> 1) Then
Debug.Print "KMS request did not complete; inspect diagnostics privately. Reconcile any write before retrying."
Exit Sub
End If
If (rest.ResponseStatusCode <> 200) Then
Debug.Print "KMS HTTP status: " & rest.ResponseStatusCode
success = result.Load(responseJson)
If (success = 1) Then
If (result.JsonTypeOf("__type") = 1) Then
Debug.Print "AWS error code: " & result.StringOf("__type")
End If
End If
Debug.Print "AWS request ID: " & rest.ResponseHdrByName("x-amzn-RequestId")
' Do not print full bodies, headers, credentials, key material, or tokens.
Exit Sub
End If
success = result.Load(responseJson)
If (success <> 1) Then
Debug.Print "Expected a well-formed JSON response."
Exit Sub
End If
success = stringCompare.SetString(result.StringOf("KeyMetadata.KeyId"))
Dim stringMatch11 As Long
stringMatch11 = stringCompare.ContentsEqual("",1)
If ((result.JsonTypeOf("KeyMetadata.KeyId") <> 1) Or (stringMatch11 = 1)) Then
Debug.Print "Missing or invalid KeyMetadata.KeyId."
Exit Sub
End If
success = stringCompare.SetString(result.StringOf("KeyMetadata.Arn"))
Dim stringMatch12 As Long
stringMatch12 = stringCompare.ContentsEqual("",1)
If ((result.JsonTypeOf("KeyMetadata.Arn") <> 1) Or (stringMatch12 = 1)) Then
Debug.Print "Missing or invalid KeyMetadata.Arn."
Exit Sub
End If
success = stringCompare.SetString(result.StringOf("KeyMetadata.Origin"))
Dim stringMatch13 As Long
stringMatch13 = stringCompare.ContentsEqual("EXTERNAL",1)
If (stringMatch13 <> 1) Then
Debug.Print "Destination must have EXTERNAL origin."
Exit Sub
End If
success = stringCompare.SetString(result.StringOf("KeyMetadata.KeyState"))
Dim stringMatch14 As Long
stringMatch14 = stringCompare.ContentsEqual("PendingImport",1)
If (stringMatch14 <> 1) Then
Debug.Print "This initial-import sample requires PendingImport; it does not replace existing material."
Exit Sub
End If
success = stringCompare.SetString(result.StringOf("KeyMetadata.KeyUsage"))
Dim stringMatch15 As Long
stringMatch15 = stringCompare.ContentsEqual("SIGN_VERIFY",1)
If (stringMatch15 <> 1) Then
Debug.Print "Destination must have SIGN_VERIFY usage."
Exit Sub
End If
success = stringCompare.SetString(result.StringOf("KeyMetadata.KeySpec"))
Dim stringMatch16 As Long
stringMatch16 = stringCompare.ContentsEqual(keySpec,1)
If (stringMatch16 <> 1) Then
Debug.Print "PFX private key does not match the destination KeySpec."
Exit Sub
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 <> 1) Then
Debug.Print "Could not set KeyId."
Exit Sub
End If
success = body.UpdateString("WrappingAlgorithm","RSA_AES_KEY_WRAP_SHA_256")
If (success <> 1) Then
Debug.Print "Could not set WrappingAlgorithm."
Exit Sub
End If
success = body.UpdateString("WrappingKeySpec","RSA_4096")
If (success <> 1) Then
Debug.Print "Could not set WrappingKeySpec."
Exit Sub
End If
success = rest.ClearAllQueryParams()
If (success <> 1) Then
Debug.Print "Could not clear previous query parameters."
Exit Sub
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") = 1) Then
success = rest.AddQueryParam("X-Amz-Security-Token",credentials.StringOf("session_token"))
If (success <> 1) Then
Debug.Print "Could not set session token."
Exit Sub
End If
End If
success = rest.AddHeader("X-Amz-Target","TrentService.GetParametersForImport")
If (success <> 1) Then
Debug.Print "Could not set operation."
Exit Sub
End If
success = rest.AddHeader("Content-Type","application/x-amz-json-1.1")
If (success <> 1) Then
Debug.Print "Could not set content type."
Exit Sub
End If
responseJson = rest.FullRequestString("POST","/",body.Emit())
If (rest.LastMethodSuccess <> 1) Then
Debug.Print "KMS request did not complete; inspect diagnostics privately. Reconcile any write before retrying."
Exit Sub
End If
If (rest.ResponseStatusCode <> 200) Then
Debug.Print "KMS HTTP status: " & rest.ResponseStatusCode
success = result.Load(responseJson)
If (success = 1) Then
If (result.JsonTypeOf("__type") = 1) Then
Debug.Print "AWS error code: " & result.StringOf("__type")
End If
End If
Debug.Print "AWS request ID: " & rest.ResponseHdrByName("x-amzn-RequestId")
' Do not print full bodies, headers, credentials, key material, or tokens.
Exit Sub
End If
success = result.Load(responseJson)
If (success <> 1) Then
Debug.Print "Expected a well-formed JSON response."
Exit Sub
End If
success = stringCompare.SetString(result.StringOf("KeyId"))
Dim stringMatch17 As Long
stringMatch17 = stringCompare.ContentsEqual("",1)
If ((result.JsonTypeOf("KeyId") <> 1) Or (stringMatch17 = 1)) Then
Debug.Print "Missing or invalid KeyId."
Exit Sub
End If
success = stringCompare.SetString(result.StringOf("KeyId"))
Dim stringMatch18 As Long
stringMatch18 = stringCompare.ContentsEqual(keyId,1)
If (stringMatch18 <> 1) Then
Debug.Print "Import parameters belong to another key."
Exit Sub
End If
success = stringCompare.SetString(result.StringOf("ImportToken"))
Dim stringMatch19 As Long
stringMatch19 = stringCompare.ContentsEqual("",1)
If ((result.JsonTypeOf("ImportToken") <> 1) Or (stringMatch19 = 1)) Then
Debug.Print "Missing or invalid ImportToken."
Exit Sub
End If
success = stringCompare.SetString(result.StringOf("PublicKey"))
Dim stringMatch20 As Long
stringMatch20 = stringCompare.ContentsEqual("",1)
If ((result.JsonTypeOf("PublicKey") <> 1) Or (stringMatch20 = 1)) Then
Debug.Print "Missing or invalid PublicKey."
Exit Sub
End If
If (result.JsonTypeOf("ParametersValidTo") <> 2) Then
Debug.Print "Missing import-parameter expiration."
Exit Sub
End If
Dim now As New CkDateTime
Dim expires As New CkDateTime
success = now.SetFromCurrentSystemTime()
If (success <> 1) Then
Debug.Print "Could not read current time."
Exit Sub
End If
success = result.DateOf("ParametersValidTo",expires)
If (success <> 1) Then
Debug.Print "Invalid import-parameter expiration."
Exit Sub
End If
If (expires.DiffSeconds(now) <= 0) Then
Debug.Print "Import parameters have expired; obtain a fresh token and wrapping key together."
Exit Sub
End If
Dim importToken As String
importToken = result.StringOf("ImportToken")
Dim wrappingKey As New PublicKey
success = wrappingKey.LoadBase64(result.StringOf("PublicKey"))
If (success <> 1) Then
Debug.Print "Could not load the RSA wrapping key."
Exit Sub
End If
If (wrappingKey.KeySize <> 4096) Then
Debug.Print "Expected the requested 4096-bit RSA wrapping key."
Exit Sub
End If
' Export PKCS#8 DER in memory only; never print or write unencrypted key material.
Dim pkcs8Base64 As String
pkcs8Base64 = privKey.GetPkcs8ENC("base64")
If (privKey.LastMethodSuccess <> 1) Then
Debug.Print "Could not encode the private key as PKCS#8."
Exit Sub
End If
Dim prng As New ChilkatPrng
' A fresh 32-byte (256-bit) AES key, not a 32-bit key.
Dim aesKeyBase64 As String
aesKeyBase64 = prng.GenRandom(32,"base64")
If (prng.LastMethodSuccess <> 1) Then
Debug.Print "Could not generate wrapping key."
Exit Sub
End If
Dim crypt As New ChilkatCrypt2
Dim wrappedPrivateKey As String
wrappedPrivateKey = crypt.AesKeyWrapWithPadding(aesKeyBase64,pkcs8Base64,"base64")
If (crypt.LastMethodSuccess <> 1) Then
Debug.Print "AES key wrapping failed."
Exit Sub
End If
Dim wrappedAesKey As New ChilkatBinData
success = wrappedAesKey.AppendEncoded(aesKeyBase64,"base64")
If (success <> 1) Then
Debug.Print "Could not decode AES key."
Exit Sub
End If
Dim rsa As New ChilkatRsa
success = rsa.UsePublicKey(wrappingKey)
If (success <> 1) Then
Debug.Print "Could not select the RSA wrapping key."
Exit Sub
End If
rsa.PkcsPadding = 0
rsa.OaepHash = "sha256"
rsa.OaepMgfHash = "sha256"
success = rsa.EncryptBd(wrappedAesKey,0)
If (success <> 1) Then
Debug.Print "RSA-OAEP AES-key wrapping failed."
Exit Sub
End If
' Wire order is RSA-wrapped AES key FIRST, followed by AES-wrapped PKCS#8.
Dim encryptedMaterial As New ChilkatBinData
success = encryptedMaterial.AppendBd(wrappedAesKey)
If (success <> 1) Then
Debug.Print "Could not assemble encrypted material."
Exit Sub
End If
success = encryptedMaterial.AppendEncoded(wrappedPrivateKey,"base64")
If (success <> 1) Then
Debug.Print "Could not append wrapped private key."
Exit Sub
End If
body.Clear
success = body.UpdateString("KeyId",keyId)
If (success <> 1) Then
Debug.Print "Could not set KeyId."
Exit Sub
End If
success = body.UpdateString("ImportToken",importToken)
If (success <> 1) Then
Debug.Print "Could not set ImportToken."
Exit Sub
End If
success = body.UpdateString("EncryptedKeyMaterial",encryptedMaterial.GetEncoded("base64"))
If (success <> 1) Then
Debug.Print "Could not set EncryptedKeyMaterial."
Exit Sub
End If
success = body.UpdateString("ExpirationModel","KEY_MATERIAL_DOES_NOT_EXPIRE")
If (success <> 1) Then
Debug.Print "Could not set ExpirationModel."
Exit Sub
End If
success = rest.ClearAllQueryParams()
If (success <> 1) Then
Debug.Print "Could not clear previous query parameters."
Exit Sub
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") = 1) Then
success = rest.AddQueryParam("X-Amz-Security-Token",credentials.StringOf("session_token"))
If (success <> 1) Then
Debug.Print "Could not set session token."
Exit Sub
End If
End If
success = rest.AddHeader("X-Amz-Target","TrentService.ImportKeyMaterial")
If (success <> 1) Then
Debug.Print "Could not set operation."
Exit Sub
End If
success = rest.AddHeader("Content-Type","application/x-amz-json-1.1")
If (success <> 1) Then
Debug.Print "Could not set content type."
Exit Sub
End If
responseJson = rest.FullRequestString("POST","/",body.Emit())
If (rest.LastMethodSuccess <> 1) Then
Debug.Print "KMS request did not complete; inspect diagnostics privately. Reconcile any write before retrying."
Exit Sub
End If
If (rest.ResponseStatusCode <> 200) Then
Debug.Print "KMS HTTP status: " & rest.ResponseStatusCode
success = result.Load(responseJson)
If (success = 1) Then
If (result.JsonTypeOf("__type") = 1) Then
Debug.Print "AWS error code: " & result.StringOf("__type")
End If
End If
Debug.Print "AWS request ID: " & rest.ResponseHdrByName("x-amzn-RequestId")
' Do not print full bodies, headers, credentials, key material, or tokens.
Exit Sub
End If
' HTTP 200 indicates acceptance; response content can be empty.
Debug.Print "Key material import accepted for: " & keyId
Debug.Print "Use DescribeKey to confirm Enabled before signing; KMS is eventually consistent."
' This does not securely erase copies of sensitive strings from managed memory.