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

Dart
import 'package:chilkat/chilkat.dart';

void main() {
  // 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..
  final 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.
  final cert = CkCert();
  try {
    cert.loadPfxFile(pfxFilePath, 'pfx_password');
  } on ChilkatException catch (e) {
    print(e.lastErrorText);
    return;
  }

  final privKey = CkPrivateKey();
  try {
    cert.getPrivateKey(privKey);
  } on ChilkatException catch (e) {
    print(e.lastErrorText);
    return;
  }

  // Get the private key as a JWK so we can get information about it..
  final jwk = CkJsonObject();
  jwk.load(privKey.getJwk());
  jwk.emitCompact = 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

  final sbKeySpec = CkStringBuilder();

  // Get the key type
  final sbKty = CkStringBuilder();
  sbKty.append(jwk.stringOf('kty'));

  // If this is an EC key, get the curve name
  final sbCurve = CkStringBuilder();
  if (jwk.hasMember('crv')) {
    sbKeySpec.append(jwk.stringOf('crv'));
    // The curve names in the jwk will be "P-256", "P-384", or "P-521"
    final numReplaced = sbKeySpec.replace('P-', 'ECC_NIST_P');
  }

  if (sbKty.contentsEqual('RSA', false)) {
    sbKeySpec.append('RSA_');
    sbKeySpec.appendInt(privKey.bitLength);
  }

  if (sbKeySpec.length == 0) {
    print('Invalid key type');
    return;
  }

  final jsonReq = CkJsonObject();
  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 = 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..
  final rest = CkRest();

  // 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/
  final bTls = true;
  final port = 443;
  final bAutoReconnect = true;
  rest.connect('kms.us-west-2.amazonaws.com', port, bTls, bAutoReconnect);

  // Provide AWS credentials for the REST call.
  final authAws = CkAuthAws();
  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');

  var strJson = '';
  final json = CkJsonObject();

  // 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');

  try {
    strJson = rest.fullRequestString('POST', '/', jsonReq.emit());
  } on ChilkatException catch (e) {
    print(e.lastErrorText);
    return;
  }

  // A successful response will have a status code equal to 200.
  if (rest.responseStatusCode != 200) {
    print('response status code = ${rest.responseStatusCode}');
    print('response status text = ${rest.responseStatusText}');
    print('response header: ${rest.responseHeader}');
    print('response body: $strJson');
    return;
  }

  // Examine the successful JSON response (shown below)
  json.load(strJson);
  print(json.emit());

  // TEMPORARY

  // TEMPORARY
  try {
    json.loadFile('c:/aaworkarea/importParams.json');
  } on ChilkatException catch (e) {
    print(e.lastErrorText);
    return;
  }

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

  final pkcs8Base64 = privKey.getPkcs8ENC('base64');

  // Generate a random 32-bit (256-bit) AES wrapping key.
  final prng = CkPrng();
  final aesKeyBase64 = prng.genRandom(32, 'base64');
  final bdAesKey = CkBinData();
  bdAesKey.appendEncoded(aesKeyBase64, 'base64');

  // -------------------------------------------------------------
  // The AesWrapWithPadding method is added in Chilkat v9.5.0.96
  // 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
  // -------------------------------------------------------------

  final crypt = CkCrypt2();
  // The encryptedPkcs8 will be returned as a base64 string.
  final String encryptedPkcs8;
  try {
    encryptedPkcs8 = crypt.aesKeyWrapWithPadding(aesKeyBase64, pkcs8Base64, 'base64');
  } on ChilkatException catch (e) {
    print(e.lastErrorText);
    return;
  }

  // Encrypt our random 256-bit AES key using the public key found in 
  // the import params we just received.
  final rsaPubKeyBase64 = json.stringOf('PublicKey');

  // We need to do RSAES_OAEP_SHA_256
  final rsa = CkRsa();

  final pubKey = CkPublicKey();
  try {
    pubKey.loadBase64(rsaPubKeyBase64);
  } on ChilkatException catch (e) {
    print(e.lastErrorText);
    return;
  }

  try {
    rsa.usePublicKey(pubKey);
  } on ChilkatException catch (e) {
    print(e.lastErrorText);
    return;
  }

  rsa.pkcsPadding = false;
  rsa.oaepMgfHash = 'sha256';
  rsa.oaepHash = 'sha256';
  rsa.encodingMode = 'base64';
  try {
    rsa.encryptBd(bdAesKey, false);
  } on ChilkatException catch (e) {
    print(e.lastErrorText);
    return;
  }

  final 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.
  final bdCombined = CkBinData();
  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');

  try {
    strJson = rest.fullRequestString('POST', '/', jsonReq.emit());
  } on ChilkatException catch (e) {
    print(e.lastErrorText);
    return;
  }

  // A successful response will have a status code equal to 200.
  if (rest.responseStatusCode != 200) {
    print('response status code = ${rest.responseStatusCode}');
    print('response status text = ${rest.responseStatusText}');
    print('response header: ${rest.responseHeader}');
    print('response body: $strJson');
    return;
  }

  // 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());
}