Importing a key into Cloud KMS

This topic shows you how to import a cryptographic key into Cloud HSM or Cloud Key Management Service.

For more details about importing keys, including limitations and restrictions, refer to Key import.

You can complete the steps in this topic in 5 to 10 minutes, not including the Before you begin steps. Wrapping the key manually adds complexity to the task.

Before you begin

It is recommended that you create a new project to test this feature, to ease clean-up after testing and to ensure that you have adequate IAM permissions to import a key.

Before you can import a key, you need to prepare the project, the local system, and the key itself.

Preparing the project

  1. Sign in to your Google Account.

    If you don't already have one, sign up for a new account.

  2. In the Google Cloud Console, on the project selector page, select or create a Google Cloud project.

    Go to the project selector page

  3. Projeniz için faturalandırmanın etkinleştirildiğinden emin olun.

    Faturalandırmayı etkinleştirmeyi öğren

  4. Enable the required API.

    Enable the API

  5. Install and initialize the Cloud SDK.
  6. The user performing the import needs the following IAM permissions to create key rings, keys, and import jobs. If the user is not the project owner, you can assign both of the following two pre-defined roles to the user:

    • roles/editor
    • roles/cloudkms.importer

    For more information about available IAM roles and permissions for Cloud KMS, refer to Permissions and roles.

Preparing the local system

Prepare the local system by choosing one of the following options. Automatic key wrapping is recommended for most users.

  • If you want to allow the gcloud command-line tool to wrap your keys automatically before transmitting them to Google Cloud, you must install the Pyca cryptography library on your local system. The Pyca library is used by the import job that wraps and protects the key locally before sending it to Google Cloud.
  • If you want to wrap your keys manually, you must configure OpenSSL for manual key wrapping.

Preparing the key

Verify that your key's algorithm and length are supported. Allowable algorithms for a key depend upon whether the key is used for symmetric encryption, asymmetric encryption or asymmetric signing, as well as whether the key is stored in software or an HSM. You specify the key's algorithm as part of the import request.

Separately, you must also verify how the key is encoded, and make adjustments if necessary.

The following cannot be changed for a key version after it is created or imported:

  • The key's protection level indicates whether the key persists in software, in an HSM, or in an external key management system. Key material cannot be moved from one of these storage environments to another. A key's versions all have the same protection level.

  • The key's purpose indicates whether the key's versions are used for symmetric encryption, asymmetric encryption, or asymmetric signing. A key's purpose limits the possible algorithms that can be used to create versions of that key. A key's versions all have the same purpose.

If you don't have a key to import but want to validate the procedure for importing keys, you can create a symmetric key on the local system, using the following command:

openssl rand 32 > ${HOME}/test.bin

Use this key for testing only. A key created this way might not be appropriate for production use.

If you need to wrap the key manually, do that before continuing with the procedures in this topic.

Create the target key and key ring

A Cloud KMS key is a container object that contains zero or more key versions. Each key version contains a cryptographic key.

When you import a key into Cloud KMS or Cloud HSM, the imported key becomes a new key version on an existing Cloud KMS or Cloud HSM key. In the rest of this topic, this key is called the target key. The target key must exist before you can import key material into it.

Importing a key version has no effect on that key's existing versions. However, It is recommended to create an empty key when testing key import. An empty key has no version, isn't active, and can't be used.

A key exists on a key ring; in this topic, this key ring is called the target key ring. The location of the target key ring determines the location where the key material is available after import. Cloud HSM keys cannot be created or imported in some locations. After a key is created, it cannot be moved to a different key ring or location.

Follow these steps to create an empty key on a new key ring using the gcloud command-line tool or the Google Cloud Console.

Web UI

  1. Go to the Cryptographic Keys page in the Cloud Console.

    Go to the Cryptographic Keys page

  2. Click Create key ring.

  3. In the Key ring name field, enter the name for your key ring.

  4. From the Location dropdown, select a location.

  5. Click Create. The detail page for the key ring opens.

  6. Click Create key.

  7. Select Imported key. This prevents an initial key version from being created.

  8. In the Key name field, enter the name for your key.

  9. Set the Protection level to either Software or HSM.

  10. [Optional] For imported keys, automatic rotation is disabled by default. If you enable automatic rotation, new key versions will be generated in Cloud KMS, and the imported key version will no longer be the default key version after a rotation.

  11. [Optional] In the Labels field, click Add label if you want to [add labels to your key][4].

  12. Click Create.

Command-line

To use Cloud KMS on the command line, first Install or upgrade to the latest version of Cloud SDK.

  1. Create the target key ring. If you intend to import into a Cloud HSM key, select a location with support for Cloud HSM.

    gcloud kms keyrings create key-ring-name \
      --location location
    

    You can learn more about creating key rings.

  2. Create the target key.

    • Set the key's purpose:
      • For a symmetric key, set the purpose to encryption.
      • For an asymmetric key, set the purpose to either asymmetric-signing or asymmetric-encryption.
    • Prevent an initial version from being created by using the --skip-initial-version-creation flag.
    • Do not set the protection level.
    • Do not specify an algorithm for the target key. You specify the algorithm of the imported key as part of the import request.
    • [Optional] Do not specify a rotation policy. If you enable automatic rotation, new key versions will be generated in Cloud KMS, and the imported key version will no longer be the default key version after a rotation.
    gcloud kms keys create key-name \
      --location location \
      --keyring key-ring-name \
      --purpose purpose \
      --skip-initial-version-creation
    

    You can learn more about creating Cloud KMS keys or Cloud HSM keys.

Python

To run this code, first set up a Python development environment and install the Cloud KMS Python SDK.

def create_key_for_import(project_id, location_id, key_ring_id, crypto_key_id):
    """

    Sets up an empty CryptoKey within a KeyRing for import.


    Args:
        project_id (string): Google Cloud project ID (e.g. 'my-project').
        location_id (string): Cloud KMS location (e.g. 'us-east1').
        key_ring_id (string): ID of the Cloud KMS key ring (e.g. 'my-key-ring').
        crypto_key_id (string): ID of the key to import (e.g. 'my-asymmetric-signing-key').
    """

    # Import the client library.
    from google.cloud import kms

    # Create the client.
    client = kms.KeyManagementServiceClient()

    # Build the key. For more information regarding allowed values of these fields, see:
    # https://googleapis.dev/python/cloudkms/latest/_modules/google/cloud/kms_v1/types/resources.html
    purpose = kms.CryptoKey.CryptoKeyPurpose.ASYMMETRIC_SIGN
    algorithm = kms.CryptoKeyVersion.CryptoKeyVersionAlgorithm.EC_SIGN_P256_SHA256
    protection_level = kms.ProtectionLevel.HSM
    key = {
        'purpose': purpose,
        'version_template': {
            'algorithm': algorithm,
            'protection_level': protection_level
        }
    }

    # Build the parent key ring name.
    key_ring_name = client.key_ring_path(project_id, location_id, key_ring_id)

    # Call the API.
    created_key = client.create_crypto_key(request={'parent': key_ring_name, 'crypto_key_id': crypto_key_id, 'crypto_key': key})
    print('Created hsm key: {}'.format(created_key.name))

The key ring and key now exist, but the key contains no key material, has no version, and is not active. Next, you create an import job.

Create the import job

An import job defines the characteristics of the keys it imports, including properties that cannot be changed after the key is imported.

The protection level defines whether keys that result from this import job will reside in software, in a HSM, or in an external key management system. The protection level can't be changed after the key is eventually imported.

The import method defines the algorithm used to create the wrapping key that protects imported keys during transit from your local system to the target Google Cloud project. You can choose a 3072-bit or a 4096- bit RSA key. Unless you have specific requirements, the 3072-bit wrapping key is recommended.

You can create an import job using the gcloud tool, the Cloud Console, or the Cloud Key Management Service API.

Web UI

  1. Go to the Cryptographic Keys page in the Cloud Console.

    Go to the Cryptographic Keys page

  2. Click the name of the target key ring.

  3. Set the Protection level to either Software or HSM. Use the same protection level as you set for the target key.

  4. Click Create import job.

  5. In the Name field, enter the name for your import job.

  6. From the Import method dropdown, set the import method to either 3072 bit RSA or 4096 bit RSA.

  7. Click Create.

Command-line

To use Cloud KMS on the command line, first Install or upgrade to the latest version of Cloud SDK.

Use a command like the following to create an import job.

gcloud kms import-jobs create import-job \
  --location location \
  --keyring key-ring-name \
  --import-method import-method \
  --protection-level protection-level
  • Use the same key ring and location as the target key.
  • Set the protection level to either software or hsm.
  • Set the import method to either rsa-oaep-3072-sha1-aes-256 or rsa-oaep-4096-sha1-aes-256.

Python

To run this code, first set up a Python development environment and install the Cloud KMS Python SDK.

def create_import_job(project_id, location_id, key_ring_id, import_job_id):
    """
    Create a new import job in Cloud KMS.

    Args:
        project_id (string): Google Cloud project ID (e.g. 'my-project').
        location_id (string): Cloud KMS location (e.g. 'us-east1').
        key_ring_id (string): ID of the Cloud KMS key ring (e.g. 'my-key-ring').
        import_job_id (string): ID of the import job (e.g. 'my-import-job').
    """

    # Import the client library.
    from google.cloud import kms

    # Create the client.
    client = kms.KeyManagementServiceClient()

    # Retrieve the fully-qualified key_ring string.
    key_ring_name = client.key_ring_path(project_id, location_id, key_ring_id)

    # Set paramaters for the import job, allowed values for ImportMethod and ProtectionLevel found here:
    # https://googleapis.dev/python/cloudkms/latest/_modules/google/cloud/kms_v1/types/resources.html

    import_method = kms.ImportJob.ImportMethod.RSA_OAEP_3072_SHA1_AES_256
    protection_level = kms.ProtectionLevel.HSM
    import_job_params = {"import_method": import_method, "protection_level": protection_level}

    # Call the client to create a new import job.
    import_job = client.create_import_job({"parent": key_ring_name, "import_job_id": import_job_id, "import_job": import_job_params})

    print('Created import job: {}'.format(import_job.name))

API

These examples use curl as an HTTP client to demonstrate using the API. For more information about access control, see Accessing the Cloud KMS API.

  1. Create an instance of the ImportJob type, and specify values for the ImportJob.protectionLevel and ImportJob.importMethod fields.

  2. Using your instance of ImportJob as the request body, call the ImportJob.create method.

Checking the state of the import job

The initial state for an import job is PENDING_GENERATION. When the state is ACTIVE, you can use it to import keys.

An import job expires after three days. If the import job is expired, you must create a new one.

You can check the status of an import job using the gcloud command-line tool, the Google Cloud Console, or the Cloud Key Management Service API.

Web UI

  1. Go to the Cryptographic Keys page in the Cloud Console.

    Go to the Cryptographic Keys page

  2. Click the name of the key ring that contains your import job.

  3. Click the Import Jobs tab at the top of the page.

  4. The state will be visible under Status next to your import job's name.

Command-line

To use Cloud KMS on the command line, first Install or upgrade to the latest version of Cloud SDK.

When an import job is active, you can use it to import keys. This may take a few minutes. Use this command to verify that the import job is active. Use the location and keyring where you created the import job.

gcloud kms import-jobs describe import-job \
  --location location \
  --keyring key-ring-name \
  --format="value(state)"
state: ACTIVE

Python

To run this code, first set up a Python development environment and install the Cloud KMS Python SDK.

def check_state_import_job(project_id, location_id, key_ring_id, import_job_id):
    """
    Check the state of an import job in Cloud KMS.

    Args:
        project_id (string): Google Cloud project ID (e.g. 'my-project').
        location_id (string): Cloud KMS location (e.g. 'us-east1').
        key_ring_id (string): ID of the Cloud KMS key ring (e.g. 'my-key-ring').
        import_job_id (string): ID of the import job (e.g. 'my-import-job').
    """

    # Import the client library.
    from google.cloud import kms

    # Create the client.
    client = kms.KeyManagementServiceClient()

    # Retrieve the fully-qualified import_job string.
    import_job_name = client.import_job_path(
        project_id, location_id, key_ring_id, import_job_id)

    # Retrieve the state from an existing import job.
    import_job = client.get_import_job(name=import_job_name)

    print('Current state of import job {}: {}'.format(import_job.name, import_job.state))

API

These examples use curl as an HTTP client to demonstrate using the API. For more information about access control, see Accessing the Cloud KMS API.

Call the ImportJob.get method and check the state field. If state is PENDING_GENERATION, the import job is still being created. Periodically recheck the state until it is ACTIVE.

As soon as the import job is active, you can make a request to import a key.

Preventing modification of import jobs

The import job determines many characteristics of the imported key, including the key's algorithm and whether an imported key is an HSM key or a software key. You can configure Identity and Access Management permissions to prevent users from creating import jobs, while allowing them to use import jobs to import keys.

  1. Only grant key administrators the importjobs.create.
  2. Grant the importjobs.useToImport permission for a specific import job to the operator who will use that job to import keys.
  3. When you create the import job, specify the protection level and algorithm for keys imported using it.

Until the import job expires, users who have the importjobs.useToImport and do not have the importjobs.create permission for a given import job can import keys, but cannot modify the characteristics of the import job.

Import the key

After checking the status of the import job, you can make an import request.

You use different flags to make the import request, depending on whether you want the gcloud command-line tool to wrap your key automatically or if you have already wrapped your key manually.

Regardless of whether you wrapped your key manually or automatically, you must set the algorithm to a supported algorithm that matches the length of the actual key to be imported, and specifies the key's purpose.

  • Keys with purpose ENCRYPT_DECRYPT use the google-symmetric-encryption algorithm, and have a length of 32.

  • Keys with purpose ASYMMETRIC_ENCRYPT or ASYMMETRIC_SIGN support a variety of algorithms and lengths.

    A key's purpose cannot be changed after the key is created, but subsequent key versions can be created at different lengths than the initial key version.

Automatically wrapping and importing a key

If you want to use automatic wrapping, you must use the gcloud command-line tool. Use a command like the following. Set --target-key-file to the location of the unwrapped key to wrap and import. Do not set -rsa-aes-wrapped-key-file.

You can optionally set the --public-key-file flag to the location where the public key has already been downloaded. When importing a large number of keys, this prevents the public key from being downloaded during each import. For example, you could write a script that downloaded the public key once, then provided its location when importing each key.

gcloud kms keys versions import \
  --import-job import-job \
  --location location \
  --keyring key-ring-name \
  --key KEY_NAME \
  --algorithm algorithm-name \
  --target-key-file path-to-unwrapped-key-to-import

The key is wrapped by the wrapping key associated with the import job, transmitted to Google Cloud, and imported as a new key version on the target key.

Importing a manually-wrapped key

Use the instructions in this section to import a key that you have wrapped manually. Set --rsa-aes-wrapped-key-file to the location of key that you manually wrapped. Do not set --target-key-file.

You can optionally set the --public-key-file flag to the location where the public key has already been downloaded. When importing a large number of keys, this prevents the public key from being downloaded during each import. For example, you could write a script that downloaded the public key once, then provided its location when importing each key.

Web UI

  1. Open the Cryptographic Keys page in the Cloud Console.

  2. Click the name of the key ring that contains your import job. The target key is shown, along with any other keys on the key ring.

  3. Click the name of the target key, then click Import key version.

  4. Select your import job from the Select import job dropdown.

  5. In the Upload the wrapped key selector, select the key that you have already wrapped.

  6. If you are importing an asymmetric key, select the algorithm from the Algorithm dropdown. Your Import key version page should look similar to:

    Import key version

  7. Click Import.

Command-line

To use Cloud KMS on the command line, first Install or upgrade to the latest version of Cloud SDK.

Use a command like the following.

gcloud kms keys versions import \
  --import-job import-job \
  --location location \
  --keyring key-ring-name \
  --key KEY_NAME \
  --algorithm algorithm-name \
  --rsa-aes-wrapped-key-file path-to-wrapped-key-to-import

For more information, see the output of the gcloud kms keys versions import --help command.

Python

To run this code, first set up a Python development environment and install the Cloud KMS Python SDK.

def import_manually_wrapped_key(project_id, location_id, key_ring_id, crypto_key_id, import_job_id):
    """
    Generates and imports local key material to Cloud KMS.

    Args:
        project_id (string): Google Cloud project ID (e.g. 'my-project').
        location_id (string): Cloud KMS location (e.g. 'us-east1').
        key_ring_id (string): ID of the Cloud KMS key ring (e.g. 'my-key-ring').
        crypto_key_id (string): ID of the key to import (e.g. 'my-asymmetric-signing-key').
        import_job_id (string): ID of the import job (e.g. 'my-import-job').
    """

    # Import the client library and Python standard cryptographic libraries.
    import os
    from cryptography.hazmat import backends
    from cryptography.hazmat.primitives import hashes, keywrap, serialization
    from cryptography.hazmat.primitives.asymmetric import ec, padding
    from google.cloud import kms

    # Generate some key material in Python and format it in PKCS #8 DER as
    # required by Google Cloud KMS.
    key = ec.generate_private_key(ec.SECP256R1, backends.default_backend())
    formatted_key = key.private_bytes(
        serialization.Encoding.DER,
        serialization.PrivateFormat.PKCS8,
        serialization.NoEncryption())

    print('Generated key bytes: {}'.format(formatted_key))

    # Create the client.
    client = kms.KeyManagementServiceClient()

    # Retrieve the fully-qualified crypto_key and import_job string.
    crypto_key_name = client.crypto_key_path(
        project_id, location_id, key_ring_id, crypto_key_id)
    import_job_name = client.import_job_path(
        project_id, location_id, key_ring_id, import_job_id)

    # Generate a temporary 32-byte key for AES-KWP and wrap the key material.
    kwp_key = os.urandom(32)
    wrapped_target_key = keywrap.aes_key_wrap_with_padding(
        kwp_key, formatted_key, backends.default_backend())

    # Retrieve the public key from the import job.
    import_job = client.get_import_job(name=import_job_name)
    import_job_pub = serialization.load_pem_public_key(
        bytes(import_job.public_key.pem, 'UTF-8'), backends.default_backend())

    # Wrap the KWP key using the import job key.
    wrapped_kwp_key = import_job_pub.encrypt(
        kwp_key,
        padding.OAEP(
            mgf=padding.MGF1(algorithm=hashes.SHA1()),
            algorithm=hashes.SHA1(),
            label=None))

    # Import the wrapped key material.
    client.import_crypto_key_version({
        "parent": crypto_key_name,
        "import_job": import_job_name,
        "algorithm": kms.CryptoKeyVersion.CryptoKeyVersionAlgorithm.EC_SIGN_P256_SHA256,
        "rsa_aes_wrapped_key": wrapped_kwp_key + wrapped_target_key,
    })

    print('Imported: {}'.format(import_job.name))

API

These examples use curl as an HTTP client to demonstrate using the API. For more information about access control, see Accessing the Cloud KMS API.

  1. For the request body of the cryptoKeyVersions.import method, set the algorithm field to the algorithm of the key being imported. This value does not need to match the versionTemplate of the CryptoKey that is importing this version. The algorithm field is of type CryptoKeyVersionAlgorithm.

  2. Also for the request body, set the wrappedKeyMaterial field to the key material that you that you have already wrapped.

  3. Call the cryptoKeyVersions.import method. The cryptoKeyVersions.import response is of type CryptoKeyVersion. When a key is successfully imported, its state is ENABLED and you can use it in Cloud KMS.

The key-import request is initiated. You can monitor its status.

Check the state of the imported key

The initial state for an imported key is PENDING_IMPORT. When the state is ENABLED, the key has been imported successfully. If the import fails, the status is IMPORT_FAILED.

You can check the status of an import request using the gcloud command-line tool, the Google Cloud Console, or the Cloud Key Management Service API.

Web UI

  1. Open the Cryptographic Keys page in the Cloud Console.

  2. Click the name of the key ring that contains your import job.

  3. Click the Import Jobs tab at the top of the page.

  4. The state will be visible under Status next to your import job's name.

Command-line

To use Cloud KMS on the command line, first Install or upgrade to the latest version of Cloud SDK.

Use the versions list command to check the state. Use the same location, target key ring, and target key that you created earlier in this topic.

gcloud kms keys versions list \
  --keyring keyring \
  --location location \
  --key key

Python

To run this code, first set up a Python development environment and install the Cloud KMS Python SDK.

def check_state_imported_key(project_id, location_id, key_ring_id, import_job_id):
    """
    Check the state of an import job in Cloud KMS.

    Args:
        project_id (string): Google Cloud project ID (e.g. 'my-project').
        location_id (string): Cloud KMS location (e.g. 'us-east1').
        key_ring_id (string): ID of the Cloud KMS key ring (e.g. 'my-key-ring').
        import_job_id (string): ID of the import job (e.g. 'my-import-job').
    """

    # Import the client library.
    from google.cloud import kms

    # Create the client.
    client = kms.KeyManagementServiceClient()

    # Retrieve the fully-qualified import_job string.
    import_job_name = client.import_job_path(
        project_id, location_id, key_ring_id, import_job_id)

    # Retrieve the state from an existing import job.
    import_job = client.get_import_job(name=import_job_name)

    print('Current state of import job {}: {}'.format(import_job.name, import_job.state))

API

These examples use curl as an HTTP client to demonstrate using the API. For more information about access control, see Accessing the Cloud KMS API.

Call the ImportJob.get method and check the state field. If state is PENDING_GENERATION, the import job is still being created. Periodically recheck the state until it is ACTIVE.

After the key is imported, its status changes to Active. For symmetric keys, you must set the imported key version as the primary version before you can use the key.

Symmetric keys: Set the primary version

This step is required when importing symmetric keys, and is not relevant for asymmetric keys. An asymmetric key does not have a primary version. You must use the gcloud command-line tool to set the primary version.

gcloud kms keys set-primary-version key-name --version=version-number

What's next