Sample code for 30+ languages & platforms
Lua Requires Chilkat v11.0.0+

AWS KMS Import PFX Key (Low-Level)

See more AWS KMS Examples

Imports a certificate's private key from a .pfx file to new key created in AWS KMS.

Chilkat Lua Downloads

Lua
local chilkat = require("chilkat")

-- This example requires the Chilkat API to have been previously unlocked.
-- See Global Unlock Sample for sample code.

-- Note: This example is using a relative file path.  You can also specify a full file path, such as "C:/someDir/myCertAndKey.pfx"
-- or a file path the makes sense on non-Windows operating systems..
local pfxFilePath = "qa_data/pfx/myCertAndKey.pfx"

-- Load the PFX into the Chilkat certificate object so we can get
-- information about the key type and size.
local cert = chilkat.Cert.new()
local success = cert:load_pfx_file(pfxFilePath, "pfx_password")
if not success then
    print(cert.last_error_text)
    return
end

local privKey = chilkat.PrivateKey.new()
success = cert:get_private_key(privKey)
if not success then
    print(cert.last_error_text)
    return
end

-- Get the private key as a JWK so we can get information about it..
local jwk = chilkat.JsonObject.new()
jwk:load(privKey:get_jwk())
jwk.emit_compact = false
print(jwk:emit())

-- The keySpec should be one of the following:
-- RSA_2048
-- RSA_3072
-- RSA_4096
-- ECC_NIST_P256
-- ECC_NIST_P384
-- ECC_NIST_P521

local sbKeySpec = chilkat.StringBuilder.new()

-- Get the key type
local sbKty = chilkat.StringBuilder.new()
sbKty:append(jwk:string_of("kty"))

-- If this is an EC key, get the curve name
local sbCurve = chilkat.StringBuilder.new()
if jwk:has_member("crv") then
    sbKeySpec:append(jwk:string_of("crv"))
    -- The curve names in the jwk will be "P-256", "P-384", or "P-521"
    local numReplaced = sbKeySpec:replace("P-", "ECC_NIST_P")
end

if sbKty:contents_equal("RSA", false) then
    sbKeySpec:append("RSA_")
    sbKeySpec:append_int(privKey.bit_length)
end

if sbKeySpec.length == 0 then
    print("Invalid key type")
    return
end

local jsonReq = chilkat.JsonObject.new()
jsonReq:update_string("Description", "Imported from PFX")
jsonReq:update_string("KeySpec", sbKeySpec:get_as_string())
jsonReq:update_string("KeyUsage", "SIGN_VERIFY")
jsonReq:update_string("Origin", "EXTERNAL")
jsonReq:update_string("Tags[0].TagKey", "purpose")
jsonReq:update_string("Tags[0].TagValue", "testing")

jsonReq.emit_compact = false
print(jsonReq:emit())

-- Our JSON request body is

-- {
--   "Description": "Imported from PFX",
--   "KeySpec": "RSA_2048",
--   "KeyUsage": "SIGN_VERIFY",
--   "Origin": "EXTERNAL",
--   "Tags": [
--     {
--       "TagKey": "purpose",
--       "TagValue": "testing"
--     }
--   ]
-- }

-- Send the POST to create a KMS key with no key material.
-- After creating, we'll continue with the steps needed to import the key material..
local rest = chilkat.Rest.new()

-- Connect to the Amazon AWS REST server.
-- Make sure to use the region that is correct for you.
-- such as https://kms.us-west-2.amazonaws.com/
local bTls = true
local port = 443
local bAutoReconnect = true
success = rest:connect("kms.us-west-2.amazonaws.com", port, bTls, bAutoReconnect)

-- Provide AWS credentials for the REST call.
local authAws = chilkat.AuthAws.new()
authAws.access_key = "AWS_ACCESS_KEY"
authAws.secret_key = "AWS_SECRET_KEY"
-- the region should match our URL above..
authAws.region = "us-west-2"
authAws.service_name = "kms"

rest:set_auth_aws(authAws)

rest:add_header("X-Amz-Target", "TrentService.CreateKey")
rest:add_header("Content-Type", "application/x-amz-json-1.1")

local json = chilkat.JsonObject.new()

-- strJson = rest.FullRequestString("POST","/",jsonReq.Emit());
-- if (rest.LastMethodSuccess != cktrue) {
--     println rest.LastErrorText;
--     return;
-- }
--
-- // A successful response will have a status code equal to 200.
-- if (rest.ResponseStatusCode != 200) {
--     println "response status code = ",rest.ResponseStatusCode;
--     println "response status text = ",rest.ResponseStatusText;
--     println "response header: ",rest.ResponseHeader;
--     println "response body: ",strJson;
--     return;
-- }
--
-- // Examine the successful JSON response (shown below)
-- ignore = json.Load(strJson);
-- json.EmitCompact = ckfalse;
--
-- println json.Emit();

-- Sample output:

-- {
--   "KeyMetadata": {
--     "AWSAccountId": "954491834127",
--     "Arn": "arn:aws:kms:us-west-2:954491834127:key/47c7dc6d-cab9-42ed-bfd6-f6387478e6f1",
--     "CreationDate": 1.697495602193E9,
--     "CustomerMasterKeySpec": "RSA_4096",
--     "Description": "Imported from PFX",
--     "Enabled": false,
--     "KeyId": "47c7dc6d-cab9-42ed-bfd6-f6387478e6f1",
--     "KeyManager": "CUSTOMER",
--     "KeySpec": "RSA_4096",
--     "KeyState": "PendingImport",
--     "KeyUsage": "SIGN_VERIFY",
--     "MultiRegion": false,
--     "Origin": "EXTERNAL",
--     "SigningAlgorithms": [
--       "RSASSA_PKCS1_V1_5_SHA_256",
--       "RSASSA_PKCS1_V1_5_SHA_384",
--       "RSASSA_PKCS1_V1_5_SHA_512",
--       "RSASSA_PSS_SHA_256",
--       "RSASSA_PSS_SHA_384",
--       "RSASSA_PSS_SHA_512"
--     ]
--   }
-- }

-- The next step is to download the wrapping public key and import token

-- Build the JSON request.

jsonReq:clear()
jsonReq:update_string("KeyId", "arn:aws:kms:us-west-2:954491834127:key/47c7dc6d-cab9-42ed-bfd6-f6387478e6f1")
jsonReq:update_string("WrappingAlgorithm", "RSA_AES_KEY_WRAP_SHA_256")
jsonReq:update_string("WrappingKeySpec", "RSA_4096")

-- Add (replace) headers and send the request.
rest:add_header("X-Amz-Target", "TrentService.GetParametersForImport")
rest:add_header("Content-Type", "application/x-amz-json-1.1")

local strJson = rest:full_request_string("POST", "/", jsonReq:emit())
if not rest.last_method_success then
    print(rest.last_error_text)
    return
end

-- A successful response will have a status code equal to 200.
if rest.response_status_code ~= 200 then
    print("response status code = " .. rest.response_status_code)
    print("response status text = " .. rest.response_status_text)
    print("response header: " .. rest.response_header)
    print("response body: " .. strJson)
    return
end

-- Examine the successful JSON response (shown below)
json:load(strJson)
print(json:emit())

-- TEMPORARY

-- TEMPORARY
success = json:load_file("c:/aaworkarea/importParams.json")
if not success then
    print(json.last_error_text)
    return
end

-- -----------------------------------------------------------------------
-- Step 3: Encrypt the key material (i.e. the RSA or EC key for the private key obtained from the PFX)
-- We'll be encrypting the PKCS8 formatted key.

local pkcs8_base64 = privKey:get_pkcs8_enc("base64")

-- Generate a random 32-bit (256-bit) AES wrapping key.
local prng = chilkat.Prng.new()
local aes_key_base64 = prng:gen_random(32, "base64")
local bdAesKey = chilkat.BinData.new()
bdAesKey:append_encoded(aes_key_base64, "base64")

-- -------------------------------------------------------------
-- The AesWrapWithPadding method is used
-- to provide the functionality to do this:

-- # Encrypt your key material with the AES symmetric encryption key
-- $ openssl enc -id-aes256-wrap-pad \
--         -K "$(xxd -p < aes-key.bin | tr -d '\n')" \
--         -iv A65959A6 \
--         -in PlaintextKeyMaterial.bin\
--         -out key-material-wrapped.bin
-- -------------------------------------------------------------

local crypt = chilkat.Crypt2.new()
-- The encryptedPkcs8 will be returned as a base64 string.
local encryptedPkcs8 = crypt:aes_key_wrap_with_padding(aes_key_base64, pkcs8_base64, "base64")
if not crypt.last_method_success then
    print(crypt.last_error_text)
    return
end

-- Encrypt our random 256-bit AES key using the public key found in
-- the import params we just received.
local rsaPubKeyBase64 = json:string_of("PublicKey")

-- We need to do RSAES_OAEP_SHA_256
local rsa = chilkat.Rsa.new()

local pubKey = chilkat.PublicKey.new()
success = pubKey:load_base64(rsaPubKeyBase64)
if not success then
    print(pubKey.last_error_text)
    return
end

success = rsa:use_public_key(pubKey)
if not success then
    print(rsa.last_error_text)
    return
end

rsa.pkcs_padding = false
rsa.oaep_mgf_hash = "sha256"
rsa.oaep_hash = "sha256"
rsa.encoding_mode = "base64"
success = rsa:encrypt_bd(bdAesKey, false)
if not success then
    print(rsa.last_error_text)
    return
end

local encryptedAesKey = bdAesKey:get_encoded("base64")

-- Concatenate the encrypted key material (i.e. the encrypted PKCS8 of our RSA private key, which came from the PFX) and the encrypted AES key.
local bdCombined = chilkat.BinData.new()
bdCombined:append_encoded(encryptedAesKey, "base64")
bdCombined:append_encoded(encryptedPkcs8, "base64")

-- -----------------------------------------------------------------------
-- Step 4:  Finally, let's import the key material..

jsonReq:clear()
jsonReq:update_string("KeyId", json:string_of("KeyId"))
jsonReq:update_string("ImportToken", json:string_of("ImportToken"))
jsonReq:update_string("EncryptedKeyMaterial", bdCombined:get_encoded("base64"))
jsonReq:update_string("ExpirationModel", "KEY_MATERIAL_DOES_NOT_EXPIRE")

-- Add (replace) headers and send the request.
rest:add_header("X-Amz-Target", "TrentService.ImportKeyMaterial")
rest:add_header("Content-Type", "application/x-amz-json-1.1")

strJson = rest:full_request_string("POST", "/", jsonReq:emit())
if not rest.last_method_success then
    print(rest.last_error_text)
    return
end

-- A successful response will have a status code equal to 200.
if rest.response_status_code ~= 200 then
    print("response status code = " .. rest.response_status_code)
    print("response status text = " .. rest.response_status_text)
    print("response header: " .. rest.response_header)
    print("response body: " .. strJson)
    return
end

-- OK, the key should be imported!  Yay!
-- You now have the private key of your certificate imported as a AWS key in the AWS Key Management Service.

-- Examine the successful JSON response (shown below)
json:load(strJson)
print(json:emit())