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

PHP ActiveX
<?php

$success = 0;

$stringCompare = new COM("Chilkat.StringBuilder");
//  Assumes Chilkat is unlocked. See Global Unlock Sample.
//  Keep this credentials file outside public web content and source control.
$credentials = new COM("Chilkat.JsonObject");
$credentials->Strict = 1;
$success = $credentials->LoadFile('qa_data/aws/kms.json');
if ($success != 1) {
    print 'Could not load private KMS configuration.' . "\n";
    exit;
}

$stringCompare->SetString($credentials->stringOf('access_key'));
$stringMatch1 = $stringCompare->ContentsEqual('',1);
if (($credentials->JsonTypeOf('access_key') != 1) or ($stringMatch1 == 1)) {
    print 'Missing or invalid access_key.' . "\n";
    exit;
}

$stringCompare->SetString($credentials->stringOf('secret_key'));
$stringMatch2 = $stringCompare->ContentsEqual('',1);
if (($credentials->JsonTypeOf('secret_key') != 1) or ($stringMatch2 == 1)) {
    print 'Missing or invalid secret_key.' . "\n";
    exit;
}

$region = 'us-west-2';
$endpoint = new COM("Chilkat.StringBuilder");
$endpoint->Append('kms.');
$endpoint->Append($region);
$endpoint->Append('.amazonaws.com');
$aws = new COM("Chilkat.AuthAws");
$aws->AccessKey = $credentials->stringOf('access_key');
$aws->SecretKey = $credentials->stringOf('secret_key');
$aws->Region = $region;
$aws->ServiceName = 'kms';
$aws->SignatureVersion = 4;
$rest = new COM("Chilkat.Rest");
$rest->ConnectTimeoutMs = 20000;
$rest->IdleTimeoutMs = 60000;
$rest->VerboseLogging = 0;
$success = $rest->SetAuthAws($aws);
if ($success != 1) {
    print 'Could not configure AWS signing.' . "\n";
    exit;
}

if ($credentials->HasMember('session_token') == 1) {
    $stringCompare->SetString($credentials->stringOf('session_token'));
    $stringMatch3 = $stringCompare->ContentsEqual('',1);
    if (($credentials->JsonTypeOf('session_token') != 1) or ($stringMatch3 == 1)) {
        print 'Missing or invalid session_token.' . "\n";
        exit;
    }

}

$connection = new COM("Chilkat.Socket");
$connection->RequireSslCertVerify = 1;
$connection->MaxReadIdleMs = 60000;
$connection->MaxSendIdleMs = 60000;
$success = $connection->Connect($endpoint->getAsString(),443,1,20000);
if ($success != 1) {
    print 'TLS connection failed; inspect diagnostics privately.' . "\n";
    exit;
}

$success = $rest->UseConnection($connection,1);
if ($success != 1) {
    print 'Could not attach TLS connection.' . "\n";
    exit;
}

//  Keep connection alive while Rest uses it.
$body = new COM("Chilkat.JsonObject");
$result = new COM("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) {
    print 'Missing or invalid pfx_password.' . "\n";
    exit;
}

$cert = new COM("Chilkat.Cert");
$success = $cert->LoadPfxFile('qa_data/pfx/myCertAndKey.pfx',$credentials->stringOf('pfx_password'));
if ($success != 1) {
    print 'Could not load PFX; inspect diagnostics privately.' . "\n";
    exit;
}

$privKey = new COM("Chilkat.PrivateKey");
$success = $cert->GetPrivateKey($privKey);
if ($success != 1) {
    print 'PFX does not contain a usable private key.' . "\n";
    exit;
}

//  Only inspect the PUBLIC JWK to identify a supported key type and curve.
$sourcePublic = new COM("Chilkat.PublicKey");
$success = $privKey->ToPublicKey($sourcePublic);
if ($success != 1) {
    print 'Could not get the public key.' . "\n";
    exit;
}

$publicJwk = $sourcePublic->getJwk();
if ($sourcePublic->LastMethodSuccess != 1) {
    print 'Could not inspect public key type.' . "\n";
    exit;
}

$keyInfo = new COM("Chilkat.JsonObject");
$keyInfo->Strict = 1;
$success = $keyInfo->Load($publicJwk);
if ($success != 1) {
    print 'Could not parse public key description.' . "\n";
    exit;
}

$keySpec = '';
$stringCompare->SetString($keyInfo->stringOf('kty'));
$stringMatch4 = $stringCompare->ContentsEqual('RSA',1);
if ($stringMatch4 == 1) {
    if ($privKey->BitLength == 2048) {
        $keySpec = 'RSA_2048';
    }

    if ($privKey->BitLength == 3072) {
        $keySpec = 'RSA_3072';
    }

    if ($privKey->BitLength == 4096) {
        $keySpec = 'RSA_4096';
    }

}

$stringCompare->SetString($keyInfo->stringOf('kty'));
$stringMatch5 = $stringCompare->ContentsEqual('EC',1);
if ($stringMatch5 == 1) {
    $stringCompare->SetString($keyInfo->stringOf('crv'));
    $stringMatch6 = $stringCompare->ContentsEqual('P-256',1);
    if ($stringMatch6 == 1) {
        $keySpec = 'ECC_NIST_P256';
    }

    $stringCompare->SetString($keyInfo->stringOf('crv'));
    $stringMatch7 = $stringCompare->ContentsEqual('P-384',1);
    if ($stringMatch7 == 1) {
        $keySpec = 'ECC_NIST_P384';
    }

    $stringCompare->SetString($keyInfo->stringOf('crv'));
    $stringMatch8 = $stringCompare->ContentsEqual('P-521',1);
    if ($stringMatch8 == 1) {
        $keySpec = 'ECC_NIST_P521';
    }

}

$stringCompare->SetString($keySpec);
$stringMatch9 = $stringCompare->ContentsEqual('',1);
if ($stringMatch9 == 1) {
    print 'Use RSA 2048/3072/4096 or a NIST P-256/P-384/P-521 EC private key.' . "\n";
    exit;
}

$stringCompare->SetString($credentials->stringOf('key_id'));
$stringMatch10 = $stringCompare->ContentsEqual('',1);
if (($credentials->JsonTypeOf('key_id') != 1) or ($stringMatch10 == 1)) {
    print 'Missing or invalid key_id.' . "\n";
    exit;
}

$keyId = $credentials->stringOf('key_id');
$success = $body->UpdateString('KeyId',$keyId);
if ($success != 1) {
    print 'Could not set KeyId.' . "\n";
    exit;
}

$success = $rest->ClearAllQueryParams();
if ($success != 1) {
    print 'Could not clear previous query parameters.' . "\n";
    exit;
}

//  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) {
    $success = $rest->AddQueryParam('X-Amz-Security-Token',$credentials->stringOf('session_token'));
    if ($success != 1) {
        print 'Could not set session token.' . "\n";
        exit;
    }

}

$success = $rest->AddHeader('X-Amz-Target','TrentService.DescribeKey');
if ($success != 1) {
    print 'Could not set operation.' . "\n";
    exit;
}

$success = $rest->AddHeader('Content-Type','application/x-amz-json-1.1');
if ($success != 1) {
    print 'Could not set content type.' . "\n";
    exit;
}

$responseJson = $rest->fullRequestString('POST','/',$body->emit());
if ($rest->LastMethodSuccess != 1) {
    print 'KMS request did not complete; inspect diagnostics privately. Reconcile any write before retrying.' . "\n";
    exit;
}

if ($rest->ResponseStatusCode != 200) {
    print 'KMS HTTP status: ' . $rest->ResponseStatusCode . "\n";
    $success = $result->Load($responseJson);
    if ($success == 1) {
        if ($result->JsonTypeOf('__type') == 1) {
            print 'AWS error code: ' . $result->stringOf('__type') . "\n";
        }

    }

    print 'AWS request ID: ' . $rest->responseHdrByName('x-amzn-RequestId') . "\n";
    //  Do not print full bodies, headers, credentials, key material, or tokens.
    exit;
}

$success = $result->Load($responseJson);
if ($success != 1) {
    print 'Expected a well-formed JSON response.' . "\n";
    exit;
}

$stringCompare->SetString($result->stringOf('KeyMetadata.KeyId'));
$stringMatch11 = $stringCompare->ContentsEqual('',1);
if (($result->JsonTypeOf('KeyMetadata.KeyId') != 1) or ($stringMatch11 == 1)) {
    print 'Missing or invalid KeyMetadata.KeyId.' . "\n";
    exit;
}

$stringCompare->SetString($result->stringOf('KeyMetadata.Arn'));
$stringMatch12 = $stringCompare->ContentsEqual('',1);
if (($result->JsonTypeOf('KeyMetadata.Arn') != 1) or ($stringMatch12 == 1)) {
    print 'Missing or invalid KeyMetadata.Arn.' . "\n";
    exit;
}

$stringCompare->SetString($result->stringOf('KeyMetadata.Origin'));
$stringMatch13 = $stringCompare->ContentsEqual('EXTERNAL',1);
if ($stringMatch13 != 1) {
    print 'Destination must have EXTERNAL origin.' . "\n";
    exit;
}

$stringCompare->SetString($result->stringOf('KeyMetadata.KeyState'));
$stringMatch14 = $stringCompare->ContentsEqual('PendingImport',1);
if ($stringMatch14 != 1) {
    print 'This initial-import sample requires PendingImport; it does not replace existing material.' . "\n";
    exit;
}

$stringCompare->SetString($result->stringOf('KeyMetadata.KeyUsage'));
$stringMatch15 = $stringCompare->ContentsEqual('SIGN_VERIFY',1);
if ($stringMatch15 != 1) {
    print 'Destination must have SIGN_VERIFY usage.' . "\n";
    exit;
}

$stringCompare->SetString($result->stringOf('KeyMetadata.KeySpec'));
$stringMatch16 = $stringCompare->ContentsEqual($keySpec,1);
if ($stringMatch16 != 1) {
    print 'PFX private key does not match the destination KeySpec.' . "\n";
    exit;
}

//  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) {
    print 'Could not set KeyId.' . "\n";
    exit;
}

$success = $body->UpdateString('WrappingAlgorithm','RSA_AES_KEY_WRAP_SHA_256');
if ($success != 1) {
    print 'Could not set WrappingAlgorithm.' . "\n";
    exit;
}

$success = $body->UpdateString('WrappingKeySpec','RSA_4096');
if ($success != 1) {
    print 'Could not set WrappingKeySpec.' . "\n";
    exit;
}

$success = $rest->ClearAllQueryParams();
if ($success != 1) {
    print 'Could not clear previous query parameters.' . "\n";
    exit;
}

//  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) {
    $success = $rest->AddQueryParam('X-Amz-Security-Token',$credentials->stringOf('session_token'));
    if ($success != 1) {
        print 'Could not set session token.' . "\n";
        exit;
    }

}

$success = $rest->AddHeader('X-Amz-Target','TrentService.GetParametersForImport');
if ($success != 1) {
    print 'Could not set operation.' . "\n";
    exit;
}

$success = $rest->AddHeader('Content-Type','application/x-amz-json-1.1');
if ($success != 1) {
    print 'Could not set content type.' . "\n";
    exit;
}

$responseJson = $rest->fullRequestString('POST','/',$body->emit());
if ($rest->LastMethodSuccess != 1) {
    print 'KMS request did not complete; inspect diagnostics privately. Reconcile any write before retrying.' . "\n";
    exit;
}

if ($rest->ResponseStatusCode != 200) {
    print 'KMS HTTP status: ' . $rest->ResponseStatusCode . "\n";
    $success = $result->Load($responseJson);
    if ($success == 1) {
        if ($result->JsonTypeOf('__type') == 1) {
            print 'AWS error code: ' . $result->stringOf('__type') . "\n";
        }

    }

    print 'AWS request ID: ' . $rest->responseHdrByName('x-amzn-RequestId') . "\n";
    //  Do not print full bodies, headers, credentials, key material, or tokens.
    exit;
}

$success = $result->Load($responseJson);
if ($success != 1) {
    print 'Expected a well-formed JSON response.' . "\n";
    exit;
}

$stringCompare->SetString($result->stringOf('KeyId'));
$stringMatch17 = $stringCompare->ContentsEqual('',1);
if (($result->JsonTypeOf('KeyId') != 1) or ($stringMatch17 == 1)) {
    print 'Missing or invalid KeyId.' . "\n";
    exit;
}

$stringCompare->SetString($result->stringOf('KeyId'));
$stringMatch18 = $stringCompare->ContentsEqual($keyId,1);
if ($stringMatch18 != 1) {
    print 'Import parameters belong to another key.' . "\n";
    exit;
}

$stringCompare->SetString($result->stringOf('ImportToken'));
$stringMatch19 = $stringCompare->ContentsEqual('',1);
if (($result->JsonTypeOf('ImportToken') != 1) or ($stringMatch19 == 1)) {
    print 'Missing or invalid ImportToken.' . "\n";
    exit;
}

$stringCompare->SetString($result->stringOf('PublicKey'));
$stringMatch20 = $stringCompare->ContentsEqual('',1);
if (($result->JsonTypeOf('PublicKey') != 1) or ($stringMatch20 == 1)) {
    print 'Missing or invalid PublicKey.' . "\n";
    exit;
}

if ($result->JsonTypeOf('ParametersValidTo') != 2) {
    print 'Missing import-parameter expiration.' . "\n";
    exit;
}

$now = new COM("Chilkat.CkDateTime");
$expires = new COM("Chilkat.CkDateTime");
$success = $now->SetFromCurrentSystemTime();
if ($success != 1) {
    print 'Could not read current time.' . "\n";
    exit;
}

$success = $result->DateOf('ParametersValidTo',$expires);
if ($success != 1) {
    print 'Invalid import-parameter expiration.' . "\n";
    exit;
}

if ($expires->DiffSeconds($now) <= 0) {
    print 'Import parameters have expired; obtain a fresh token and wrapping key together.' . "\n";
    exit;
}

$importToken = $result->stringOf('ImportToken');
$wrappingKey = new COM("Chilkat.PublicKey");
$success = $wrappingKey->LoadBase64($result->stringOf('PublicKey'));
if ($success != 1) {
    print 'Could not load the RSA wrapping key.' . "\n";
    exit;
}

if ($wrappingKey->KeySize != 4096) {
    print 'Expected the requested 4096-bit RSA wrapping key.' . "\n";
    exit;
}

//  Export PKCS#8 DER in memory only; never print or write unencrypted key material.
$pkcs8Base64 = $privKey->getPkcs8ENC('base64');
if ($privKey->LastMethodSuccess != 1) {
    print 'Could not encode the private key as PKCS#8.' . "\n";
    exit;
}

$prng = new COM("Chilkat.Prng");
//  A fresh 32-byte (256-bit) AES key, not a 32-bit key.
$aesKeyBase64 = $prng->genRandom(32,'base64');
if ($prng->LastMethodSuccess != 1) {
    print 'Could not generate wrapping key.' . "\n";
    exit;
}

$crypt = new COM("Chilkat.Crypt2");
$wrappedPrivateKey = $crypt->aesKeyWrapWithPadding($aesKeyBase64,$pkcs8Base64,'base64');
if ($crypt->LastMethodSuccess != 1) {
    print 'AES key wrapping failed.' . "\n";
    exit;
}

$wrappedAesKey = new COM("Chilkat.BinData");
$success = $wrappedAesKey->AppendEncoded($aesKeyBase64,'base64');
if ($success != 1) {
    print 'Could not decode AES key.' . "\n";
    exit;
}

$rsa = new COM("Chilkat.Rsa");
$success = $rsa->UsePublicKey($wrappingKey);
if ($success != 1) {
    print 'Could not select the RSA wrapping key.' . "\n";
    exit;
}

$rsa->PkcsPadding = 0;
$rsa->OaepHash = 'sha256';
$rsa->OaepMgfHash = 'sha256';
$success = $rsa->EncryptBd($wrappedAesKey,0);
if ($success != 1) {
    print 'RSA-OAEP AES-key wrapping failed.' . "\n";
    exit;
}

//  Wire order is RSA-wrapped AES key FIRST, followed by AES-wrapped PKCS#8.
$encryptedMaterial = new COM("Chilkat.BinData");
$success = $encryptedMaterial->AppendBd($wrappedAesKey);
if ($success != 1) {
    print 'Could not assemble encrypted material.' . "\n";
    exit;
}

$success = $encryptedMaterial->AppendEncoded($wrappedPrivateKey,'base64');
if ($success != 1) {
    print 'Could not append wrapped private key.' . "\n";
    exit;
}

$body->Clear();
$success = $body->UpdateString('KeyId',$keyId);
if ($success != 1) {
    print 'Could not set KeyId.' . "\n";
    exit;
}

$success = $body->UpdateString('ImportToken',$importToken);
if ($success != 1) {
    print 'Could not set ImportToken.' . "\n";
    exit;
}

$success = $body->UpdateString('EncryptedKeyMaterial',$encryptedMaterial->getEncoded('base64'));
if ($success != 1) {
    print 'Could not set EncryptedKeyMaterial.' . "\n";
    exit;
}

$success = $body->UpdateString('ExpirationModel','KEY_MATERIAL_DOES_NOT_EXPIRE');
if ($success != 1) {
    print 'Could not set ExpirationModel.' . "\n";
    exit;
}

$success = $rest->ClearAllQueryParams();
if ($success != 1) {
    print 'Could not clear previous query parameters.' . "\n";
    exit;
}

//  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) {
    $success = $rest->AddQueryParam('X-Amz-Security-Token',$credentials->stringOf('session_token'));
    if ($success != 1) {
        print 'Could not set session token.' . "\n";
        exit;
    }

}

$success = $rest->AddHeader('X-Amz-Target','TrentService.ImportKeyMaterial');
if ($success != 1) {
    print 'Could not set operation.' . "\n";
    exit;
}

$success = $rest->AddHeader('Content-Type','application/x-amz-json-1.1');
if ($success != 1) {
    print 'Could not set content type.' . "\n";
    exit;
}

$responseJson = $rest->fullRequestString('POST','/',$body->emit());
if ($rest->LastMethodSuccess != 1) {
    print 'KMS request did not complete; inspect diagnostics privately. Reconcile any write before retrying.' . "\n";
    exit;
}

if ($rest->ResponseStatusCode != 200) {
    print 'KMS HTTP status: ' . $rest->ResponseStatusCode . "\n";
    $success = $result->Load($responseJson);
    if ($success == 1) {
        if ($result->JsonTypeOf('__type') == 1) {
            print 'AWS error code: ' . $result->stringOf('__type') . "\n";
        }

    }

    print 'AWS request ID: ' . $rest->responseHdrByName('x-amzn-RequestId') . "\n";
    //  Do not print full bodies, headers, credentials, key material, or tokens.
    exit;
}

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

?>