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

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 VBScript Downloads

VBScript
Dim fso, outFile
Set fso = CreateObject("Scripting.FileSystemObject")
'Create a Unicode (utf-16) output text file.
Set outFile = fso.CreateTextFile("output.txt", True, True)

success = 0

set stringCompare = CreateObject("Chilkat.StringBuilder")
'  Assumes Chilkat is unlocked. See Global Unlock Sample.
'  Keep this credentials file outside public web content and source control.
set credentials = CreateObject("Chilkat.JsonObject")
credentials.Strict = 1
success = credentials.LoadFile("qa_data/aws/kms.json")
If (success <> 1) Then
    outFile.WriteLine("Could not load private KMS configuration.")
    WScript.Quit
End If

success = stringCompare.SetString(credentials.StringOf("access_key"))
stringMatch1 = stringCompare.ContentsEqual("",1)
If ((credentials.JsonTypeOf("access_key") <> 1) Or (stringMatch1 = 1)) Then
    outFile.WriteLine("Missing or invalid access_key.")
    WScript.Quit
End If

success = stringCompare.SetString(credentials.StringOf("secret_key"))
stringMatch2 = stringCompare.ContentsEqual("",1)
If ((credentials.JsonTypeOf("secret_key") <> 1) Or (stringMatch2 = 1)) Then
    outFile.WriteLine("Missing or invalid secret_key.")
    WScript.Quit
End If

region = "us-west-2"
set endpoint = CreateObject("Chilkat.StringBuilder")
success = endpoint.Append("kms.")
success = endpoint.Append(region)
success = endpoint.Append(".amazonaws.com")
set aws = CreateObject("Chilkat.AuthAws")
aws.AccessKey = credentials.StringOf("access_key")
aws.SecretKey = credentials.StringOf("secret_key")
aws.Region = region
aws.ServiceName = "kms"
aws.SignatureVersion = 4
set rest = CreateObject("Chilkat.Rest")
rest.ConnectTimeoutMs = 20000
rest.IdleTimeoutMs = 60000
rest.VerboseLogging = 0
success = rest.SetAuthAws(aws)
If (success <> 1) Then
    outFile.WriteLine("Could not configure AWS signing.")
    WScript.Quit
End If

If (credentials.HasMember("session_token") = 1) Then
    success = stringCompare.SetString(credentials.StringOf("session_token"))
    stringMatch3 = stringCompare.ContentsEqual("",1)
    If ((credentials.JsonTypeOf("session_token") <> 1) Or (stringMatch3 = 1)) Then
        outFile.WriteLine("Missing or invalid session_token.")
        WScript.Quit
    End If

End If

set connection = CreateObject("Chilkat.Socket")
connection.RequireSslCertVerify = 1
connection.MaxReadIdleMs = 60000
connection.MaxSendIdleMs = 60000
success = connection.Connect(endpoint.GetAsString(),443,1,20000)
If (success <> 1) Then
    outFile.WriteLine("TLS connection failed; inspect diagnostics privately.")
    WScript.Quit
End If

success = rest.UseConnection(connection,1)
If (success <> 1) Then
    outFile.WriteLine("Could not attach TLS connection.")
    WScript.Quit
End If

'  Keep connection alive while Rest uses it.
set body = CreateObject("Chilkat.JsonObject")
set result = CreateObject("Chilkat.JsonObject")
result.Strict = 1

'  pfx_password is a string; an empty string is allowed for an unprotected PFX.
If (credentials.JsonTypeOf("pfx_password") <> 1) Then
    outFile.WriteLine("Missing or invalid pfx_password.")
    WScript.Quit
End If

set cert = CreateObject("Chilkat.Cert")
success = cert.LoadPfxFile("qa_data/pfx/myCertAndKey.pfx",credentials.StringOf("pfx_password"))
If (success <> 1) Then
    outFile.WriteLine("Could not load PFX; inspect diagnostics privately.")
    WScript.Quit
End If

set privKey = CreateObject("Chilkat.PrivateKey")
success = cert.GetPrivateKey(privKey)
If (success <> 1) Then
    outFile.WriteLine("PFX does not contain a usable private key.")
    WScript.Quit
End If

'  Only inspect the PUBLIC JWK to identify a supported key type and curve.
set sourcePublic = CreateObject("Chilkat.PublicKey")
success = privKey.ToPublicKey(sourcePublic)
If (success <> 1) Then
    outFile.WriteLine("Could not get the public key.")
    WScript.Quit
End If

publicJwk = sourcePublic.GetJwk()
If (sourcePublic.LastMethodSuccess <> 1) Then
    outFile.WriteLine("Could not inspect public key type.")
    WScript.Quit
End If

set keyInfo = CreateObject("Chilkat.JsonObject")
keyInfo.Strict = 1
success = keyInfo.Load(publicJwk)
If (success <> 1) Then
    outFile.WriteLine("Could not parse public key description.")
    WScript.Quit
End If

keySpec = ""
success = stringCompare.SetString(keyInfo.StringOf("kty"))
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"))
stringMatch5 = stringCompare.ContentsEqual("EC",1)
If (stringMatch5 = 1) Then
    success = stringCompare.SetString(keyInfo.StringOf("crv"))
    stringMatch6 = stringCompare.ContentsEqual("P-256",1)
    If (stringMatch6 = 1) Then
        keySpec = "ECC_NIST_P256"
    End If

    success = stringCompare.SetString(keyInfo.StringOf("crv"))
    stringMatch7 = stringCompare.ContentsEqual("P-384",1)
    If (stringMatch7 = 1) Then
        keySpec = "ECC_NIST_P384"
    End If

    success = stringCompare.SetString(keyInfo.StringOf("crv"))
    stringMatch8 = stringCompare.ContentsEqual("P-521",1)
    If (stringMatch8 = 1) Then
        keySpec = "ECC_NIST_P521"
    End If

End If

success = stringCompare.SetString(keySpec)
stringMatch9 = stringCompare.ContentsEqual("",1)
If (stringMatch9 = 1) Then
    outFile.WriteLine("Use RSA 2048/3072/4096 or a NIST P-256/P-384/P-521 EC private key.")
    WScript.Quit
End If

success = stringCompare.SetString(credentials.StringOf("key_id"))
stringMatch10 = stringCompare.ContentsEqual("",1)
If ((credentials.JsonTypeOf("key_id") <> 1) Or (stringMatch10 = 1)) Then
    outFile.WriteLine("Missing or invalid key_id.")
    WScript.Quit
End If

keyId = credentials.StringOf("key_id")
success = body.UpdateString("KeyId",keyId)
If (success <> 1) Then
    outFile.WriteLine("Could not set KeyId.")
    WScript.Quit
End If

success = rest.ClearAllQueryParams()
If (success <> 1) Then
    outFile.WriteLine("Could not clear previous query parameters.")
    WScript.Quit
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
        outFile.WriteLine("Could not set session token.")
        WScript.Quit
    End If

End If

success = rest.AddHeader("X-Amz-Target","TrentService.DescribeKey")
If (success <> 1) Then
    outFile.WriteLine("Could not set operation.")
    WScript.Quit
End If

success = rest.AddHeader("Content-Type","application/x-amz-json-1.1")
If (success <> 1) Then
    outFile.WriteLine("Could not set content type.")
    WScript.Quit
End If

responseJson = rest.FullRequestString("POST","/",body.Emit())
If (rest.LastMethodSuccess <> 1) Then
    outFile.WriteLine("KMS request did not complete; inspect diagnostics privately. Reconcile any write before retrying.")
    WScript.Quit
End If

If (rest.ResponseStatusCode <> 200) Then
    outFile.WriteLine("KMS HTTP status: " & rest.ResponseStatusCode)
    success = result.Load(responseJson)
    If (success = 1) Then
        If (result.JsonTypeOf("__type") = 1) Then
            outFile.WriteLine("AWS error code: " & result.StringOf("__type"))
        End If

    End If

    outFile.WriteLine("AWS request ID: " & rest.ResponseHdrByName("x-amzn-RequestId"))
    '  Do not print full bodies, headers, credentials, key material, or tokens.
    WScript.Quit
End If

success = result.Load(responseJson)
If (success <> 1) Then
    outFile.WriteLine("Expected a well-formed JSON response.")
    WScript.Quit
End If

success = stringCompare.SetString(result.StringOf("KeyMetadata.KeyId"))
stringMatch11 = stringCompare.ContentsEqual("",1)
If ((result.JsonTypeOf("KeyMetadata.KeyId") <> 1) Or (stringMatch11 = 1)) Then
    outFile.WriteLine("Missing or invalid KeyMetadata.KeyId.")
    WScript.Quit
End If

success = stringCompare.SetString(result.StringOf("KeyMetadata.Arn"))
stringMatch12 = stringCompare.ContentsEqual("",1)
If ((result.JsonTypeOf("KeyMetadata.Arn") <> 1) Or (stringMatch12 = 1)) Then
    outFile.WriteLine("Missing or invalid KeyMetadata.Arn.")
    WScript.Quit
End If

success = stringCompare.SetString(result.StringOf("KeyMetadata.Origin"))
stringMatch13 = stringCompare.ContentsEqual("EXTERNAL",1)
If (stringMatch13 <> 1) Then
    outFile.WriteLine("Destination must have EXTERNAL origin.")
    WScript.Quit
End If

success = stringCompare.SetString(result.StringOf("KeyMetadata.KeyState"))
stringMatch14 = stringCompare.ContentsEqual("PendingImport",1)
If (stringMatch14 <> 1) Then
    outFile.WriteLine("This initial-import sample requires PendingImport; it does not replace existing material.")
    WScript.Quit
End If

success = stringCompare.SetString(result.StringOf("KeyMetadata.KeyUsage"))
stringMatch15 = stringCompare.ContentsEqual("SIGN_VERIFY",1)
If (stringMatch15 <> 1) Then
    outFile.WriteLine("Destination must have SIGN_VERIFY usage.")
    WScript.Quit
End If

success = stringCompare.SetString(result.StringOf("KeyMetadata.KeySpec"))
stringMatch16 = stringCompare.ContentsEqual(keySpec,1)
If (stringMatch16 <> 1) Then
    outFile.WriteLine("PFX private key does not match the destination KeySpec.")
    WScript.Quit
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
    outFile.WriteLine("Could not set KeyId.")
    WScript.Quit
End If

success = body.UpdateString("WrappingAlgorithm","RSA_AES_KEY_WRAP_SHA_256")
If (success <> 1) Then
    outFile.WriteLine("Could not set WrappingAlgorithm.")
    WScript.Quit
End If

success = body.UpdateString("WrappingKeySpec","RSA_4096")
If (success <> 1) Then
    outFile.WriteLine("Could not set WrappingKeySpec.")
    WScript.Quit
End If

success = rest.ClearAllQueryParams()
If (success <> 1) Then
    outFile.WriteLine("Could not clear previous query parameters.")
    WScript.Quit
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
        outFile.WriteLine("Could not set session token.")
        WScript.Quit
    End If

End If

success = rest.AddHeader("X-Amz-Target","TrentService.GetParametersForImport")
If (success <> 1) Then
    outFile.WriteLine("Could not set operation.")
    WScript.Quit
End If

success = rest.AddHeader("Content-Type","application/x-amz-json-1.1")
If (success <> 1) Then
    outFile.WriteLine("Could not set content type.")
    WScript.Quit
End If

responseJson = rest.FullRequestString("POST","/",body.Emit())
If (rest.LastMethodSuccess <> 1) Then
    outFile.WriteLine("KMS request did not complete; inspect diagnostics privately. Reconcile any write before retrying.")
    WScript.Quit
End If

If (rest.ResponseStatusCode <> 200) Then
    outFile.WriteLine("KMS HTTP status: " & rest.ResponseStatusCode)
    success = result.Load(responseJson)
    If (success = 1) Then
        If (result.JsonTypeOf("__type") = 1) Then
            outFile.WriteLine("AWS error code: " & result.StringOf("__type"))
        End If

    End If

    outFile.WriteLine("AWS request ID: " & rest.ResponseHdrByName("x-amzn-RequestId"))
    '  Do not print full bodies, headers, credentials, key material, or tokens.
    WScript.Quit
End If

success = result.Load(responseJson)
If (success <> 1) Then
    outFile.WriteLine("Expected a well-formed JSON response.")
    WScript.Quit
End If

success = stringCompare.SetString(result.StringOf("KeyId"))
stringMatch17 = stringCompare.ContentsEqual("",1)
If ((result.JsonTypeOf("KeyId") <> 1) Or (stringMatch17 = 1)) Then
    outFile.WriteLine("Missing or invalid KeyId.")
    WScript.Quit
End If

success = stringCompare.SetString(result.StringOf("KeyId"))
stringMatch18 = stringCompare.ContentsEqual(keyId,1)
If (stringMatch18 <> 1) Then
    outFile.WriteLine("Import parameters belong to another key.")
    WScript.Quit
End If

success = stringCompare.SetString(result.StringOf("ImportToken"))
stringMatch19 = stringCompare.ContentsEqual("",1)
If ((result.JsonTypeOf("ImportToken") <> 1) Or (stringMatch19 = 1)) Then
    outFile.WriteLine("Missing or invalid ImportToken.")
    WScript.Quit
End If

success = stringCompare.SetString(result.StringOf("PublicKey"))
stringMatch20 = stringCompare.ContentsEqual("",1)
If ((result.JsonTypeOf("PublicKey") <> 1) Or (stringMatch20 = 1)) Then
    outFile.WriteLine("Missing or invalid PublicKey.")
    WScript.Quit
End If

If (result.JsonTypeOf("ParametersValidTo") <> 2) Then
    outFile.WriteLine("Missing import-parameter expiration.")
    WScript.Quit
End If

set now = CreateObject("Chilkat.CkDateTime")
set expires = CreateObject("Chilkat.CkDateTime")
success = now.SetFromCurrentSystemTime()
If (success <> 1) Then
    outFile.WriteLine("Could not read current time.")
    WScript.Quit
End If

success = result.DateOf("ParametersValidTo",expires)
If (success <> 1) Then
    outFile.WriteLine("Invalid import-parameter expiration.")
    WScript.Quit
End If

If (expires.DiffSeconds(now) <= 0) Then
    outFile.WriteLine("Import parameters have expired; obtain a fresh token and wrapping key together.")
    WScript.Quit
End If

importToken = result.StringOf("ImportToken")
set wrappingKey = CreateObject("Chilkat.PublicKey")
success = wrappingKey.LoadBase64(result.StringOf("PublicKey"))
If (success <> 1) Then
    outFile.WriteLine("Could not load the RSA wrapping key.")
    WScript.Quit
End If

If (wrappingKey.KeySize <> 4096) Then
    outFile.WriteLine("Expected the requested 4096-bit RSA wrapping key.")
    WScript.Quit
End If

'  Export PKCS#8 DER in memory only; never print or write unencrypted key material.
pkcs8Base64 = privKey.GetPkcs8ENC("base64")
If (privKey.LastMethodSuccess <> 1) Then
    outFile.WriteLine("Could not encode the private key as PKCS#8.")
    WScript.Quit
End If

set prng = CreateObject("Chilkat.Prng")
'  A fresh 32-byte (256-bit) AES key, not a 32-bit key.
aesKeyBase64 = prng.GenRandom(32,"base64")
If (prng.LastMethodSuccess <> 1) Then
    outFile.WriteLine("Could not generate wrapping key.")
    WScript.Quit
End If

set crypt = CreateObject("Chilkat.Crypt2")
wrappedPrivateKey = crypt.AesKeyWrapWithPadding(aesKeyBase64,pkcs8Base64,"base64")
If (crypt.LastMethodSuccess <> 1) Then
    outFile.WriteLine("AES key wrapping failed.")
    WScript.Quit
End If

set wrappedAesKey = CreateObject("Chilkat.BinData")
success = wrappedAesKey.AppendEncoded(aesKeyBase64,"base64")
If (success <> 1) Then
    outFile.WriteLine("Could not decode AES key.")
    WScript.Quit
End If

set rsa = CreateObject("Chilkat.Rsa")
success = rsa.UsePublicKey(wrappingKey)
If (success <> 1) Then
    outFile.WriteLine("Could not select the RSA wrapping key.")
    WScript.Quit
End If

rsa.PkcsPadding = 0
rsa.OaepHash = "sha256"
rsa.OaepMgfHash = "sha256"
success = rsa.EncryptBd(wrappedAesKey,0)
If (success <> 1) Then
    outFile.WriteLine("RSA-OAEP AES-key wrapping failed.")
    WScript.Quit
End If

'  Wire order is RSA-wrapped AES key FIRST, followed by AES-wrapped PKCS#8.
set encryptedMaterial = CreateObject("Chilkat.BinData")
success = encryptedMaterial.AppendBd(wrappedAesKey)
If (success <> 1) Then
    outFile.WriteLine("Could not assemble encrypted material.")
    WScript.Quit
End If

success = encryptedMaterial.AppendEncoded(wrappedPrivateKey,"base64")
If (success <> 1) Then
    outFile.WriteLine("Could not append wrapped private key.")
    WScript.Quit
End If

body.Clear 
success = body.UpdateString("KeyId",keyId)
If (success <> 1) Then
    outFile.WriteLine("Could not set KeyId.")
    WScript.Quit
End If

success = body.UpdateString("ImportToken",importToken)
If (success <> 1) Then
    outFile.WriteLine("Could not set ImportToken.")
    WScript.Quit
End If

success = body.UpdateString("EncryptedKeyMaterial",encryptedMaterial.GetEncoded("base64"))
If (success <> 1) Then
    outFile.WriteLine("Could not set EncryptedKeyMaterial.")
    WScript.Quit
End If

success = body.UpdateString("ExpirationModel","KEY_MATERIAL_DOES_NOT_EXPIRE")
If (success <> 1) Then
    outFile.WriteLine("Could not set ExpirationModel.")
    WScript.Quit
End If

success = rest.ClearAllQueryParams()
If (success <> 1) Then
    outFile.WriteLine("Could not clear previous query parameters.")
    WScript.Quit
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
        outFile.WriteLine("Could not set session token.")
        WScript.Quit
    End If

End If

success = rest.AddHeader("X-Amz-Target","TrentService.ImportKeyMaterial")
If (success <> 1) Then
    outFile.WriteLine("Could not set operation.")
    WScript.Quit
End If

success = rest.AddHeader("Content-Type","application/x-amz-json-1.1")
If (success <> 1) Then
    outFile.WriteLine("Could not set content type.")
    WScript.Quit
End If

responseJson = rest.FullRequestString("POST","/",body.Emit())
If (rest.LastMethodSuccess <> 1) Then
    outFile.WriteLine("KMS request did not complete; inspect diagnostics privately. Reconcile any write before retrying.")
    WScript.Quit
End If

If (rest.ResponseStatusCode <> 200) Then
    outFile.WriteLine("KMS HTTP status: " & rest.ResponseStatusCode)
    success = result.Load(responseJson)
    If (success = 1) Then
        If (result.JsonTypeOf("__type") = 1) Then
            outFile.WriteLine("AWS error code: " & result.StringOf("__type"))
        End If

    End If

    outFile.WriteLine("AWS request ID: " & rest.ResponseHdrByName("x-amzn-RequestId"))
    '  Do not print full bodies, headers, credentials, key material, or tokens.
    WScript.Quit
End If

'  HTTP 200 indicates acceptance; response content can be empty.
outFile.WriteLine("Key material import accepted for: " & keyId)
outFile.WriteLine("Use DescribeKey to confirm Enabled before signing; KMS is eventually consistent.")
'  This does not securely erase copies of sensitive strings from managed memory.

outFile.Close