

# Importing and exporting keys
<a name="keys-importexport"></a>

You can import AWS Payment Cryptography keys from other solutions and export them to other solutions, such as HSMs. Many customers exchange keys with service providers using import and export functionality. We designed AWS Payment Cryptography to use a modern, electronic approach to key management that helps you maintain compliance and controls. We recommend using standards-based electronic key exchange instead of paper-based key components.

**Minimum key strengths and the effect on import and export functions**  
PCI requires specific minimum key strengths for cryptographic operations, key storage, and key transmission. These requirements can change when PCI standards are revised. The rules specify that wrapping keys used for storage or transport must be at least as strong as the key being protected. We enforce this requirement automatically during export and prevent keys from being protected by weaker keys, as shown in the following table.  
The following table shows the supported combinations of wrapping keys, keys to protect, and protection methods.      
[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/payment-cryptography/latest/userguide/keys-importexport.html)
For more information, see [Appendix D - Minimum and Equivalent Key Sizes and Strengths for Approved Algorithms](https://docs-prv.pcisecuritystandards.org/PTS/Derived%20Test%20Requirements/PCI_HSM_DTRs_v4.pdf) in the PCI HSM standards. 

**Key Encryption Key (KEK) Exchange**  
We recommend using [ANSI X9.24 TR-34](terminology.md#terms.tr34) standard. This initial key type can be called a Key Encryption Key (KEK), Zone Master Key (ZMK), or Zone Control Master Key (ZCMK). If your systems or partners don't support TR-34 yet you can use [RSA Wrap/Unwrap](terminology.md#terms.rsawrap). If your needs include exchanging AES-256 keys, you can use [ECDH](terminology.md#terms.ecdh).   
If you need to continue processing paper key components until all partners support electronic key exchange, consider using an offline HSM or utilizing a 3rd party [key custodian as a service](terminology.md#terms.kcaas).  
To import your own test keys or to synchronize keys with your existing HSMs, please see the AWS Payment Cryptography sample code on [GitHub](https://github.com/aws-samples/samples-for-payment-cryptography-service/tree/main/key-import-export). 

**Working Key (WK) Exchange**  
We use industry standards ([ANSI X9.24 TR 31-2018](terminology.md#terms.tr31) and X9.143) for exchanging working keys. This requires that you've already exchanged a KEK using TR-34, RSA Wrap, ECDH or similar schemes. This approach meets the PCI PIN requirement to cryptographically bind key material to its type and usage at all times. Working keys include acquirer working keys, issuer working keys, BDK, and IPEK. 

**Topics**
+ [Import keys](keys-import.md)
+ [Export keys](keys-export.md)
+ [Advanced Topics](keyexchange-advanced.md)

# Import keys
<a name="keys-import"></a>

**Important**  
 Examples require the latest version of the AWS CLI V2. Before getting started, make sure that you've upgraded to the [latest version](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html). 

**Contents**
+ [Introduction to importing keys](#keys-import-introduction)
+ [Importing symmetric keys](#keys-import-symmetric)
  + [Import keys using asymmetric techniques (TR-34)](#keys-import-tr34)
  + [Import keys using asymmetric techniques (ECDH)](#keys-import-ecdh)
  + [Import keys using asymmetric techniques (RSA Unwrap)](#keys-import-rsaunwrap)
  + [Import symmetric keys using a pre-established key exchange key (TR-31)](#keys-import-tr31)
+ [Importing asymmetric (RSA, ECC) public keys](#keys-import-asymmetric)
  + [Importing RSA public keys](#keys-import-rsapublickey)
  + [Importing ECC public keys](#keys-import-eccpublickey)

## Introduction to importing keys
<a name="keys-import-introduction"></a>

**Note**  
When importing keys using X9.143, TR-31 or TR-34 key blocks, AWS Payment Cryptography typically retains (but does not utilize) any optional headers. The HM(HMAC hash type) header is used during cryptographic operations. The KP header (KCV of wrapping key) is specific to the import process and is not retained. 

When exchanging keys with a counterparty, it is typically to first exchange a key exchange key (KEK). This key will then be used to protect subsequent keys. Using electronic formats, the KEK may be exchanged use asymmetric techniques such as TR-34, ECDH or RSA wrap. Subsequent keys will be exchanged using a symmetric key exchange such as TR-31. This KEK will be long lived and may only be updated every few years based on policy and its defined crypto period. 

If only one or two keys are being exchanged, you may also chose to use asymmetric techniques to directly exchange that key such as a BDK. AWS Payment Cryptography supports both methods of key exchange.

## Importing symmetric keys
<a name="keys-import-symmetric"></a>

### Import keys using asymmetric techniques (TR-34)
<a name="keys-import-tr34"></a>

![\[AWS Payment Cryptography key encryption key import process\]](http://docs.aws.amazon.com/payment-cryptography/latest/userguide/images/keyimport-process-kek-import.png)


 TR-34 uses RSA asymmetric cryptography to encrypt and sign symmetric keys for exchange. This ensures both confidentiality (encryption) and integrity (signature) of the wrapped key. 

 To import your own keys, check out the AWS Payment Cryptography sample project on [GitHub](https://github.com/aws-samples/samples-for-payment-cryptography-service/tree/main/key-import-export). For instructions on how to import/export keys from other platforms, sample code is available on [GitHub](https://github.com/aws-samples/samples-for-payment-cryptography-service/tree/main/key-import-export) or consult the user guide for those platforms. 

1. 

****Call the Initialize Import command****  
Call `get-parameters-for-import` to initialize the import process. This API generates a key pair for key imports, signs the key, and returns the certificate and certificate root. Encrypt the key to be exported using this key. In TR-34 terminology, this is known as the KRD Cert. These certificates are base64 encoded, short-lived, and intended only for this purpose. Save the `ImportToken` value. 

   ```
   $ aws payment-cryptography get-parameters-for-import \
       --key-material-type TR34_KEY_BLOCK \
       --wrapping-key-algorithm RSA_2048
   ```

   ```
   {
       "ImportToken": "import-token-bwxli6ocftypneu5",
       "ParametersValidUntilTimestamp": 1698245002.065,
       "WrappingKeyCertificateChain": "LS0tLS1CRUdJTiBDRVJUSUZJQ0FURS0....",
       "WrappingKeyCertificate": "LS0tLS1CRUdJTiBDRVJUSUZJQ0FURS0tLS0....",
       "WrappingKeyAlgorithm": "RSA_2048"
   }
   ```

1. 

****Install public certificate on key source system****  
With most HSMs, you need to install, load, or trust the public certificate generated in step 1 to export keys using it. This could include the entire certificate chain or just the root certificate from step 1, depending on the HSM. 

1. 

****Generate key pair on source system and provide certificate chain to AWS Payment Cryptography****  
To ensure integrity of the transmitted payload, the sending party (Key Distribution Host or KDH) signs it. Generate a public key for this purpose and create a public key certificate (X509) to provide back to AWS Payment Cryptography. 

    When transferring keys from an HSM, create a key pair on that HSM. The HSM, a third party, or a service such as AWS Private CA can generate the certificate. 

   Load the root certificate to AWS Payment Cryptography using the `importKey` command with KeyMaterialType of `RootCertificatePublicKey` and KeyUsageType of `TR31_S0_ASYMMETRIC_KEY_FOR_DIGITAL_SIGNATURE`. 

   For intermediate certificates, use the `importKey` command with KeyMaterialType of `TrustedCertificatePublicKey` and KeyUsageType of `TR31_S0_ASYMMETRIC_KEY_FOR_DIGITAL_SIGNATURE`. Repeat this process for multiple intermediate certificates. Use the `KeyArn` of the last imported certificate in the chain as an input to subsequent import commands. 
**Note**  
Don't import the leaf certificate. Provide it directly during the import command.

1. 

****Export key from source system****  
Many HSMs and related systems support exporting keys using the TR-34 norm. Specify the public key from step 1 as the KRD (encryption) cert and the key from step 3 as the KDH (signing) cert. To import to AWS Payment Cryptography, specify the format as TR-34.2012 non-CMS two pass format, which may also be referred to as the TR-34 Diebold format. 

1. 

****Call Import Key****  
Call the importKey API with a KeyMaterialType of `TR34_KEY_BLOCK`. Use the keyARN of the last CA imported in step 3 for `certificate-authority-public-key-identifier`, the wrapped key material from step 4 for `key-material`, and the leaf certificate from step 3 for `signing-key-certificate`. Include the import-token from step 1. 

   ```
   $ aws payment-cryptography import-key \
       --key-material='{"Tr34KeyBlock": { \
       "CertificateAuthorityPublicKeyIdentifier": "arn:aws:payment-cryptography:us-east-2:111122223333:key/zabouwe3574jysdl", \
       "ImportToken": "import-token-bwxli6ocftypneu5", \
       "KeyBlockFormat": "X9_TR34_2012", \
       "SigningKeyCertificate": "LS0tLS1CRUdJTiBDRVJUSUZJQ0FURS0tLS0tCk1JSUV2RENDQXFTZ0F3SUJ...", \
       "WrappedKeyBlock": "308205A106092A864886F70D010702A08205923082058E020101310D300B0609608648016503040201308203..."} \
       }'
   ```

   ```
   {
     "Key": {
       "CreateTimestamp": "2023-06-13T16:52:52.859000-04:00",
       "Enabled": true,
       "KeyArn": "arn:aws:payment-cryptography:us-east-2:111122223333:key/ov6icy4ryas4zcza",
       "KeyAttributes": {
         "KeyAlgorithm": "TDES_3KEY",
         "KeyClass": "SYMMETRIC_KEY",
         "KeyModesOfUse": {
           "Decrypt": true,
           "DeriveKey": false,
           "Encrypt": true,
           "Generate": false,
           "NoRestrictions": false,
           "Sign": false,
           "Unwrap": true,
           "Verify": false,
           "Wrap": true
         },
         "KeyUsage": "TR31_K1_KEY_ENCRYPTION_KEY"
       },
       "KeyCheckValue": "CB94A2",
       "KeyCheckValueAlgorithm": "ANSI_X9_24",
       "KeyOrigin": "EXTERNAL",
       "KeyState": "CREATE_COMPLETE",
       "UsageStartTimestamp": "2023-06-13T16:52:52.859000-04:00"
     }
   }
   ```

1. 

****Use imported key for cryptographic operations or subsequent import****  
If the imported KeyUsage was TR31\$1K0\$1KEY\$1ENCRYPTION\$1KEY, you can use this key for subsequent key imports using TR-31. For other key types (such as TR31\$1D0\$1SYMMETRIC\$1DATA\$1ENCRYPTION\$1KEY), you can use the key directly for cryptographic operations. 

### Import keys using asymmetric techniques (ECDH)
<a name="keys-import-ecdh"></a>

![\[AWS Payment Cryptography key encryption key import process using ECDH\]](http://docs.aws.amazon.com/payment-cryptography/latest/userguide/images/keyimport-ecdh-import.png)


Elliptic Curve Diffie-Hellman (ECDH) uses ECC asymmetric cryptography to establish a shared key between two parties without requiring pre-exchanged keys. ECDH keys are ephemeral, so AWS Payment Cryptography does not store them. In this process, a one-time [KBPK/KEK](terminology.md#terms.kbpk) is derived using ECDH. That derived key is immediately used to wrap the actual key that you want to transfer, which could be another KBPK, an IPEK key, or other key types. 

When importing, the sending system is commonly known as Party U (Initiator) and AWS Payment Cryptography is known as Party V (Responder). 

**Note**  
 While ECDH can be used to exchange any symmetric key type, it is the only approach that can securely transfer AES-256 keys. 

1. 

****Generate ECC Key Pair****  
Call `create-key` to create an ECC key pair for this process. This API generates a key pair for key imports or exports. At creation, specify what kind of keys can be derived using this ECC key. When using ECDH to exchange (wrap) other keys, use a value of `TR31_K1_KEY_BLOCK_PROTECTION_KEY`.
**Note**  
 Although low-level ECDH generates a derived key that can be used for any purpose, AWS Payment Cryptography limits the accidental reuse of a key for multiple purposes by allowing a key to only be used for a single derived-key type. 

   ```
   $ aws payment-cryptography create-key --exportable --key-attributes KeyAlgorithm=ECC_NIST_P256,KeyUsage=TR31_K3_ASYMMETRIC_KEY_FOR_KEY_AGREEMENT,KeyClass=ASYMMETRIC_KEY_PAIR,KeyModesOfUse='{DeriveKey=true}' --derive-key-usage "TR31_K1_KEY_BLOCK_PROTECTION_KEY"
   ```

   ```
   {
                     "Key": {
                         "KeyArn": "arn:aws:payment-cryptography:us-east-2:111122223333:key/wc3rjsssguhxtilv",
                         "KeyAttributes": {
                             "KeyUsage": "TR31_K3_ASYMMETRIC_KEY_FOR_KEY_AGREEMENT",
                             "KeyClass": "ASYMMETRIC_KEY_PAIR",
                             "KeyAlgorithm": "ECC_NIST_P256",
                             "KeyModesOfUse": {
                                 "Encrypt": false,
                                 "Decrypt": false,
                                 "Wrap": false,
                                 "Unwrap": false,
                                 "Generate": false,
                                 "Sign": false,
                                 "Verify": false,
                                 "DeriveKey": true,
                                 "NoRestrictions": false
                             }
                         },
                         "KeyCheckValue": "2432827F",
                         "KeyCheckValueAlgorithm": "CMAC",
                         "Enabled": true,
                         "Exportable": true,
                         "KeyState": "CREATE_COMPLETE",
                         "KeyOrigin": "AWS_PAYMENT_CRYPTOGRAPHY",
                         "CreateTimestamp": "2025-03-28T22:03:41.087000-07:00",
                         "UsageStartTimestamp": "2025-03-28T22:03:41.068000-07:00"
                     }
                 }
   ```

1. 

****Get Public Key Certificate****  
Call `get-public-key-certificate` to receive the public key as an X.509 certificate signed by your account's CA that is specific to AWS Payment Cryptography in a specific region.  
**Example**  

   ```
   $ aws payment-cryptography get-public-key-certificate \
                    --key-identifier arn:aws:payment-cryptography:us-east-2:111122223333:key/wc3rjsssguhxtilv
   ```

   ```
   {
               "KeyCertificate": "LS0tLS1CRUdJTi...",
               "KeyCertificateChain": "LS0tLS1CRUdJT..."
         }
   ```

1. 

****Install public certificate on counterparty system (Party U)****  
With many HSMs, you need to install, load, or trust the public certificate generated in step 1 to export keys using it. This could include the entire certificate chain or just the root certificate from step 1, depending on the HSM. Consult your HSM documentation for more information.

1. 

****Generate ECC key pair on source system and provide certificate chain to AWS Payment Cryptography****  
In ECDH, each party generates a key pair and agrees on a common key. For AWS Payment Cryptography to derive the key, it needs the counterparty's public key in X.509 public key format.

   When transferring keys from an HSM, create a key pair on that HSM. For HSMs that support key blocks, the key header will look similar to `D0144K3EX00E0000`. When creating the certificate, you generally generate a CSR on the HSM and then the HSM, a third party, or a service such as AWS Private CA can generate the certificate.

   Load the root certificate to AWS Payment Cryptography using the `importKey` command with KeyMaterialType of `RootCertificatePublicKey` and KeyUsageType of `TR31_S0_ASYMMETRIC_KEY_FOR_DIGITAL_SIGNATURE`.

   For intermediate certificates, use the `importKey` command with KeyMaterialType of `TrustedCertificatePublicKey` and KeyUsageType of `TR31_S0_ASYMMETRIC_KEY_FOR_DIGITAL_SIGNATURE`. Repeat this process for multiple intermediate certificates. Use the `KeyArn` of the last imported certificate in the chain as an input to subsequent import commands.
**Note**  
Don't import the leaf certificate. Provide it directly during the import command.

1. 

****Derive one-time key using ECDH on Party U HSM****  
Many HSMs and related systems support establishing keys using ECDH. Specify the public key from step 1 as the public key and the key from step 3 as the private key. For allowable options, such as derivation methods, see the [API guide](https://docs.aws.amazon.com/payment-cryptography/latest/APIReference/API_ImportDiffieHellmanTr31KeyBlock.html). 
**Note**  
 The derivation parameters such as hash type must match exactly on both sides. Otherwise, you will generate a different key. 

1. 

****Export key from source system****  
Finally, export the key you want to transport to AWS Payment Cryptography using standard TR-31 commands. Specify the ECDH derived key as the KBPK. The key to be exported can be any TDES or AES key subject to TR-31 valid combinations, as long as the wrapping key is at least as strong as the key to be exported. 

1. 

****Call Import Key****  
Call the `import-key` API with a KeyMaterialType of `DiffieHellmanTr31KeyBlock`. Use the KeyARN of the last CA imported in step 3 for `certificate-authority-public-key-identifier`, the wrapped key material from step 4 for `key-material`, and the leaf certificate from step 3 for `public-key-certificate`. Include the private key ARN from step 1.

   ```
   $ aws payment-cryptography import-key \
             --key-material='{
               "DiffieHellmanTr31KeyBlock": {
                 "CertificateAuthorityPublicKeyIdentifier": "arn:aws:payment-cryptography:us-east-2:111122223333:key/swseahwtq2oj6zi5",
                 "DerivationData": {
                   "SharedInformation": "1234567890"
                 },
                 "DeriveKeyAlgorithm": "AES_256",
                 "KeyDerivationFunction": "NIST_SP800",
                 "KeyDerivationHashAlgorithm": "SHA_256",
                 "PrivateKeyIdentifier": "arn:aws:payment-cryptography:us-east-2:111122223333:key/wc3rjsssguhxtilv",
                 "PublicKeyCertificate": "LS0tLS1CRUdJTiBDRVJUSUZJQ0FURS0tLS0tCk1JSUN....",
                 "WrappedKeyBlock": "D0112K1TB00E0000D603CCA8ACB71517906600FF8F0F195A38776A7190A0EF0024F088A5342DB98E2735084A7841CB00E16D373A70857E9A"
               }
             }'
   ```

   ```
   {
           "Key": {
             "CreateTimestamp": "2025-03-13T16:52:52.859000-04:00",
             "Enabled": true,
             "KeyArn": "arn:aws:payment-cryptography:us-east-2:111122223333:key/ov6icy4ryas4zcza",
             "KeyAttributes": {
               "KeyAlgorithm": "TDES_3KEY",
               "KeyClass": "SYMMETRIC_KEY",
               "KeyModesOfUse": {
                 "Decrypt": true,
                 "DeriveKey": false,
                 "Encrypt": true,
                 "Generate": false,
                 "NoRestrictions": false,
                 "Sign": false,
                 "Unwrap": true,
                 "Verify": false,
                 "Wrap": true
               },
               "KeyUsage": "TR31_K1_KEY_ENCRYPTION_KEY"
             },
             "KeyCheckValue": "CB94A2",
             "KeyCheckValueAlgorithm": "ANSI_X9_24",
             "KeyOrigin": "EXTERNAL",
             "KeyState": "CREATE_COMPLETE",
             "UsageStartTimestamp": "2025-03-13T16:52:52.859000-04:00"
           }
         }
   ```

1. 

****Use imported key for cryptographic operations or subsequent import****  
If the imported KeyUsage was TR31\$1K0\$1KEY\$1ENCRYPTION\$1KEY, you can use this key for subsequent key imports using TR-31. For other key types (such as TR31\$1D0\$1SYMMETRIC\$1DATA\$1ENCRYPTION\$1KEY), you can use the key directly for cryptographic operations.

### Import keys using asymmetric techniques (RSA Unwrap)
<a name="keys-import-rsaunwrap"></a>

 Overview: AWS Payment Cryptography supports RSA wrap/unwrap for key exchange when TR-34 isn't feasible. Like TR-34, this technique uses RSA asymmetric cryptography to encrypt symmetric keys for exchange. However, unlike TR-34, this method doesn't have the sending party sign the payload. Also, this RSA wrap technique doesn't maintain the integrity of the key metadata during transfer because it doesn't include key blocks. 

**Note**  
 You can use RSA wrap to import or export TDES and AES-128 keys. 

1. 

****Call the Initialize Import command****  
Call **get-parameters-for-import** to initialize the import process with a `KeyMaterialType` of `KEY_CRYPTOGRAM`. Use `RSA_2048` for the `WrappingKeyAlgorithm` when exchanging TDES keys. Use `RSA_3072` or `RSA_4096` when exchanging TDES or AES-128 keys. This API generates a key pair for key imports, signs the key using a certificate root, and returns both the certificate and certificate root. Encrypt the key to be exported using this key. These certificates are short-lived and intended only for this purpose. 

   ```
   $ aws payment-cryptography get-parameters-for-import \
       --key-material-type KEY_CRYPTOGRAM \
       --wrapping-key-algorithm RSA_4096
   ```

   ```
   {
     "ImportToken": "import-token-bwxli6ocftypneu5",
     "ParametersValidUntilTimestamp": 1698245002.065,
     "WrappingKeyCertificateChain": "LS0tLS1CRUdJTiBDRVJUSUZJQ0FURS0....",
     "WrappingKeyCertificate": "LS0tLS1CRUdJTiBDRVJUSUZJQ0FURS0tLS0....",
     "WrappingKeyAlgorithm": "RSA_4096"
   }
   ```

1. 

****Install public certificate on key source system****  
With many HSMs, you need to install, load, or trust the public certificate (and/or its root) generated in step 1 to export keys using it. 

1. 

****Export key from source system****  
Many HSMs and related systems support exporting keys using RSA wrap. Specify the public key from step 1 as the encryption cert (`WrappingKeyCertificate`). If you need the chain of trust, use the `WrappingKeyCertificateChain` from step 1. When exporting the key from your HSM, specify the format as RSA, with Padding Mode = PKCS\$11 v2.2 OAEP (with SHA 256 or SHA 512). 

1. 

****Call **import-key******  
Call the **import-key** API with a `KeyMaterialType` of `KeyMaterial`. You need the `ImportToken` from step 1 and the `key-material` (wrapped key material) from step 3. Provide the key parameters (such as Key Usage) because RSA wrap doesn't use key blocks. 

   ```
   $ cat import-key-cryptogram.json 
   ```

   ```
   {
     "KeyMaterial": {
       "KeyCryptogram": {
         "Exportable": true,
         "ImportToken": "import-token-bwxli6ocftypneu5",
         "KeyAttributes": {
           "KeyAlgorithm": "AES_128",
           "KeyClass": "SYMMETRIC_KEY",
           "KeyModesOfUse": {
             "Decrypt": true,
             "DeriveKey": false,
             "Encrypt": true,
             "Generate": false,
             "NoRestrictions": false,
             "Sign": false,
             "Unwrap": true,
             "Verify": false,
             "Wrap": true
           },
           "KeyUsage": "TR31_K0_KEY_ENCRYPTION_KEY"
         },
         "WrappedKeyCryptogram": "18874746731....",
         "WrappingSpec": "RSA_OAEP_SHA_256"
       }
     }
   }
   ```

   ```
   $ aws payment-cryptography import-key --cli-input-json file://import-key-cryptogram.json
   ```

   ```
   {
     "Key": {
       "KeyOrigin": "EXTERNAL",
       "Exportable": true,
       "KeyCheckValue": "DA1ACF",
       "UsageStartTimestamp": 1697643478.92,
       "Enabled": true,
       "KeyArn": "arn:aws:payment-cryptography:us-east-2:111122223333:key/kwapwa6qaifllw2h",
       "CreateTimestamp": 1697643478.92,
       "KeyState": "CREATE_COMPLETE",
       "KeyAttributes": {
         "KeyAlgorithm": "AES_128",
         "KeyModesOfUse": {
           "Encrypt": true,
           "Unwrap": true,
           "Verify": false,
           "DeriveKey": false,
           "Decrypt": true,
           "NoRestrictions": false,
           "Sign": false,
           "Wrap": true,
           "Generate": false
         },
         "KeyUsage": "TR31_K0_KEY_ENCRYPTION_KEY",
         "KeyClass": "SYMMETRIC_KEY"
       },
       "KeyCheckValueAlgorithm": "CMAC"
     }
   }
   ```

1. 

****Use imported key for cryptographic operations or subsequent import****  
If the imported `KeyUsage` was `TR31_K0_KEY_ENCRYPTION_KEY` or `TR31_K1_KEY_BLOCK_PROTECTION_KEY`, you can use this key for subsequent key imports using TR-31. If the key type was any other type (such as `TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY`), you can use the key directly for cryptographic operations. 

### Import symmetric keys using a pre-established key exchange key (TR-31)
<a name="keys-import-tr31"></a>

![\[AWS Payment Cryptography symmetric key import process\]](http://docs.aws.amazon.com/payment-cryptography/latest/userguide/images/keyimport-process-wk-import.png)


When exchanging multiple keys or supporting key rotation, partners typically first exchange an initial key encryption key (KEK). You can do this using techniques such as paper key components or, for AWS Payment Cryptography, using [TR-34](#keys-import-tr34).

 After establishing a KEK, you can use it to transport subsequent keys (including other KEKs). AWS Payment Cryptography supports this key exchange using ANSI TR-31, which is widely used and supported by HSM vendors. 

1. 

****Import Key Encryption Key (KEK)****  
Make sure you've already imported your KEK and have the keyARN (or keyAlias) available.

1. 

****Create key on source platform****  
If the key doesn't exist, create it on the source platform. Alternatively, you can create the key on AWS Payment Cryptography and use the **export** command. 

1. 

****Export key from source platform****  
When exporting, specify the export format as TR-31. The source platform will ask for the key to export and the key encryption key to use. 

1. 

****Import into AWS Payment Cryptography****  
When calling the **import-key** command, use the keyARN (or alias) of your key encryption key for `WrappingKeyIdentifier`. Use the output from the source platform for `WrappedKeyBlock`.   
**Example**  

   ```
   $ aws payment-cryptography import-key \
       --key-material='{"Tr31KeyBlock": { \
       "WrappingKeyIdentifier": "arn:aws:payment-cryptography:us-east-2:111122223333:key/ov6icy4ryas4zcza", \
       "WrappedKeyBlock": "D0112B0AX00E00002E0A3D58252CB67564853373D1EBCC1E23B2ADE7B15E967CC27B85D5999EF58E11662991FF5EB1381E987D744334B99D"} \
       }'
   ```

   ```
   {
     "Key": {
       "KeyArn": "arn:aws:payment-cryptography:us-east-2:111122223333:key/kwapwa6qaifllw2h",
       "KeyAttributes": {
         "KeyUsage": "TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY",
         "KeyClass": "SYMMETRIC_KEY",
         "KeyAlgorithm": "AES_128",
         "KeyModesOfUse": {
           "Encrypt": true,
           "Decrypt": true,
           "Wrap": true,
           "Unwrap": true,
           "Generate": false,
           "Sign": false,
           "Verify": false,
           "DeriveKey": false,
           "NoRestrictions": false
         }
       },
       "KeyCheckValue": "0A3674",
       "KeyCheckValueAlgorithm": "CMAC",
       "Enabled": true,
       "Exportable": true,
       "KeyState": "CREATE_COMPLETE",
       "KeyOrigin": "EXTERNAL",
       "CreateTimestamp": "2023-06-02T07:38:14.913000-07:00",
       "UsageStartTimestamp": "2023-06-02T07:38:14.857000-07:00"
     }
   }
   ```

## Importing asymmetric (RSA, ECC) public keys
<a name="keys-import-asymmetric"></a>

All certificates imported must be at least as strong as their issuing(predecessor) certificate in the chain. This means that a RSA\$12048 CA can only be used to protect a RSA\$12048 leaf certificate and an ECC certificate must be protected by another ECC certificate of equivalent strength. An ECC P384 certificate can only be issued by a P384 or P521 CA. All certificates must be unexpired at the time of import. 

### Importing RSA public keys
<a name="keys-import-rsapublickey"></a>

AWS Payment Cryptography supports importing public RSA keys as X.509 certificates. To import a certificate, first import its root certificate. All certificates must be unexpired at the time of import. The certificate should be in PEM format and base64 encoded. 

1. 

****Import Root Certificate into AWS Payment Cryptography****  
Use the following command to import the root certificate:  
**Example**  

   ```
   $ aws payment-cryptography import-key \
       --key-material='{"RootCertificatePublicKey": { \
       "KeyAttributes": { \
       "KeyAlgorithm": "RSA_2048", \
       "KeyClass": "PUBLIC_KEY", \
       "KeyModesOfUse": { \
       "Verify": true}, \
       "KeyUsage": "TR31_S0_ASYMMETRIC_KEY_FOR_DIGITAL_SIGNATURE"}, \
       "PublicKeyCertificate": "LS0tLS1CRUdJTiBDRVJUSUZJQ0FURS0tLS0tCk1JSURKVENDQWcyZ0F3SUJBZ0lCWkRBTkJna3Foa2lHOXcwQkFR..."} \
       }'
   ```

   ```
   {
     "Key": {
       "CreateTimestamp": "2023-08-08T18:52:01.023000+00:00",
       "Enabled": true,
       "KeyArn": "arn:aws:payment-cryptography:us-east-2:111122223333:key/zabouwe3574jysdl",
       "KeyAttributes": {
         "KeyAlgorithm": "RSA_2048",
         "KeyClass": "PUBLIC_KEY",
         "KeyModesOfUse": {
           "Decrypt": false,
           "DeriveKey": false,
           "Encrypt": false,
           "Generate": false,
           "NoRestrictions": false,
           "Sign": false,
           "Unwrap": false,
           "Verify": true,
           "Wrap": false
         },
         "KeyUsage": "TR31_S0_ASYMMETRIC_KEY_FOR_DIGITAL_SIGNATURE"
       },
       "KeyOrigin": "EXTERNAL",
       "KeyState": "CREATE_COMPLETE",
       "UsageStartTimestamp": "2023-08-08T18:52:01.023000+00:00"
     }
   }
   ```

1. 

****Import Public Key Certificate into AWS Payment Cryptography****  
You can now import a public key. As TR-34 and ECDH rely on passing the leaf certificate at run-time, this option is only used when encrypting data using a public key from another system. KeyUsage will be set to TR31\$1D1\$1ASYMMETRIC\$1KEY\$1FOR\$1DATA\$1ENCRYPTION.  
**Example**  

   ```
   $ aws payment-cryptography import-key \
       --key-material='{"Tr31KeyBlock": { \
       "WrappingKeyIdentifier": "arn:aws:payment-cryptography:us-east-2:111122223333:key/ov6icy4ryas4zcza", \
       "WrappedKeyBlock": "D0112B0AX00E00002E0A3D58252CB67564853373D1EBCC1E23B2ADE7B15E967CC27B85D5999EF58E11662991FF5EB1381E987D744334B99D"} \
       }'
   ```

   ```
   {
     "Key": {
       "CreateTimestamp": "2023-08-08T18:55:46.815000+00:00",
       "Enabled": true,
       "KeyArn": "arn:aws:payment-cryptography:us-east-2:111122223333:key/4kd6xud22e64wcbk",
       "KeyAttributes": {
         "KeyAlgorithm": "RSA_4096",
         "KeyClass": "PUBLIC_KEY",
         "KeyModesOfUse": {
           "Decrypt": false,
           "DeriveKey": false,
           "Encrypt": false,
           "Generate": false,
           "NoRestrictions": false,
           "Sign": false,
           "Unwrap": false,
           "Verify": true,
           "Wrap": false
         },
         "KeyUsage": "TR31_S0_ASYMMETRIC_KEY_FOR_DIGITAL_SIGNATURE"
       },
       "KeyOrigin": "EXTERNAL",
       "KeyState": "CREATE_COMPLETE",
       "UsageStartTimestamp": "2023-08-08T18:55:46.815000+00:00"
     }
   }
   ```

### Importing ECC public keys
<a name="keys-import-eccpublickey"></a>

AWS Payment Cryptography supports importing public ECC keys as X.509 certificates. To import a certificate, first import its root CA certificate and any intermediate certificates. All certificates must be unexpired at the time of import. The certificate should be in PEM format and base64 encoded.

1. 

****Import ECC Root Certificate into AWS Payment Cryptography****  
Use the following command to import the root certificate:  
**Example**  

   ```
   $ aws payment-cryptography import-key \
       --key-material='{"RootCertificatePublicKey": { \
       "KeyAttributes": { \
       "KeyAlgorithm": "ECC_NIST_P521", \
       "KeyClass": "PUBLIC_KEY", \
       "KeyModesOfUse": { \
       "Verify": true}, \
       "KeyUsage": "TR31_S0_ASYMMETRIC_KEY_FOR_DIGITAL_SIGNATURE"}, \
       "PublicKeyCertificate": "LS0tLS1CRUdJTiBDRVJUSUZJQ0FURS0tLS0tCk1JSUNQekNDQWFDZ0F3SUJBZ0lDSjNVd0NnWUlLb1pJemowRUF3UXdNakVlTUJ3R0ExVUVDd3dWVTJWc1psTnAKWjI1bFpFTmxjblJwWm1sallYUmxNUkF3RGdZRFZRUUREQWRMUkVnZ1EwRXhNQjRYRFRJMU1ETXlPREF3TURBdwpNRm9YRFRJMk1ETXlPREF3TURBd01Gb3dNakVlTUJ3R0ExVUVDd3dWVTJWc1psTnBaMjVsWkVObGNuUnBabWxqCllYUmxNUkF3RGdZRFZRUUREQWRMUkVnZ1EwRXhNSUdiTUJBR0J5cUdTTTQ5QWdFR0JTdUJCQUFqQTRHR0FBUUEKRDVEUXc5RW1Tb1lJVkRnbUpmRm1wL1pzMXp1M0ZobThrdUdkYlA4NWgwNTdydkhHZ3VISW03V3N1aTlpdXNvNApFWEZnV3ZUdy85amhZcVJrMi9yY1RHb0JrS2NpV3Q2UHMxVmpSUVZhVEZmbmxPdjRNTURQUEFEUWthVU45cVNNCkF5MTF0RklKNlFGWDR0aGx3RzBaZkFwd0NMV1ZyMzFrRU45RDJhVUh6Mjg5WlM2all6QmhNQjhHQTFVZEl3UVkKTUJhQUZFMjhnay9QZnZ3NklsNm9yQzNwRmJtK280emxNQjBHQTFVZERnUVdCQlJOdklKUHozNzhPaUplcUt3dAo2Ulc1dnFPTTVUQVBCZ05WSFJNQkFmOEVCVEFEQVFIL01BNEdBMVVkRHdFQi93UUVBd0lDeERBS0JnZ3Foa2pPClBRUURCQU9CakFBd2dZZ0NRZ0ZRRit5VUVSYTZoQ0RwSDVHeVhlaVFYYU0wc25Fd3o2TmlmOHlSTlF1dzJ5MUoKdTNoKzZYa2N6Y3lVT01NSzhaRnhBVDhFOERMVUtpdjM1VmdzSkFDN09RSkNBSWMzdEVNV01tZTVCV3ZXTFVxSQpnV3h5U3UxWDdRSTJrR2dUK1FqRGlhQ2E4b091NVlJTmZscW4reUswR29yNGJzMTBZaUh4SHhpV2t0UVRSdVp4CkhIU3UKLS0tLS1FTkQgQ0VSVElGSUNBVEUtLS0tLQo="} \
       }'
   ```

   ```
   {
     "Key": {
       "CreateTimestamp": "2023-08-08T18:52:01.023000+00:00",
       "Enabled": true,
       "KeyArn": "arn:aws:payment-cryptography:us-east-2:111122223333:key/wv4gb6h3xcqjk6sm",
       "KeyAttributes": {
         "KeyAlgorithm": "ECC_NIST_P521",
         "KeyClass": "PUBLIC_KEY",
         "KeyModesOfUse": {
           "Decrypt": false,
           "DeriveKey": false,
           "Encrypt": false,
           "Generate": false,
           "NoRestrictions": false,
           "Sign": false,
           "Unwrap": false,
           "Verify": true,
           "Wrap": false
         },
         "KeyUsage": "TR31_S0_ASYMMETRIC_KEY_FOR_DIGITAL_SIGNATURE"
       },
       "KeyOrigin": "EXTERNAL",
       "KeyState": "CREATE_COMPLETE",
       "UsageStartTimestamp": "2025-03-08T18:52:01.023000+00:00"
     }
   }
   ```

1. 

****Import Intermediate Certificate into AWS Payment Cryptography****  
Use the following command to import an intermediate certificate:  
**Example**  

   ```
   $ aws payment-cryptography import-key \
                   --key-material='{"TrustedCertificatePublicKey": { \
                   --certificate-authority-public-key-identifier='"arn:aws:payment-cryptography:us-east-2:111122223333:key/wv4gb6h3xcqjk6sm"  \
       "KeyAttributes": { \
       "KeyAlgorithm": "ECC_NIST_P521", \
       "KeyClass": "PUBLIC_KEY", \
       "KeyModesOfUse": { \
       "Verify": true}, \
       "KeyUsage": "TR31_S0_ASYMMETRIC_KEY_FOR_DIGITAL_SIGNATURE"}, \
       "PublicKeyCertificate": "LS0tLS1CRUdJTiBDRVJUSUZJQ0FURS0tLS0tCk1JSUNLekNDQVkyZ0F3SUJBZ0lDVDAwd0NnWUlLb1pJemowRUF3UXdNakVlTUJ3R0ExVUVDd3dWVTJWc1psTnAKWjI1bFpFTmxjblJwWm1sallYUmxNUkF3RGdZRFZRUUREQWRMUkVnZ1EwRXhNQjRYRFRJMU1ETXlPREF3TURBdwpNRm9YRFRJMk1ETXlPREF3TURBd01Gb3dNREVlTUJ3R0ExVUVBd3dWUzBSSUlFbHVkR1Z5YldWa2FXRjBaU0JEClFTQXhNUTR3REFZRFZRUUZFd1V4TURJd01UQ0JtekFRQmdjcWhrak9QUUlCQmdVcmdRUUFJd09CaGdBRUFPOGwKZFM4c09YQlNWQlVINWxmRWZkNTZxYVVIenExZVN3VGZKdnI5eEFmb2hRNTNWZ2hLUlZoNzhNR2tJTjVCNTBJTAozbmhaU1JnUnRoS20xNkxwc084NEFGa1Z0ZEpOaEJpYUlQZlRlYXltOHh6OU44KzFWZ3RMTDZBcTBtNkwwMUFwCkUvUmxzUUJ3NWxoakM4VHVOWU1QaUpMYUNPbjJrZVh6SU5SSm01SjJtR3Q1bzFJd1VEQWZCZ05WSFNNRUdEQVcKZ0JSbklBNi9Vc3RMYUpzTzlpYjg1Zm9DWEcwRk96QWRCZ05WSFE0RUZnUVVaeUFPdjFMTFMyaWJEdlltL09YNgpBbHh0QlRzd0RnWURWUjBQQVFIL0JBUURBZ2JBTUFvR0NDcUdTTTQ5QkFNRUE0R0xBRENCaHdKQ0FmTnJjdXBkClpQd3ZqTGdVeFZiN1NtSXNhY2Z6MVZrNWZFYXZHNlVzdU95Y1lGbHlQQTlJZGgyK0lOcW5jSVg4VEo2cDFJRWkKN3RCTHpPb1l0ZWd2Q1dsL0FrRkRzWHFsWkI5bU93WnNEQy9HZEpEcm5uQ0ZkR29hM1NwZytqbGdhOGdQTmxLbAo1dE9IU0lVZnZxcFhEcWYrdXV6SEc1Z3FjdUhnQU8wOUhuMloyNUc4eVE9PQotLS0tLUVORCBDRVJUSUZJQ0FURS0tLS0tCg=="} \
       }'
   ```

   ```
   {
     "Key": {
       "CreateTimestamp": "2025-03-20T18:52:01.023000+00:00",
       "Enabled": true,
       "KeyArn": "arn:aws:payment-cryptography:us-east-2:111122223333:key/swseahwtq2oj6zi5",
       "KeyAttributes": {
         "KeyAlgorithm": "ECC",
         "KeyClass": "PUBLIC_KEY",
         "KeyModesOfUse": {
           "Decrypt": false,
           "DeriveKey": false,
           "Encrypt": false,
           "Generate": false,
           "NoRestrictions": false,
           "Sign": false,
           "Unwrap": false,
           "Verify": true,
           "Wrap": false
         },
         "KeyUsage": "TR31_S0_ASYMMETRIC_KEY_FOR_DIGITAL_SIGNATURE"
       },
       "KeyOrigin": "EXTERNAL",
       "KeyState": "CREATE_COMPLETE",
       "UsageStartTimestamp": "2025-03-25T18:52:01.023000+00:00"
     }
   }
   ```

1. 

****Import Public Key Certificate(Leaf) into AWS Payment Cryptography****  
 Although you can import a leaf ECC certificate, there is currently no defined functions in AWS Payment Cryptography for it besides storage. This is because when using ECDH functions, the leaf certificate is passed at runtime. 

# Export keys
<a name="keys-export"></a>

**Contents**
+ [Export symmetric keys](#keys-export-symmetric)
  + [Export keys using asymmetric techniques (TR-34)](#keys-export-tr34)
  + [Export keys using asymmetric techniques (ECDH)](#keys-export-ecdh)
  + [Export keys using asymmetric techniques (RSA Wrap)](#keys-export-rsawrap)
  + [Export symmetric keys using a pre-established key exchange key (TR-31)](#keys-export-tr31)
+ [Export DUKPT Initial Keys (IPEK/IK)](#keys-export-ipek)
+ [Specify key block headers for export](#keys-export-optionalheaders)
  + [Common Headers](#keys-export-commonheaders)
+ [Export asymmetric (RSA) keys](#keys-export-publickey)

## Export symmetric keys
<a name="keys-export-symmetric"></a>

**Important**  
 Make sure you have the latest version of AWS CLI before you begin. To upgrade, see [Installing the AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html). 

### Export keys using asymmetric techniques (TR-34)
<a name="keys-export-tr34"></a>

TR-34 uses RSA asymmetric cryptography to encrypt and sign symmetric keys for exchange. The encryption protects confidentiality, while the signature ensures integrity. When you export keys, AWS Payment Cryptography acts as the key distribution host (KDH), and your target system becomes the key receiving device (KRD).

**Note**  
If your HSM supports TR-34 export but not TR-34 import, we recommend that you first establish a shared KEK between your HSM and AWS Payment Cryptography using TR-34. You can then use TR-31 to transfer your remaining keys.

1. 

****Initialize the export process****  
Run **get-parameters-for-export** to generate a key pair for key exports. We use this key pair to sign the TR-34 payload. In TR-34 terminology, this is the KDH signing certificate. The certificates are short-lived and valid only for the duration specified in `ParametersValidUntilTimestamp`.
**Note**  
All certificates are in base64 encoding.  
**Example**  

   ```
   $ aws payment-cryptography get-parameters-for-export \
       --signing-key-algorithm RSA_2048 \
       --key-material-type TR34_KEY_BLOCK
   ```

   ```
   {
     "SigningKeyCertificate": "LS0tLS1CRUdJTiBDRVJUSUZJQ0FURS0tLS0tCk1JSUV2RENDQXFTZ0F3SUJ...",
     "SigningKeyCertificateChain": "LS0tLS1CRUdJTiBDRVJUSUZJQ0FURS0tLS....",
     "SigningKeyAlgorithm": "RSA_2048",
     "ExportToken": "export-token-au7pvkbsq4mbup6i",
     "ParametersValidUntilTimestamp": "2023-06-13T15:40:24.036000-07:00"
   }
   ```

1. 

****Import the AWS Payment Cryptography certificate to your receiving system****  
Import the certificate chain from step 1 to your receiving system.

1. 

****Set up your receiving system's certificates****  
To protect the transmitted payload, the sending party (KDH) encrypts it. Your receiving system (typically your HSM or your partner's HSM) needs to generate a public key and create an X.509 public key certificate. You can use AWS Private CA to generate certificates, but you can use any certificate authority.

   After you have the certificate, import the root certificate to AWS Payment Cryptography using the **ImportKey** command. Set `KeyMaterialType` to `RootCertificatePublicKey` and `KeyUsageType` to `TR31_S0_ASYMMETRIC_KEY_FOR_DIGITAL_SIGNATURE`.

   We use `TR31_S0_ASYMMETRIC_KEY_FOR_DIGITAL_SIGNATURE` as the `KeyUsageType` because this is the root key that signs the leaf certificate. You don't need to import leaf certificates into AWS Payment Cryptography—you can pass them inline.
**Note**  
If you previously imported the root certificate, skip this step. For intermediate certificates, use `TrustedCertificatePublicKey`.

1. 

****Export your key****  
Call the **ExportKey** API with `KeyMaterialType` set to `TR34_KEY_BLOCK`. You need to provide:
   + The keyARN of the root CA from step 3 as the `CertificateAuthorityPublicKeyIdentifier`
   + The leaf certificate from step 3 as the `WrappingKeyCertificate`
   + The keyARN (or alias) of the key you want to export as the `--export-key-identifier`
   + The export-token from step 1  
**Example**  

   ```
   $ aws payment-cryptography export-key \
       --export-key-identifier "example-export-key" \
       --key-material '{"Tr34KeyBlock": { \
       "CertificateAuthorityPublicKeyIdentifier": "arn:aws:payment-cryptography:us-east-2:111122223333:key/4kd6xud22e64wcbk", \
       "ExportToken": "export-token-au7pvkbsq4mbup6i", \
       "KeyBlockFormat": "X9_TR34_2012", \
       "WrappingKeyCertificate": "LS0tLS1CRUdJTiBDRVJUSUZJQ0FURS0tLS0tCk1JSUV2RENDQXFXZ0F3SUJBZ0lSQ..."} \
       }'
   ```

   ```
   {
     "WrappedKey": {
       "KeyMaterial": "308205A106092A864886F70D010702A08205923082058...",
       "WrappedKeyMaterialFormat": "TR34_KEY_BLOCK"
     }
   }
   ```

### Export keys using asymmetric techniques (ECDH)
<a name="keys-export-ecdh"></a>

![\[AWS Payment Cryptography key encryption key import process using ECDH\]](http://docs.aws.amazon.com/payment-cryptography/latest/userguide/images/keyimport-ecdh-export.png)


Elliptic Curve Diffie-Hellman (ECDH) uses ECC asymmetric cryptography to establish a shared key between two parties without requiring pre-exchanged keys. ECDH keys are ephemeral, so AWS Payment Cryptography does not store them. In this process, a one-time [KBPK/KEK](terminology.md#terms.kbpk) is derived using ECDH. That derived key is immediately used to wrap the key you want to transfer, which could be another KBPK, a BDK, an IPEK key, or other key types. 

When exporting, AWS Payment Cryptography is referred to as Party U (Initiator) and the receiving system is known as Party V (Responder). 

**Note**  
ECDH can be used to exchange any symmetric key type, but it is the only approach that can be used to transfer AES-256 keys if a KEK is not already established. 

1. 

****Generate ECC Key Pair****  
Call `create-key` to create an ECC key pair for this process. This API generates a key pair for key imports or exports. At creation, specify what kind of keys can be derived using this ECC key. When using ECDH to exchange (wrap) other keys, use a value of `TR31_K1_KEY_BLOCK_PROTECTION_KEY`.
**Note**  
 Although low-level ECDH generates a derived key that can be used for any purpose, AWS Payment Cryptography limits the accidental reuse of a key for multiple purposes by allowing a key to only be used for a single derived-key type. 

   ```
   $ aws payment-cryptography create-key --exportable --key-attributes KeyAlgorithm=ECC_NIST_P256,KeyUsage=TR31_K3_ASYMMETRIC_KEY_FOR_KEY_AGREEMENT,KeyClass=ASYMMETRIC_KEY_PAIR,KeyModesOfUse='{DeriveKey=true}' --derive-key-usage "TR31_K1_KEY_BLOCK_PROTECTION_KEY"
   ```

   ```
   {
           "Key": {
               "KeyArn": "arn:aws:payment-cryptography:us-east-2:111122223333:key/wc3rjsssguhxtilv",
               "KeyAttributes": {
                   "KeyUsage": "TR31_K3_ASYMMETRIC_KEY_FOR_KEY_AGREEMENT",
                   "KeyClass": "ASYMMETRIC_KEY_PAIR",
                   "KeyAlgorithm": "ECC_NIST_P256",
                   "KeyModesOfUse": {
                       "Encrypt": false,
                       "Decrypt": false,
                       "Wrap": false,
                       "Unwrap": false,
                       "Generate": false,
                       "Sign": false,
                       "Verify": false,
                       "DeriveKey": true,
                       "NoRestrictions": false
                   }
               },
               "KeyCheckValue": "2432827F",
               "KeyCheckValueAlgorithm": "CMAC",
               "Enabled": true,
               "Exportable": true,
               "KeyState": "CREATE_COMPLETE",
               "KeyOrigin": "AWS_PAYMENT_CRYPTOGRAPHY",
               "CreateTimestamp": "2025-03-28T22:03:41.087000-07:00",
               "UsageStartTimestamp": "2025-03-28T22:03:41.068000-07:00"
           }
       }
   ```

1. 

****Get Public Key Certificate****  
Call `get-public-key-certificate` to receive the public key as an X.509 certificate signed by your account's CA that is specific to AWS Payment Cryptography in a specific region.  
**Example**  

   ```
   $ aws payment-cryptography get-public-key-certificate \
              --key-identifier arn:aws:payment-cryptography:us-east-2:111122223333:key/wc3rjsssguhxtilv
   ```

   ```
   {
         "KeyCertificate": "LS0tLS1CRUdJTi...",
         "KeyCertificateChain": "LS0tLS1CRUdJT..."
       }
   ```

1. 

****Install public certificate on counterparty system (Party V)****  
With many HSMs, you need to install, load, or trust the public certificate generated in step 1 to establish keys. This could include the entire certificate chain or just the root certificate, depending on the HSM. Consult your HSM documentation for specific instructions.

1. 

****Generate ECC key pair on source system and provide certificate chain to AWS Payment Cryptography****  
In ECDH, each party generates a key pair and agrees on a common key. For AWS Payment Cryptography to derive the key, it needs the counterparty's public key in X.509 public key format.

   When transferring keys from an HSM, create a key pair on that HSM. For HSMs that support key blocks, the key header will look similar to `D0144K3EX00E0000`. When creating the certificate, you generally generate a CSR on the HSM, and then the HSM, a third party, or a service such as AWS Private CA can generate the certificate.

   Load the root certificate to AWS Payment Cryptography using the `importKey` command with KeyMaterialType of `RootCertificatePublicKey` and KeyUsageType of `TR31_S0_ASYMMETRIC_KEY_FOR_DIGITAL_SIGNATURE`.

   For intermediate certificates, use the `importKey` command with KeyMaterialType of `TrustedCertificatePublicKey` and KeyUsageType of `TR31_S0_ASYMMETRIC_KEY_FOR_DIGITAL_SIGNATURE`. Repeat this process for multiple intermediate certificates. Use the `KeyArn` of the last imported certificate in the chain as an input to subsequent export commands.
**Note**  
Don't import the leaf certificate. Provide it directly during the export command.

1. 

****Derive key and export key from AWS Payment Cryptography****  
When exporting, the service derives a key using ECDH and then immediately uses it as the [KBPK](terminology.md#terms.kbpk) to wrap the key to export using TR-31. The key to be exported can be any TDES or AES key subject to TR-31 valid combinations, as long as the wrapping key is at least as strong as the key to be exported. 

   ```
   $ aws payment-cryptography export-key \
               --export-key-identifier arn:aws:payment-cryptography:us-west-2:529027455495:key/e3a65davqhbpjm4h \
               --key-material='{
                 "DiffieHellmanTr31KeyBlock": {
                   "CertificateAuthorityPublicKeyIdentifier": "arn:aws:payment-cryptography:us-east-2:111122223333:key/swseahwtq2oj6zi5",
                   "DerivationData": {
                     "SharedInformation": "ADEF567890"
                   },
                   "DeriveKeyAlgorithm": "AES_256",
                   "KeyDerivationFunction": "NIST_SP800",
                   "KeyDerivationHashAlgorithm": "SHA_256",
                   "PrivateKeyIdentifier": "arn:aws:payment-cryptography:us-east-2:111122223333:key/wc3rjsssguhxtilv",
                   "PublicKeyCertificate": "LS0tLS1CRUdJTiBDRVJUSUZJQ0FUR..."
                 }
               }'
   ```

   ```
   {
               "WrappedKey": {
                   "WrappedKeyMaterialFormat": "TR31_KEY_BLOCK",
                   "KeyMaterial": "D0112K1TB00E00007012724C0FAAF64DA50E2FF4F9A94DF50441143294E0E995DB2171554223EAA56D078C4CFCB1C112B33BBF05597EE700",
                   "KeyCheckValue": "E421AD",
                   "KeyCheckValueAlgorithm": "ANSI_X9_24"
               }
           }
   ```

1. 

****Derive one-time key using ECDH on Party V HSM****  
Many HSMs and related systems support establishing keys using ECDH. Specify the public key from step 1 as the public key and the key from step 3 as the private key. For allowable options, such as derivation methods, see the [API guide](https://docs.aws.amazon.com/payment-cryptography/latest/APIReference/API_ExportDiffieHellmanTr31KeyBlock.html). 
**Note**  
 The derivation parameters such as hash type must match exactly on both sides. Otherwise, you will generate a different key. 

1. 

****Import key to target system****  
Finally, import the key from AWS Payment Cryptography using standard TR-31 commands. Specify the ECDH derived key as the KBPK and use the TR-31 key block that was previously exported from AWS Payment Cryptography. 

### Export keys using asymmetric techniques (RSA Wrap)
<a name="keys-export-rsawrap"></a>

 When TR-34 isn't available, you can use RSA wrap/unwrap for key exchange. Like TR-34, this method uses RSA asymmetric cryptography to encrypt symmetric keys. However, RSA wrap doesn't include: 
+ Payload signing by the sending party
+ Key blocks that maintain key metadata integrity during transport

**Note**  
You can use RSA wrap to export TDES and AES-128 keys.

1. 

****Create an RSA key and certificate on your receiving system****  
Create or identify an RSA key for receiving the wrapped key. We require keys to be in X.509 certificate format. Make sure the certificate is signed by a root certificate that you can import into AWS Payment Cryptography.

1. 

****Import the root public certificate to AWS Payment Cryptography****  
Use **import-key** with the `--key-material` option to import the certificate

   ```
   $ aws payment-cryptography import-key \
       --key-material='{"RootCertificatePublicKey": { \
       "KeyAttributes": { \
       "KeyAlgorithm": "RSA_4096", \
       "KeyClass": "PUBLIC_KEY", \
       "KeyModesOfUse": {"Verify": true}, \
       "KeyUsage": "TR31_S0_ASYMMETRIC_KEY_FOR_DIGITAL_SIGNATURE"}, \
       "PublicKeyCertificate": "LS0tLS1CRUdJTiBDRV..."} \
       }'
   ```

   ```
   {
     "Key": {
       "CreateTimestamp": "2023-09-14T10:50:32.365000-07:00",
       "Enabled": true,
       "KeyArn": "arn:aws:payment-cryptography:us-east-2:111122223333:key/nsq2i3mbg6sn775f",
       "KeyAttributes": {
         "KeyAlgorithm": "RSA_4096",
         "KeyClass": "PUBLIC_KEY",
         "KeyModesOfUse": {
           "Decrypt": false,
           "DeriveKey": false,
           "Encrypt": false,
           "Generate": false,
           "NoRestrictions": false,
           "Sign": false,
           "Unwrap": false,
           "Verify": true,
           "Wrap": false
         },
         "KeyUsage": "TR31_S0_ASYMMETRIC_KEY_FOR_DIGITAL_SIGNATURE"
       },
       "KeyOrigin": "EXTERNAL",
       "KeyState": "CREATE_COMPLETE",
       "UsageStartTimestamp": "2023-09-14T10:50:32.365000-07:00"
     }
   }
   ```

1. 

****Export your key****  
Tell AWS Payment Cryptography to export your key using your leaf certificate. You need to specify: 
   + The ARN for the root certificate you imported in step 2
   + The leaf certificate for export
   + The symmetric key to export

   The output is a hex-encoded binary wrapped (encrypted) version of your symmetric key.  
**Example – Exporting a key**  

   ```
   $ cat export-key.json
   ```

   ```
   {
     "ExportKeyIdentifier": "arn:aws:payment-cryptography:us-east-2:111122223333:key/tqv5yij6wtxx64pi",
     "KeyMaterial": {
       "KeyCryptogram": {
         "CertificateAuthorityPublicKeyIdentifier": "arn:aws:payment-cryptography:us-east-2:111122223333:key/zabouwe3574jysdl",
         "WrappingKeyCertificate": "LS0tLS1CRUdJTiBDEXAMPLE...",
         "WrappingSpec": "RSA_OAEP_SHA_256"
       }
     }
   }
   ```

   ```
   $ aws payment-cryptography export-key \
       --cli-input-json file://export-key.json
   ```

   ```
   {
     "WrappedKey": {
       "KeyMaterial": "18874746731E9E1C4562E4116D1C2477063FCB08454D757D81854AEAEE0A52B1F9D303FA29C02DC82AE7785353816EFAC8B5F4F79CC29A1DDA80C65F34364373D8C74E5EC67E4CB55DEA7F091210DCACD3C46FE4A5DAA0F0D9CAA7C959CA7144A5E7052F34AAED93EF44C004AE7ABEBD616C955BBA10993C06FB905319F87B9B4E1B7A7C7D17AF15B6154E807B9C574387A43197C31C6E565554437A252EFF8AC81613305760D11F9B53B08A1BA79EC7E7C82C48083C4E2D0B6F86C34AB83647BDD7E85240AD1AF3C0F6CA8C5BF323BB2D3896457C554F978F4C9436513F494130A6FADBC038D51898AAD72E02A89FF256C524E7B5D85B813751B718C4933D9DC6031F2C5B2E13351A54B6021B2DB72AA0C7EA54727FBCD557E67E5E7CC2E165576E39DB4DA33510BA9A3C847313103A18EF3B23A3440471864D58C79C569D5CD2A653AC16043CA9A61E6878F74C18EE15F9AB23754C37A945B68C0437C19F0079F74B573D9B59DAC25A20781DBE8075C947C9EDC76177A1B0794288CBF89567A541E8401C74E85B8E1C3E501860AF702F641CAA04327018A84EF3A82932A2BCF37047AB40FE77E0A6F68D0904C7E60983CD6F871D5E0E27EEF425C97D39E9394E8927EEF5D2EA9388DF3C5C241F99378DF5DADE8D0F0CF453C803BA38BA702B9651685FAFA6DCB4B14333F8D3C57F2D93E0852AA94EEC3AF3217CAE5873EFD9",
       "WrappedKeyMaterialFormat": "KEY_CRYPTOGRAM"
     }
   }
   ```

1. 

****Import the key to your receiving system****  
Many HSMs and related systems support importing keys using RSA unwrap (including AWS Payment Cryptography). When importing, specify:
   + The public key from step 1 as the encryption certificate
   + The format as RSA
   + Padding Mode as PKCS\$11 v2.2 OAEP (with SHA 256)
**Note**  
We output the wrapped key in hexBinary format. You might need to convert the format if your system requires a different binary representation, such as base64.

### Export symmetric keys using a pre-established key exchange key (TR-31)
<a name="keys-export-tr31"></a>

When exchanging multiple keys or supporting key rotation, you typically first exchange an initial key encryption key (KEK) using paper key components or, with AWS Payment Cryptography, using [TR-34](#keys-export-tr34). After establishing a KEK, you can use it to transport subsequent keys, including other KEKs. We support this key exchange using ANSI TR-31, which is widely supported by HSM vendors.

1. 

****Set up your Key Encryption Key (KEK)****  
Make sure you have already exchanged your KEK and have the keyARN (or keyAlias) available.

1. 

****Create your key on AWS Payment Cryptography****  
Create your key if it doesn't already exist. Alternatively, you can create the key on your other system and use the [import](#keys-export-tr31) command.

1. 

****Export your key from AWS Payment Cryptography****  
When exporting in TR-31 format, specify the key you want to export and the wrapping key to use.  
**Example – Exporting a key using TR31 key block**  

   ```
   $ aws payment-cryptography export-key \
       --key-material='{"Tr31KeyBlock": \
       { "WrappingKeyIdentifier": "arn:aws:payment-cryptography:us-east-2:111122223333:key/ov6icy4ryas4zcza" }}' \
       --export-key-identifier arn:aws:payment-cryptography:us-east-2:111122223333:key/5rplquuwozodpwsp
   ```

   ```
   {
     "WrappedKey": {
       "KeyCheckValue": "73C263",
       "KeyCheckValueAlgorithm": "ANSI_X9_24",
       "KeyMaterial": "D0144K0AB00E0000A24D3ACF3005F30A6E31D533E07F2E1B17A2A003B338B1E79E5B3AD4FBF7850FACF9A3784489581A543C84816C8D3542AE888CE6D4EDDFD09C39957B131617BC",
       "WrappedKeyMaterialFormat": "TR31_KEY_BLOCK"
     }
   }
   ```

1. 

****Import the key to your system****  
Use your system's import key implementation to import the key.

## Export DUKPT Initial Keys (IPEK/IK)
<a name="keys-export-ipek"></a>

When using [DUKPT](terminology.md#terms.dukpt), you can generate a single Base Derivation Key (BDK) for a fleet of terminals. The terminals don't have direct access to the BDK. Instead, each terminal receives a unique initial terminal key, known as IPEK or Initial Key (IK). Each IPEK is derived from the BDK using a unique Key Serial Number (KSN).

The KSN structure varies by encryption type:
+ For TDES: The 10-byte KSN includes:
  + 24 bits for the Key Set ID
  + 19 bits for the terminal ID
  + 21 bits for the transaction counter
+ For AES: The 12-byte KSN includes:
  + 32 bits for the BDK ID
  + 32 bits for the derivation identifier (ID)
  + 32 bits for the transaction counter

We provide a mechanism to generate and export these initial keys. You can export the generated keys using TR-31, TR-34, or RSA wrap methods. Note that IPEK keys are not persisted and can't be used for subsequent operations on AWS Payment Cryptography.

We don't enforce the split between the first two parts of the KSN. If you want to store the derivation identifier with the BDK, you can use AWS tags.

**Note**  
The counter portion of the KSN (32 bits for AES DUKPT) isn't used for IPEK/IK derivation. For example, inputs of 12345678901234560001 and 12345678901234569999 will generate the same IPEK.

```
$ aws payment-cryptography export-key \
    --key-material='{"Tr31KeyBlock": { \
    "WrappingKeyIdentifier": "arn:aws:payment-cryptography:us-east-2:111122223333:key/ov6icy4ryas4zcza"}} ' \
    --export-key-identifier arn:aws:payment-cryptography:us-east-2:111122223333:key/tqv5yij6wtxx64pi \
    --export-attributes 'ExportDukptInitialKey={KeySerialNumber=12345678901234560001}'
```

```
{
"WrappedKey": {
    "KeyCheckValue": "73C263",
    "KeyCheckValueAlgorithm": "ANSI_X9_24",
    "KeyMaterial": "B0096B1TX00S000038A8A06588B9011F0D5EEF1CCAECFA6962647A89195B7A98BDA65DDE7C57FEA507559AF2A5D601D1",
    "WrappedKeyMaterialFormat": "TR31_KEY_BLOCK"
}
}
```

## Specify key block headers for export
<a name="keys-export-optionalheaders"></a>

You can modify or append key block information when exporting in ASC TR-31 or TR-34 formats. The following table describes the TR-31 key block format and which elements you can modify during export.


| Key Block Attribute | Purpose | Can you modify during export? | Notes | 
| --- | --- | --- | --- | 
| Version ID |  Defines the method used to protect the key material. The standard includes:  [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/payment-cryptography/latest/userguide/keys-export.html)  | No |  We use version B for TDES wrapping keys and version D for AES wrapping keys. We support versions A and C only for import operations.  | 
| Key Block Length | Specifies the length of the remaining message | No |  We calculate this value automatically. The length might appear incorrect before decrypting the payload because we may add key padding as required by the specification.  | 
| Key Usage |  Defines the permitted purposes for the key, such as:  [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/payment-cryptography/latest/userguide/keys-export.html)  | No |  | 
| Algorithm |  Specifies the algorithm of the underlying key. We support: [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/payment-cryptography/latest/userguide/keys-export.html)  | No | We export this value as-is. | 
| Key Usage |  Defines allowed operations, such as:  [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/payment-cryptography/latest/userguide/keys-export.html)  | Yes\$1 |  | 
| Key Version | Indicates the version number for key replacement/rotation. Defaults to 00 if not specified. | Yes - Can append |  | 
| Key Exportability |  Controls whether the key can be exported:  [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/payment-cryptography/latest/userguide/keys-export.html)  | Yes\$1 |  | 
| Optional Key Blocks | Yes - Can append |  Optional key blocks are name/value pairs cryptographically bound to the key. For example, KeySetID for DUKPT keys. We automatically calculate the number of blocks, length of each block, and padding block (PB) based on your name/value pair input.  |  | 

*\$1When modifying values, your new value must be more restrictive than the current value in AWS Payment Cryptography.* For example: 
+ If the current key mode of use is Generate=True,Verify=True, you can change it to Generate=True,Verify=False
+ If the key is already set to not exportable, you can't change it to exportable

When you export keys, we automatically apply the current values from the key being exported. However, you might want to modify or append those values before sending to the receiving system. Here are some common scenarios: 
+ When exporting a key to a payment terminal, set its exportability to `Not Exportable` because terminals typically only import keys and shouldn't export them.
+ When you need to pass associated key metadata to the receiving system, use TR-31 optional headers to cryptographically bind the metadata to the key instead of creating a custom payload.
+ Set the Key Version using the `KeyVersion` field to track key rotation.

TR-31/X9.143 defines common headers, but you can use other headers as long as they meet AWS Payment Cryptography parameters and your receiving system can accept them. For more information about key block headers during export, see [Key Block Headers](https://docs.aws.amazon.com/payment-cryptography/latest/DataAPIReference/API_KeyBlockHeaders.html) in the API Guide.

Here's an example of exporting a BDK key (for instance, to a KIF) with these specifications: 
+ Key version: 02
+ KeyExportability: NON\$1EXPORTABLE
+ KeySetID: 00ABCDEFAB (00 indicates TDES key, ABCDEFABCD is the initial key)

 Because we don't specify key modes of use, this key inherits the mode of use from arn:aws:payment-cryptography:us-east-2:111122223333:key/5rplquuwozodpwsp (DeriveKey = true).

**Note**  
Even when you set exportability to Not Exportable in this example, the [KIF](terminology.md#terms.kif) can still:   
Derive keys such as [IPEK/IK](terminology.md#terms.ipek) used in DUKPT
Export these derived keys to install on devices
This is specifically allowed by the standards.

```
$ aws payment-cryptography export-key \
    --key-material='{"Tr31KeyBlock": { \
    "WrappingKeyIdentifier": "arn:aws:payment-cryptography:us-east-2:111122223333:key/ov6icy4ryas4zcza", \
    "KeyBlockHeaders": { \
    "KeyModesOfUse": { \
    "Derive": true}, \
    "KeyExportability": "NON_EXPORTABLE", \
    "KeyVersion": "02", \
    "OptionalBlocks": { \
    "BI": "00ABCDEFABCD"}}} \
    }' \
    --export-key-identifier arn:aws:payment-cryptography:us-east-2:111122223333:key/5rplquuwozodpwsp
```

```
{
"WrappedKey": {
    "WrappedKeyMaterialFormat": "TR31_KEY_BLOCK",
    "KeyMaterial": "EXAMPLE_KEY_MATERIAL_TR31",
    "KeyCheckValue": "A4C9B3",
    "KeyCheckValueAlgorithm": "ANSI_X9_24"
    }
}
```

### Common Headers
<a name="keys-export-commonheaders"></a>

X9.143 defines certain headers for common use cases. With the exception of the HM(HMAC Hash) header, AWS Payment Cryptography does not parse or utilize these headers.


| Header Name | Purpose | Typical Validation | Notes | 
| --- | --- | --- | --- | 
| BI | Base Derivation Key Identifier for DUKPT | 2 hex characters (00 for TDES, 11 for AES) then 10 hex characters for TDES KSI or 8 hex characters for BDK ID (AES DUKPT). | Contains the (BDK ID, for AES DUKPT) or the Key Set Identifier (KSI, for TDES DUKPT). Can be used when exchanging the BDK ID or the KSI, but do not need to exchange the other data contained in the IK and KS blocks. Typically BI is used when transmitting to a KIF whereas IK or KS are used when injecting into the terminal itself. | 
| HM | Specifies the hash type for HMAC operations |  [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/payment-cryptography/latest/userguide/keys-export.html)  | The service automatically populates this field on export and will parse it on import. Hash types not supported by the service such as SHAKE128 can be imported but may not be usuable for cryptographic functions. | 
| IK |  Initial Key Serial Number for AES DUKPT | 16 hex characters  | This value is used to instantiate the use of the Initial DUKPT key on the receiving device and it identifies the Initial Key derived from a BDK. This field typically contains the derivation data but no counter. Use KS for TDES DUKPT. | 
| KS |  Initial Key Serial Number for TDES DUKPT | 20 hex characters  | This value is used to instantiate the use of the Initial DUKPT key on the receiving device and it identifies the Initial Key derived from a BDK. This field typically contains the derivation data \$1 a zeroized counter value. Use IK for AES DUKPT. | 
| KP | [KCV](terminology.md#terms.kcv) of the wrapping key | 2 hex characters represent the KCV method (00 for X9.24 method and 01 for CMAC method). Followed by KCV value which is typically 6 hex characters. For example 010FA329 represents KCV of 0FA329 calculated using 01(CMAC) method.   | This value is used to instantiate the use of the Initial DUKPT key on the receiving device and it identifies the Initial Key derived from a BDK. This field typically contains the derivation data \$1 a zeroized counter value. Use IK for AES DUKPT. | 
| PB | Padding block | random printable ASCII characters  | The service automatically populates this field on export to ensure optional headers are multiples of encryption block length | 

## Export asymmetric (RSA) keys
<a name="keys-export-publickey"></a>

To export a public key in certificate form, use the **get-public-key-certificate** command. This command returns: 
+ The certificate
+ The root certificate

Both certificates are in base64 encoding.

**Note**  
This operation is not idempotent—subsequent calls might generate different certificates even when using the same underlying key.

**Example**  

```
$ aws payment-cryptography get-public-key-certificate \
     --key-identifier arn:aws:payment-cryptography:us-east-2:111122223333:key/5dza7xqd6soanjtb
```

```
{
"KeyCertificate": "LS0tLS1CRUdJTi...",
"KeyCertificateChain": "LS0tLS1CRUdJT..."
}
```

# Advanced Topics
<a name="keyexchange-advanced"></a>

This section covers advanced key exchange scenarios and configurations.

**Topics**
+ [Bring Your Own Certificate Authority (BYOCA)](keyexchange-byoca.md)

# Bring Your Own Certificate Authority (BYOCA)
<a name="keyexchange-byoca"></a>

By default, when a public key certificate is needed for asymmetric(RSA,ECC) keys created within the service, these certificates are issued by a AWS Payment Cryptography and account-unique certificate authority(CA). This is intended to make it simple to use X.509 without the burden of identifying or setting up a CA or managing Certificate Signing Requests(CSR).

AWS Payment Cryptography also provides the ability to use your own CA when it is required for policy or compliance reasons.

## Overview
<a name="keyexchange-byoca.overview"></a>

The BYOCA feature allows you to use your own Certificate Authority anywhere that certificates are used, including TR-34 import/export, RSA Unwrap, and ECDH-based key transfers. This is useful when you need to maintain a consistent certificate chain across your organization or when working with partners who require specific CA certificates. The following example demonstrates the BYOCA workflow using TR-34 key export.

The three key differences compared to the standard TR-34 export flow are:

1. The signing RSA key is explicitly created using [CreateKey](https://docs.aws.amazon.com/payment-cryptography/latest/APIReference/API_CreateKey.html). Previously, it was implicitly created via [GetParametersForExport](https://docs.aws.amazon.com/payment-cryptography/latest/DataAPIReference/API_GetParametersForExport.html).

1. A new API [GetCertificateSigningRequest](https://docs.aws.amazon.com/payment-cryptography/latest/DataAPIReference/API_GetCertificateSigningRequest.html) creates a Certificate Signing Request (CSR) that can be signed by your external CA.

1. The [ExportKey](https://docs.aws.amazon.com/payment-cryptography/latest/DataAPIReference/API_ExportKey.html) API is extended to allow a certificate to be provided at runtime. Previously, this was implicitly provided by `import-token`, which becomes an optional field.

**Important Considerations**  
These examples use RSA-2048 keys and wrap a TDES-2KEY key. When exporting AES-128, make sure that all keys are RSA-3072 or RSA-4096.
The most common error is that the key represented by `SigningKeyIdentifier` and `SigningKeyCertificate` do not match.

## BYOCA Workflow
<a name="keyexchange-byoca.workflow"></a>

The following steps demonstrate the complete BYOCA workflow for TR-34 export.

**Topics**
+ [Step 1: Create RSA Key](#keyexchange-byoca.create-rsa)
+ [Step 2: Generate Certificate Signing Request](#keyexchange-byoca.generate-csr)
+ [Step 3: Review CSR (Optional)](#keyexchange-byoca.review-csr)
+ [Step 4: Sign the CSR with a Certificate Authority](#keyexchange-byoca.sign-csr)
+ [Step 5: Import CA Certificate](#keyexchange-byoca.import-ca)
+ [Step 6: Get KRD Encryption Certificate](#keyexchange-byoca.get-krd)
+ [Step 7: Export Key with BYOCA](#keyexchange-byoca.export-key)

### Step 1: Create RSA Key
<a name="keyexchange-byoca.create-rsa"></a>

First, create an RSA Key Pair that will ultimately be the KDH Signing Certificate. You can add tags to identify the key's purpose.

**Example Create RSA Key for Signing**  

```
$ aws payment-cryptography create-key --exportable \
    --key-attributes KeyAlgorithm=RSA_2048,KeyUsage=TR31_S0_ASYMMETRIC_KEY_FOR_DIGITAL_SIGNATURE,KeyClass=ASYMMETRIC_KEY_PAIR,KeyModesOfUse='{Sign=True}'
```

```
{
    "Key": {
        "KeyArn": "arn:aws:payment-cryptography:us-east-1:111122223333:key/xgmq6fs6uow736uc",
        "KeyAttributes": {
            "KeyUsage": "TR31_S0_ASYMMETRIC_KEY_FOR_DIGITAL_SIGNATURE",
            "KeyClass": "ASYMMETRIC_KEY_PAIR",
            "KeyAlgorithm": "RSA_2048",
            "KeyModesOfUse": {
                "Sign": true
            }
        },
        "KeyCheckValue": "41E3723C",
        "KeyCheckValueAlgorithm": "SHA_1",
        "Enabled": true,
        "Exportable": true,
        "KeyState": "CREATE_COMPLETE",
        "KeyOrigin": "AWS_PAYMENT_CRYPTOGRAPHY"
    }
}
```

Take note of the `KeyArn` as you'll need it in the next step.

### Step 2: Generate Certificate Signing Request
<a name="keyexchange-byoca.generate-csr"></a>

Generate a Certificate Signing Request (CSR) to be signed by your external CA using the [GetCertificateSigningRequest](https://docs.aws.amazon.com/payment-cryptography/latest/DataAPIReference/API_GetCertificateSigningRequest.html) API. The output is a base64-encoded PEM file. If you base64 decode the contents and save them, you will have a valid CSR in PEM format.

**Example Generate CSR**  

```
$ aws payment-cryptography-data get-certificate-signing-request \
    --key-identifier arn:aws:payment-cryptography:us-east-1:111122223333:key/xgmq6fs6uow736uc \
    --signing-algorithm SHA512 \
    --certificate-subject '{
        "CommonName": "MyCertificateAWSUSEAST",
        "Organization": "Amazon",
        "OrganizationUnit": "PaymentCryptography",
        "Country": "US",
        "StateOrProvince": "Virginia",
        "City": "Arlington"
    }'
```

```
{
    "CertificateSigningRequest": "LS0tLS1CRUdJTiBDRVJUSUZJQ0FURSBSRVFVRVNULS0tLS0..."
}
```

The `CertificateSigningRequest` field contains the base64-encoded CSR that you'll send to your CA for signing.

### Step 3: Review CSR (Optional)
<a name="keyexchange-byoca.review-csr"></a>

You can optionally use OpenSSL to review the CSR contents and ensure it's valid and as expected.

**Example Review CSR with OpenSSL**  

```
$ echo "LS0tLS1CRUdJTiBDRVJUSUZJQ0FURSBSRVFVRVNULS0tLS0..." | base64 -d | openssl req -text
```

### Step 4: Sign the CSR with a Certificate Authority
<a name="keyexchange-byoca.sign-csr"></a>

After generating the CSR, you need to have it signed by a Certificate Authority (CA). In production environments, you would typically use AWS Private CA or your organization's established CA infrastructure. For testing purposes, you can use OpenSSL to create a self-signed certificate.

#### Using AWS Private CA
<a name="keyexchange-byoca.sign-csr-pca"></a>

To sign the CSR using AWS Private CA, first decode the base64-encoded CSR and save it to a file, then use the [IssueCertificate](https://docs.aws.amazon.com/acm-pca/latest/APIReference/API_IssueCertificate.html) API.

**Example Sign CSR with AWS Private CA**  

```
$ echo "LS0tLS1CRUdJTiBDRVJUSUZJQ0FURSBSRVFVRVNULS0tLS0..." | base64 -d > csr.pem

$ aws acm-pca issue-certificate \
    --certificate-authority-arn arn:aws:acm-pca:us-east-1:111122223333:certificate-authority/12345678-1234-1234-1234-123456789012 \
    --csr fileb://csr.pem \
    --signing-algorithm SHA256WITHRSA \
    --validity Value=365,Type=DAYS
```

```
{
    "CertificateArn": "arn:aws:acm-pca:us-east-1:111122223333:certificate-authority/12345678-1234-1234-1234-123456789012/certificate/abcdef1234567890"
}
```

Then retrieve the signed certificate:

**Example Retrieve Signed Certificate**  

```
$ aws acm-pca get-certificate \
    --certificate-authority-arn arn:aws:acm-pca:us-east-1:111122223333:certificate-authority/12345678-1234-1234-1234-123456789012 \
    --certificate-arn arn:aws:acm-pca:us-east-1:111122223333:certificate-authority/12345678-1234-1234-1234-123456789012/certificate/abcdef1234567890
```

```
{
    "Certificate": "-----BEGIN CERTIFICATE-----\nMIID...\n-----END CERTIFICATE-----",
    "CertificateChain": "-----BEGIN CERTIFICATE-----\nMIID...\n-----END CERTIFICATE-----"
}
```

Save the certificate content for use in the export step. You'll need to base64-encode it when providing it to the `ExportKey` API.

#### Using OpenSSL for Testing
<a name="keyexchange-byoca.sign-csr-openssl"></a>

For testing purposes, you can use OpenSSL to create a self-signed CA and sign the CSR. First, create a CA private key and self-signed certificate:

**Example Create Test CA with OpenSSL**  

```
$ # Generate CA private key
openssl genrsa -out ca-key.pem 4096

$ # Create self-signed CA certificate
openssl req -new -x509 -days 3650 -key ca-key.pem -out ca-cert.pem \
    -subj "/C=US/ST=Virginia/L=Arlington/O=TestOrg/CN=Test CA"
```

Then decode the CSR from the previous step and sign it with your test CA:

**Example Sign CSR with OpenSSL**  

```
$ # Decode the base64-encoded CSR
echo "LS0tLS1CRUdJTiBDRVJUSUZJQ0FURSBSRVFVRVNULS0tLS0..." | base64 -d > csr.pem

$ # Sign the CSR with the CA
openssl x509 -req -in csr.pem -CA ca-cert.pem -CAkey ca-key.pem \
    -CAcreateserial -out signed-cert.pem -days 365 -sha512
```

```
Certificate request self-signature ok
subject=C=US, ST=Virginia, L=Arlington, O=Amazon, OU=PaymentCryptography, CN=MyCertificateAWSUSEAST
```

The signed certificate is now in `signed-cert.pem`. You'll need to base64-encode this certificate when providing it to the `ExportKey` API:

**Example Base64 Encode the Signed Certificate**  

```
$ cat signed-cert.pem | base64 -w 0
```

### Step 5: Import CA Certificate
<a name="keyexchange-byoca.import-ca"></a>

Any CA being used needs to be trusted first to prevent arbitrary certificates from being used. Import your external CA's root certificate using the [ImportKey](https://docs.aws.amazon.com/payment-cryptography/latest/APIReference/API_ImportKey.html) API. If using an intermediate CA, call `import-key` again but specify `TrustedPublicKey` instead of `RootCertificatePublicKey` and specify the root CA ARN.

**Example Import Root CA Certificate**  

```
$ aws payment-cryptography import-key --key-material='{
    "RootCertificatePublicKey": {
        "KeyAttributes": {
            "KeyAlgorithm": "RSA_4096",
            "KeyClass": "PUBLIC_KEY",
            "KeyModesOfUse": {
                "Verify": true
            },
            "KeyUsage": "TR31_S0_ASYMMETRIC_KEY_FOR_DIGITAL_SIGNATURE"
        },
        "PublicKeyCertificate": "LS0tLS1CRUdJTiBDRVJUSUZJQ0FURS0tLS0t..."
    }
}'
```

```
{
    "Key": {
        "KeyArn": "arn:aws:payment-cryptography:us-east-1:111122223333:key/xivpaqy7qbbm7cdw",
        "KeyAttributes": {
            "KeyUsage": "TR31_S0_ASYMMETRIC_KEY_FOR_DIGITAL_SIGNATURE",
            "KeyClass": "PUBLIC_KEY",
            "KeyAlgorithm": "RSA_4096",
            "KeyModesOfUse": {
                "Verify": true
            }
        },
        "Enabled": true,
        "KeyState": "CREATE_COMPLETE",
        "KeyOrigin": "EXTERNAL"
    }
}
```

Take note of the CA's `KeyArn` for use in the export step.

### Step 6: Get KRD Encryption Certificate
<a name="keyexchange-byoca.get-krd"></a>

In this example, we're importing back into AWS Payment Cryptography, so we call the service to receive a KRD public key certificate using the [GetParametersForImport](https://docs.aws.amazon.com/payment-cryptography/latest/DataAPIReference/API_GetParametersForImport.html) API. In a real scenario, this would be provided by the other system, like an HSM, an ATM, a payment terminal or payment terminal management system.

**Example Get Parameters for Import**  

```
$ aws payment-cryptography-data get-parameters-for-import \
    --key-material-type "TR34_KEY_BLOCK" \
    --wrapping-key-algorithm RSA_2048
```

```
{
    "WrappingKeyCertificate": "LS0tLS1CRUdJTiBDRVJUSUZJQ0FURS0tLS0t...",
    "WrappingKeyCertificateChain": "LS0tLS1CRUdJTiBDRVJUSUZJQ0FURS0tLS0t...",
    "WrappingKeyAlgorithm": "RSA_2048",
    "ImportToken": "import-token-v2rxpl6drxeptn7w",
    "ParametersValidUntilTimestamp": "2025-11-01T18:45:31.271000-07:00"
}
```

### Step 7: Export Key with BYOCA
<a name="keyexchange-byoca.export-key"></a>

Finally, export the key using TR-34 with your own CA-signed certificate using the [ExportKey](https://docs.aws.amazon.com/payment-cryptography/latest/DataAPIReference/API_ExportKey.html) API. Provide the signing certificate that was signed by your external CA.

**Example TR-34 Export with BYOCA**  

```
$ aws payment-cryptography-data export-key \
    --export-key-identifier arn:aws:payment-cryptography:us-east-1:111122223333:key/iox73p5f4c4yjiod \
    --key-material '{
        "Tr34KeyBlock": {
            "CertificateAuthorityPublicKeyIdentifier": "arn:aws:payment-cryptography:us-east-1:111122223333:key/j625deyfqlwctu57",
            "SigningKeyIdentifier": "arn:aws:payment-cryptography:us-east-1:111122223333:key/xgmq6fs6uow736uc",
            "SigningKeyCertificate": "LS0tLS1CRUdJTiBDRVJUSUZJQ0FURS0tLS0t...",
            "KeyBlockFormat": "X9_TR34_2012",
            "WrappingKeyCertificate": "LS0tLS1CRUdJTiBDRVJUSUZJQ0FURS0tLS0t..."
        }
    }'
```

```
{
    "WrappedKey": {
        "WrappedKeyMaterialFormat": "TR34_KEY_BLOCK",
        "KeyMaterial": "3082055A06092A864886F70D010702A082054B30820547...",
        "KeyCheckValue": "3DCA31",
        "KeyCheckValueAlgorithm": "ANSI_X9_24"
    }
}
```

The exported key block can now be imported by the receiving system using the standard TR-34 import process.

## Additional Notes
<a name="keyexchange-byoca.notes"></a>
+ These examples are shown using the AWS CLI. The same functionality is available in all AWS SDKs including Java, Python, Go, and Rust.
+ If you're testing with a self-signed CA, you can use OpenSSL to create a test CA and sign the CSR. In production, use your organization's established CA infrastructure.