Sample code for 30+ languages & platforms
Ruby 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 Ruby Downloads

Ruby
require 'chilkat'

success = false

stringCompare = Chilkat::CkStringBuilder.new()
#  Assumes Chilkat is unlocked. See Global Unlock Sample.
#  Keep this credentials file outside public web content and source control.
credentials = Chilkat::CkJsonObject.new()
credentials.put_Strict(true)
success = credentials.LoadFile("qa_data/aws/kms.json")
if (success != true)
    print "Could not load private KMS configuration." + "\n";
    exit
end

stringCompare.SetString(credentials.stringOf("access_key"))
stringMatch1 = stringCompare.ContentsEqual("",true)
if ((credentials.JsonTypeOf("access_key") != 1) or (stringMatch1 == true))
    print "Missing or invalid access_key." + "\n";
    exit
end

stringCompare.SetString(credentials.stringOf("secret_key"))
stringMatch2 = stringCompare.ContentsEqual("",true)
if ((credentials.JsonTypeOf("secret_key") != 1) or (stringMatch2 == true))
    print "Missing or invalid secret_key." + "\n";
    exit
end

region = "us-west-2"
endpoint = Chilkat::CkStringBuilder.new()
endpoint.Append("kms.")
endpoint.Append(region)
endpoint.Append(".amazonaws.com")
aws = Chilkat::CkAuthAws.new()
aws.put_AccessKey(credentials.stringOf("access_key"))
aws.put_SecretKey(credentials.stringOf("secret_key"))
aws.put_Region(region)
aws.put_ServiceName("kms")
aws.put_SignatureVersion(4)
rest = Chilkat::CkRest.new()
rest.put_ConnectTimeoutMs(20000)
rest.put_IdleTimeoutMs(60000)
rest.put_VerboseLogging(false)
success = rest.SetAuthAws(aws)
if (success != true)
    print "Could not configure AWS signing." + "\n";
    exit
end

if (credentials.HasMember("session_token") == true)
    stringCompare.SetString(credentials.stringOf("session_token"))
    stringMatch3 = stringCompare.ContentsEqual("",true)
    if ((credentials.JsonTypeOf("session_token") != 1) or (stringMatch3 == true))
        print "Missing or invalid session_token." + "\n";
        exit
    end

end

connection = Chilkat::CkSocket.new()
connection.put_RequireSslCertVerify(true)
connection.put_MaxReadIdleMs(60000)
connection.put_MaxSendIdleMs(60000)
success = connection.Connect(endpoint.getAsString(),443,true,20000)
if (success != true)
    print "TLS connection failed; inspect diagnostics privately." + "\n";
    exit
end

success = rest.UseConnection(connection,true)
if (success != true)
    print "Could not attach TLS connection." + "\n";
    exit
end

#  Keep connection alive while Rest uses it.
body = Chilkat::CkJsonObject.new()
result = Chilkat::CkJsonObject.new()
result.put_Strict(true)

#  pfx_password is a string; an empty string is allowed for an unprotected PFX.
if (credentials.JsonTypeOf("pfx_password") != 1)
    print "Missing or invalid pfx_password." + "\n";
    exit
end

cert = Chilkat::CkCert.new()
success = cert.LoadPfxFile("qa_data/pfx/myCertAndKey.pfx",credentials.stringOf("pfx_password"))
if (success != true)
    print "Could not load PFX; inspect diagnostics privately." + "\n";
    exit
end

privKey = Chilkat::CkPrivateKey.new()
success = cert.GetPrivateKey(privKey)
if (success != true)
    print "PFX does not contain a usable private key." + "\n";
    exit
end

#  Only inspect the PUBLIC JWK to identify a supported key type and curve.
sourcePublic = Chilkat::CkPublicKey.new()
success = privKey.ToPublicKey(sourcePublic)
if (success != true)
    print "Could not get the public key." + "\n";
    exit
end

publicJwk = sourcePublic.getJwk()
if (sourcePublic.get_LastMethodSuccess() != true)
    print "Could not inspect public key type." + "\n";
    exit
end

keyInfo = Chilkat::CkJsonObject.new()
keyInfo.put_Strict(true)
success = keyInfo.Load(publicJwk)
if (success != true)
    print "Could not parse public key description." + "\n";
    exit
end

keySpec = ""
stringCompare.SetString(keyInfo.stringOf("kty"))
stringMatch4 = stringCompare.ContentsEqual("RSA",true)
if (stringMatch4 == true)
    if (privKey.get_BitLength() == 2048)
        keySpec = "RSA_2048"
    end

    if (privKey.get_BitLength() == 3072)
        keySpec = "RSA_3072"
    end

    if (privKey.get_BitLength() == 4096)
        keySpec = "RSA_4096"
    end

end

stringCompare.SetString(keyInfo.stringOf("kty"))
stringMatch5 = stringCompare.ContentsEqual("EC",true)
if (stringMatch5 == true)
    stringCompare.SetString(keyInfo.stringOf("crv"))
    stringMatch6 = stringCompare.ContentsEqual("P-256",true)
    if (stringMatch6 == true)
        keySpec = "ECC_NIST_P256"
    end

    stringCompare.SetString(keyInfo.stringOf("crv"))
    stringMatch7 = stringCompare.ContentsEqual("P-384",true)
    if (stringMatch7 == true)
        keySpec = "ECC_NIST_P384"
    end

    stringCompare.SetString(keyInfo.stringOf("crv"))
    stringMatch8 = stringCompare.ContentsEqual("P-521",true)
    if (stringMatch8 == true)
        keySpec = "ECC_NIST_P521"
    end

end

stringCompare.SetString(keySpec)
stringMatch9 = stringCompare.ContentsEqual("",true)
if (stringMatch9 == true)
    print "Use RSA 2048/3072/4096 or a NIST P-256/P-384/P-521 EC private key." + "\n";
    exit
end

stringCompare.SetString(credentials.stringOf("key_id"))
stringMatch10 = stringCompare.ContentsEqual("",true)
if ((credentials.JsonTypeOf("key_id") != 1) or (stringMatch10 == true))
    print "Missing or invalid key_id." + "\n";
    exit
end

keyId = credentials.stringOf("key_id")
success = body.UpdateString("KeyId",keyId)
if (success != true)
    print "Could not set KeyId." + "\n";
    exit
end

success = rest.ClearAllQueryParams()
if (success != true)
    print "Could not clear previous query parameters." + "\n";
    exit
end

#  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)
    success = rest.AddQueryParam("X-Amz-Security-Token",credentials.stringOf("session_token"))
    if (success != true)
        print "Could not set session token." + "\n";
        exit
    end

end

success = rest.AddHeader("X-Amz-Target","TrentService.DescribeKey")
if (success != true)
    print "Could not set operation." + "\n";
    exit
end

success = rest.AddHeader("Content-Type","application/x-amz-json-1.1")
if (success != true)
    print "Could not set content type." + "\n";
    exit
end

responseJson = rest.fullRequestString("POST","/",body.emit())
if (rest.get_LastMethodSuccess() != true)
    print "KMS request did not complete; inspect diagnostics privately. Reconcile any write before retrying." + "\n";
    exit
end

if (rest.get_ResponseStatusCode() != 200)
    print "KMS HTTP status: " + rest.get_ResponseStatusCode().to_s() + "\n";
    success = result.Load(responseJson)
    if (success == true)
        if (result.JsonTypeOf("__type") == 1)
            print "AWS error code: " + result.stringOf("__type") + "\n";
        end

    end

    print "AWS request ID: " + rest.responseHdrByName("x-amzn-RequestId") + "\n";
    #  Do not print full bodies, headers, credentials, key material, or tokens.
    exit
end

success = result.Load(responseJson)
if (success != true)
    print "Expected a well-formed JSON response." + "\n";
    exit
end

stringCompare.SetString(result.stringOf("KeyMetadata.KeyId"))
stringMatch11 = stringCompare.ContentsEqual("",true)
if ((result.JsonTypeOf("KeyMetadata.KeyId") != 1) or (stringMatch11 == true))
    print "Missing or invalid KeyMetadata.KeyId." + "\n";
    exit
end

stringCompare.SetString(result.stringOf("KeyMetadata.Arn"))
stringMatch12 = stringCompare.ContentsEqual("",true)
if ((result.JsonTypeOf("KeyMetadata.Arn") != 1) or (stringMatch12 == true))
    print "Missing or invalid KeyMetadata.Arn." + "\n";
    exit
end

stringCompare.SetString(result.stringOf("KeyMetadata.Origin"))
stringMatch13 = stringCompare.ContentsEqual("EXTERNAL",true)
if (stringMatch13 != true)
    print "Destination must have EXTERNAL origin." + "\n";
    exit
end

stringCompare.SetString(result.stringOf("KeyMetadata.KeyState"))
stringMatch14 = stringCompare.ContentsEqual("PendingImport",true)
if (stringMatch14 != true)
    print "This initial-import sample requires PendingImport; it does not replace existing material." + "\n";
    exit
end

stringCompare.SetString(result.stringOf("KeyMetadata.KeyUsage"))
stringMatch15 = stringCompare.ContentsEqual("SIGN_VERIFY",true)
if (stringMatch15 != true)
    print "Destination must have SIGN_VERIFY usage." + "\n";
    exit
end

stringCompare.SetString(result.stringOf("KeyMetadata.KeySpec"))
stringMatch16 = stringCompare.ContentsEqual(keySpec,true)
if (stringMatch16 != true)
    print "PFX private key does not match the destination KeySpec." + "\n";
    exit
end

#  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)
    print "Could not set KeyId." + "\n";
    exit
end

success = body.UpdateString("WrappingAlgorithm","RSA_AES_KEY_WRAP_SHA_256")
if (success != true)
    print "Could not set WrappingAlgorithm." + "\n";
    exit
end

success = body.UpdateString("WrappingKeySpec","RSA_4096")
if (success != true)
    print "Could not set WrappingKeySpec." + "\n";
    exit
end

success = rest.ClearAllQueryParams()
if (success != true)
    print "Could not clear previous query parameters." + "\n";
    exit
end

#  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)
    success = rest.AddQueryParam("X-Amz-Security-Token",credentials.stringOf("session_token"))
    if (success != true)
        print "Could not set session token." + "\n";
        exit
    end

end

success = rest.AddHeader("X-Amz-Target","TrentService.GetParametersForImport")
if (success != true)
    print "Could not set operation." + "\n";
    exit
end

success = rest.AddHeader("Content-Type","application/x-amz-json-1.1")
if (success != true)
    print "Could not set content type." + "\n";
    exit
end

responseJson = rest.fullRequestString("POST","/",body.emit())
if (rest.get_LastMethodSuccess() != true)
    print "KMS request did not complete; inspect diagnostics privately. Reconcile any write before retrying." + "\n";
    exit
end

if (rest.get_ResponseStatusCode() != 200)
    print "KMS HTTP status: " + rest.get_ResponseStatusCode().to_s() + "\n";
    success = result.Load(responseJson)
    if (success == true)
        if (result.JsonTypeOf("__type") == 1)
            print "AWS error code: " + result.stringOf("__type") + "\n";
        end

    end

    print "AWS request ID: " + rest.responseHdrByName("x-amzn-RequestId") + "\n";
    #  Do not print full bodies, headers, credentials, key material, or tokens.
    exit
end

success = result.Load(responseJson)
if (success != true)
    print "Expected a well-formed JSON response." + "\n";
    exit
end

stringCompare.SetString(result.stringOf("KeyId"))
stringMatch17 = stringCompare.ContentsEqual("",true)
if ((result.JsonTypeOf("KeyId") != 1) or (stringMatch17 == true))
    print "Missing or invalid KeyId." + "\n";
    exit
end

stringCompare.SetString(result.stringOf("KeyId"))
stringMatch18 = stringCompare.ContentsEqual(keyId,true)
if (stringMatch18 != true)
    print "Import parameters belong to another key." + "\n";
    exit
end

stringCompare.SetString(result.stringOf("ImportToken"))
stringMatch19 = stringCompare.ContentsEqual("",true)
if ((result.JsonTypeOf("ImportToken") != 1) or (stringMatch19 == true))
    print "Missing or invalid ImportToken." + "\n";
    exit
end

stringCompare.SetString(result.stringOf("PublicKey"))
stringMatch20 = stringCompare.ContentsEqual("",true)
if ((result.JsonTypeOf("PublicKey") != 1) or (stringMatch20 == true))
    print "Missing or invalid PublicKey." + "\n";
    exit
end

if (result.JsonTypeOf("ParametersValidTo") != 2)
    print "Missing import-parameter expiration." + "\n";
    exit
end

now = Chilkat::CkDateTime.new()
expires = Chilkat::CkDateTime.new()
success = now.SetFromCurrentSystemTime()
if (success != true)
    print "Could not read current time." + "\n";
    exit
end

success = result.DateOf("ParametersValidTo",expires)
if (success != true)
    print "Invalid import-parameter expiration." + "\n";
    exit
end

if (expires.DiffSeconds(now) <= 0)
    print "Import parameters have expired; obtain a fresh token and wrapping key together." + "\n";
    exit
end

importToken = result.stringOf("ImportToken")
wrappingKey = Chilkat::CkPublicKey.new()
success = wrappingKey.LoadBase64(result.stringOf("PublicKey"))
if (success != true)
    print "Could not load the RSA wrapping key." + "\n";
    exit
end

if (wrappingKey.get_KeySize() != 4096)
    print "Expected the requested 4096-bit RSA wrapping key." + "\n";
    exit
end

#  Export PKCS#8 DER in memory only; never print or write unencrypted key material.
pkcs8Base64 = privKey.getPkcs8ENC("base64")
if (privKey.get_LastMethodSuccess() != true)
    print "Could not encode the private key as PKCS#8." + "\n";
    exit
end

prng = Chilkat::CkPrng.new()
#  A fresh 32-byte (256-bit) AES key, not a 32-bit key.
aesKeyBase64 = prng.genRandom(32,"base64")
if (prng.get_LastMethodSuccess() != true)
    print "Could not generate wrapping key." + "\n";
    exit
end

crypt = Chilkat::CkCrypt2.new()
wrappedPrivateKey = crypt.aesKeyWrapWithPadding(aesKeyBase64,pkcs8Base64,"base64")
if (crypt.get_LastMethodSuccess() != true)
    print "AES key wrapping failed." + "\n";
    exit
end

wrappedAesKey = Chilkat::CkBinData.new()
success = wrappedAesKey.AppendEncoded(aesKeyBase64,"base64")
if (success != true)
    print "Could not decode AES key." + "\n";
    exit
end

rsa = Chilkat::CkRsa.new()
success = rsa.UsePublicKey(wrappingKey)
if (success != true)
    print "Could not select the RSA wrapping key." + "\n";
    exit
end

rsa.put_PkcsPadding(false)
rsa.put_OaepHash("sha256")
rsa.put_OaepMgfHash("sha256")
success = rsa.EncryptBd(wrappedAesKey,false)
if (success != true)
    print "RSA-OAEP AES-key wrapping failed." + "\n";
    exit
end

#  Wire order is RSA-wrapped AES key FIRST, followed by AES-wrapped PKCS#8.
encryptedMaterial = Chilkat::CkBinData.new()
success = encryptedMaterial.AppendBd(wrappedAesKey)
if (success != true)
    print "Could not assemble encrypted material." + "\n";
    exit
end

success = encryptedMaterial.AppendEncoded(wrappedPrivateKey,"base64")
if (success != true)
    print "Could not append wrapped private key." + "\n";
    exit
end

body.Clear()
success = body.UpdateString("KeyId",keyId)
if (success != true)
    print "Could not set KeyId." + "\n";
    exit
end

success = body.UpdateString("ImportToken",importToken)
if (success != true)
    print "Could not set ImportToken." + "\n";
    exit
end

success = body.UpdateString("EncryptedKeyMaterial",encryptedMaterial.getEncoded("base64"))
if (success != true)
    print "Could not set EncryptedKeyMaterial." + "\n";
    exit
end

success = body.UpdateString("ExpirationModel","KEY_MATERIAL_DOES_NOT_EXPIRE")
if (success != true)
    print "Could not set ExpirationModel." + "\n";
    exit
end

success = rest.ClearAllQueryParams()
if (success != true)
    print "Could not clear previous query parameters." + "\n";
    exit
end

#  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)
    success = rest.AddQueryParam("X-Amz-Security-Token",credentials.stringOf("session_token"))
    if (success != true)
        print "Could not set session token." + "\n";
        exit
    end

end

success = rest.AddHeader("X-Amz-Target","TrentService.ImportKeyMaterial")
if (success != true)
    print "Could not set operation." + "\n";
    exit
end

success = rest.AddHeader("Content-Type","application/x-amz-json-1.1")
if (success != true)
    print "Could not set content type." + "\n";
    exit
end

responseJson = rest.fullRequestString("POST","/",body.emit())
if (rest.get_LastMethodSuccess() != true)
    print "KMS request did not complete; inspect diagnostics privately. Reconcile any write before retrying." + "\n";
    exit
end

if (rest.get_ResponseStatusCode() != 200)
    print "KMS HTTP status: " + rest.get_ResponseStatusCode().to_s() + "\n";
    success = result.Load(responseJson)
    if (success == true)
        if (result.JsonTypeOf("__type") == 1)
            print "AWS error code: " + result.stringOf("__type") + "\n";
        end

    end

    print "AWS request ID: " + rest.responseHdrByName("x-amzn-RequestId") + "\n";
    #  Do not print full bodies, headers, credentials, key material, or tokens.
    exit
end

#  HTTP 200 indicates acceptance; response content can be empty.
print "Key material import accepted for: " + keyId + "\n";
print "Use DescribeKey to confirm Enabled before signing; KMS is eventually consistent." + "\n";
#  This does not securely erase copies of sensitive strings from managed memory.