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

Perl
use strict;
use warnings;
use Chilkat2;

# 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..
my $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.
my $cert = Chilkat2::Cert->new;
my $success = $cert->LoadPfxFile($pfxFilePath, 'pfx_password');
if (!$success) {
    print $cert->LastErrorText, "\n";
    exit;
}

my $privKey = Chilkat2::PrivateKey->new;
$success = $cert->GetPrivateKey($privKey);
if (!$success) {
    print $cert->LastErrorText, "\n";
    exit;
}

# Get the private key as a JWK so we can get information about it..
my $jwk = Chilkat2::JsonObject->new;
$jwk->Load($privKey->GetJwk());
$jwk->EmitCompact(0);
print $jwk->Emit(), "\n";

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

my $sbKeySpec = Chilkat2::StringBuilder->new;

# Get the key type
my $sbKty = Chilkat2::StringBuilder->new;
$sbKty->Append($jwk->StringOf('kty'));

# If this is an EC key, get the curve name
my $sbCurve = Chilkat2::StringBuilder->new;
if ($jwk->HasMember('crv')) {
    $sbKeySpec->Append($jwk->StringOf('crv'));
    # The curve names in the jwk will be "P-256", "P-384", or "P-521"
    my $numReplaced = $sbKeySpec->Replace('P-', 'ECC_NIST_P');
}

if ($sbKty->ContentsEqual('RSA', 0)) {
    $sbKeySpec->Append('RSA_');
    $sbKeySpec->AppendInt($privKey->BitLength);
}

if ($sbKeySpec->Length == 0) {
    print "Invalid key type\n";
    exit;
}

my $jsonReq = Chilkat2::JsonObject->new;
$jsonReq->UpdateString('Description', 'Imported from PFX');
$jsonReq->UpdateString('KeySpec', $sbKeySpec->GetAsString());
$jsonReq->UpdateString('KeyUsage', 'SIGN_VERIFY');
$jsonReq->UpdateString('Origin', 'EXTERNAL');
$jsonReq->UpdateString('Tags[0].TagKey', 'purpose');
$jsonReq->UpdateString('Tags[0].TagValue', 'testing');

$jsonReq->EmitCompact(0);
print $jsonReq->Emit(), "\n";

# 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..
my $rest = Chilkat2::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/
my $bTls = 1;
my $port = 443;
my $bAutoReconnect = 1;
$success = $rest->Connect('kms.us-west-2.amazonaws.com', $port, $bTls, $bAutoReconnect);

# Provide AWS credentials for the REST call.
my $authAws = Chilkat2::AuthAws->new;
$authAws->AccessKey('AWS_ACCESS_KEY');
$authAws->SecretKey('AWS_SECRET_KEY');
# the region should match our URL above..
$authAws->Region('us-west-2');
$authAws->ServiceName('kms');

$rest->SetAuthAws($authAws);

$rest->AddHeader('X-Amz-Target', 'TrentService.CreateKey');
$rest->AddHeader('Content-Type', 'application/x-amz-json-1.1');

my $json = Chilkat2::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->UpdateString('KeyId', 'arn:aws:kms:us-west-2:954491834127:key/47c7dc6d-cab9-42ed-bfd6-f6387478e6f1');
$jsonReq->UpdateString('WrappingAlgorithm', 'RSA_AES_KEY_WRAP_SHA_256');
$jsonReq->UpdateString('WrappingKeySpec', 'RSA_4096');

# Add (replace) headers and send the request.
$rest->AddHeader('X-Amz-Target', 'TrentService.GetParametersForImport');
$rest->AddHeader('Content-Type', 'application/x-amz-json-1.1');

my $strJson = $rest->FullRequestString('POST', '/', $jsonReq->Emit());
if (!$rest->LastMethodSuccess) {
    print $rest->LastErrorText, "\n";
    exit;
}

# A successful response will have a status code equal to 200.
if ($rest->ResponseStatusCode != 200) {
    print 'response status code = ', $rest->ResponseStatusCode, "\n";
    print 'response status text = ', $rest->ResponseStatusText, "\n";
    print 'response header: ', $rest->ResponseHeader, "\n";
    print 'response body: ', $strJson, "\n";
    exit;
}

# Examine the successful JSON response (shown below)
$json->Load($strJson);
print $json->Emit(), "\n";

# TEMPORARY

# TEMPORARY
$success = $json->LoadFile('c:/aaworkarea/importParams.json');
if (!$success) {
    print $json->LastErrorText, "\n";
    exit;
}

# -----------------------------------------------------------------------
# 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.

my $pkcs8_base64 = $privKey->GetPkcs8ENC('base64');

# Generate a random 32-bit (256-bit) AES wrapping key.
my $prng = Chilkat2::Prng->new;
my $aes_key_base64 = $prng->GenRandom(32, 'base64');
my $bdAesKey = Chilkat2::BinData->new;
$bdAesKey->AppendEncoded($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
# -------------------------------------------------------------

my $crypt = Chilkat2::Crypt2->new;
# The encryptedPkcs8 will be returned as a base64 string.
my $encryptedPkcs8 = $crypt->AesKeyWrapWithPadding($aes_key_base64, $pkcs8_base64, 'base64');
if (!$crypt->LastMethodSuccess) {
    print $crypt->LastErrorText, "\n";
    exit;
}

# Encrypt our random 256-bit AES key using the public key found in
# the import params we just received.
my $rsaPubKeyBase64 = $json->StringOf('PublicKey');

# We need to do RSAES_OAEP_SHA_256
my $rsa = Chilkat2::Rsa->new;

my $pubKey = Chilkat2::PublicKey->new;
$success = $pubKey->LoadBase64($rsaPubKeyBase64);
if (!$success) {
    print $pubKey->LastErrorText, "\n";
    exit;
}

$success = $rsa->UsePublicKey($pubKey);
if (!$success) {
    print $rsa->LastErrorText, "\n";
    exit;
}

$rsa->PkcsPadding(0);
$rsa->OaepMgfHash('sha256');
$rsa->OaepHash('sha256');
$rsa->EncodingMode('base64');
$success = $rsa->EncryptBd($bdAesKey, 0);
if (!$success) {
    print $rsa->LastErrorText, "\n";
    exit;
}

my $encryptedAesKey = $bdAesKey->GetEncoded('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.
my $bdCombined = Chilkat2::BinData->new;
$bdCombined->AppendEncoded($encryptedAesKey, 'base64');
$bdCombined->AppendEncoded($encryptedPkcs8, 'base64');

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

$jsonReq->Clear();
$jsonReq->UpdateString('KeyId', $json->StringOf('KeyId'));
$jsonReq->UpdateString('ImportToken', $json->StringOf('ImportToken'));
$jsonReq->UpdateString('EncryptedKeyMaterial', $bdCombined->GetEncoded('base64'));
$jsonReq->UpdateString('ExpirationModel', 'KEY_MATERIAL_DOES_NOT_EXPIRE');

# Add (replace) headers and send the request.
$rest->AddHeader('X-Amz-Target', 'TrentService.ImportKeyMaterial');
$rest->AddHeader('Content-Type', 'application/x-amz-json-1.1');

$strJson = $rest->FullRequestString('POST', '/', $jsonReq->Emit());
if (!$rest->LastMethodSuccess) {
    print $rest->LastErrorText, "\n";
    exit;
}

# A successful response will have a status code equal to 200.
if ($rest->ResponseStatusCode != 200) {
    print 'response status code = ', $rest->ResponseStatusCode, "\n";
    print 'response status text = ', $rest->ResponseStatusText, "\n";
    print 'response header: ', $rest->ResponseHeader, "\n";
    print 'response body: ', $strJson, "\n";
    exit;
}

# 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(), "\n";