Import a key version into Cloud KMS Stay organized with collections Save and categorize content based on your preferences.
This guide shows you how to import a cryptographic keyinto Cloud HSM or Cloud Key Management Service as a new key version.
For more details about importing keys, including limitations andrestrictions, seekey import.
You can complete the steps in this guide in 5 to 10 minutes, not including theBefore you begin steps. Wrapping the key manually addscomplexity to the task.
Before you begin
We recommend that you create a new project to test this feature, to easeclean-up after testing and to ensure that you have adequateIdentity and Access Management (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
- Sign in to your Google Cloud account. If you're new to Google Cloud, create an account to evaluate how our products perform in real-world scenarios. New customers also get $300 in free credits to run, test, and deploy workloads.
In the Google Cloud console, on the project selector page, select or create a Google Cloud project.
Note: If you don't plan to keep the resources that you create in this procedure, create a project instead of selecting an existing project. After you finish these steps, you can delete the project, removing all resources associated with the project.Roles required to select or create a project
- Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
- Create a project: To create a project, you need the Project Creator role (
roles/resourcemanager.projectCreator), which contains theresourcemanager.projects.createpermission.Learn how to grant roles.
Verify that billing is enabled for your Google Cloud project.
Enable the required API.
Roles required to enable APIs
To enable APIs, you need the Service Usage Admin IAM role (
roles/serviceusage.serviceUsageAdmin), which contains theserviceusage.services.enablepermission.Learn how to grant roles.Install the Google Cloud CLI.
If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.
Toinitialize the gcloud CLI, run the following command:
gcloudinit
In the Google Cloud console, on the project selector page, select or create a Google Cloud project.
Note: If you don't plan to keep the resources that you create in this procedure, create a project instead of selecting an existing project. After you finish these steps, you can delete the project, removing all resources associated with the project.Roles required to select or create a project
- Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
- Create a project: To create a project, you need the Project Creator role (
roles/resourcemanager.projectCreator), which contains theresourcemanager.projects.createpermission.Learn how to grant roles.
Verify that billing is enabled for your Google Cloud project.
Enable the required API.
Roles required to enable APIs
To enable APIs, you need the Service Usage Admin IAM role (
roles/serviceusage.serviceUsageAdmin), which contains theserviceusage.services.enablepermission.Learn how to grant roles.Install the Google Cloud CLI.
If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.
Toinitialize the gcloud CLI, run the following command:
gcloudinit
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 assignboth of the following two predefined roles to the user:
roles/editorroles/cloudkms.importer
For more information about available IAM roles and permissions for Cloud KMS, refer toPermissions and roles.
Preparing the local system
Prepare the local system by choosingone of the following options. Automatickey wrapping is recommended for most users.
- If you want to allow the Google Cloud CLI to wrap your keys automaticallybefore transmitting them to Google Cloud, you mustinstall the Pyca cryptography libraryon your local system. The Pyca library is used by the import job thatwraps and protects the key locally before sending it to Google Cloud.
- If you want to wrap your keys manually, you mustconfigureOpenSSL for manual key wrapping.
Preparing the key
Verify that your key'salgorithm and length aresupported. Allowable algorithms for a key depend upon whether the key isused for symmetric encryption, asymmetric encryption or asymmetric signing, aswell as whether the key is stored in software or an HSM. You specify the key'salgorithm as part of theimport request.
Separately, you must alsoverify how the key is encoded,and make adjustments if necessary.
The following can't be changed for a key version after it is created orimported:
Theprotection level indicates whether the key persists in software, ina multi-tenant HSM, in a single-tenant HSM, or in an external key managementsystem. Key material cannot be moved from one of these storage environmentsto another. All versions of a key have the same protection level.
Thepurpose indicates whether versions of the key are used for symmetricencryption, asymmetric encryption, or asymmetric signing. The purpose of thekey limits the possible algorithms that can be used to create versions ofthat key. All versions of a key have the same purpose.
If you don't have a key to import but want to validate the procedure forimporting keys, you can create a symmetric key on the local system, using thefollowing command:
openssl rand 32 > ${HOME}/test.binUse this key for testing only. A key created this way might not be appropriatefor production use.
If you need towrap the key manually,do that before continuing with the procedures in this guide.
Create the target key and key ring
A Cloud KMS key is a container object that contains zero or morekey versions. Each key version contains a cryptographic key.
When you import a key into Cloud KMS or Cloud HSM, theimported key becomes a new key version on an existing Cloud KMS orCloud HSM key. In the rest of this guide, this key is called thetarget key. The target key must exist before you can import key material intoit.
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 keyhas no version, isn't active, and can't be used.
You may optionally specify that your newly created key may only contain importedversions, which prevents accidental generation of new versions inCloud KMS.
A key exists on a key ring; in this guide, this key ring is called thetarget key ring. The location of the target key ring determines the locationwhere the key material is available after import. Cloud HSM keys cannotbe created or imported in somelocations. After a key iscreated, 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 theGoogle Cloud CLI or the Google Cloud console.
Console
In the Google Cloud console, go to theKey Management page.
ClickCreate key ring.
In theKey ring name field, enter the name for your key ring.
UnderLocation type, select a location type and location.
ClickCreate. TheCreate key page opens.
In theKey name field, enter the name for your key.
ForProtection level, selectSoftware,HSM, orSingle-tenant HSM.
If you selectedSingle-tenant HSM, then select theSingle-tenant HSMinstance where you want to create thekey.
ForKey material, selectImported key and then clickContinue.This prevents an initial key version from being created.
Set thePurpose andAlgorithm for the key and then clickContinue.
Optional: If you want this key to contain only imported key versions,selectRestrict key versions to import only. This prevents you fromaccidentally creating new key versions in Cloud KMS.
Optional: For imported keys, automatic rotation is disabled by default.To enable automatic rotation, select a value from theKey rotationperiod field.
If you enable automatic rotation, new key versions will be generated inCloud KMS, and the imported key version will no longerbe the default key version after a rotation.
ClickCreate.
gcloud
To use Cloud KMS on the command line, firstInstall or upgrade to the latest version of Google Cloud CLI.
Create the target key ring. Choose a location that is compatible with theprotection level that you want to use. For more information about supportedlocations, seeCloud KMS locations.
gcloud kms keyrings createKEY_RING \ --locationLOCATION
You can learn more aboutcreating key rings.
Create the target key using the
kms keys createcommand with the--skip-initial-version-creationflag. This creates a key with no initialkey version so that your imported key material is version1. Use the--import-onlyflag to prevent Cloud KMS from generating keymaterial for new key versions. With this flag set, new key versions for thiskey must be imported. Keys created as--import-onlymust be rotatedmanually.gcloud kms keys createKEY_NAME \ --locationLOCATION \ --keyringKEY_RING \ --purposePURPOSE \ --protection-levelPROTECTION_LEVEL \ --skip-initial-version-creation \ --import-only
Replace the following:
KEY_NAME: the name that you want to use for the key.LOCATION: the location of the key ring.KEY_RING: the key ring where you want to create the key.PURPOSE: thepurpose thatyou want to use for the key.PROTECTION_LEVEL: the protection level that you want to usefor the key—for example,HSM.
To create a Single-tenant Cloud HSM key, add the
--cryptoKeyBackendflag to this command and add the resource identifier of theSingle-tenant Cloud HSM instance where you want to import the key:--crypto-key-backend="projects/INSTANCE_PROJECT/locations/LOCATION/singleTenantHsmInstances/INSTANCE_NAME"
Go
To run this code, firstset up a Go development environment andinstall the Cloud KMS Go SDK.
import("context""fmt""io"kms"cloud.google.com/go/kms/apiv1""cloud.google.com/go/kms/apiv1/kmspb")// createKeyForImport creates a new asymmetric signing key in Cloud HSM.funccreateKeyForImport(wio.Writer,parent,idstring)error{// parent := "projects/my-project/locations/us-east1/keyRings/my-key-ring"// id := "my-imported-key"// Create the client.ctx:=context.Background()client,err:=kms.NewKeyManagementClient(ctx)iferr!=nil{returnfmt.Errorf("failed to create kms client: %w",err)}deferclient.Close()// Build the request.req:=&kmspb.CreateCryptoKeyRequest{Parent:parent,CryptoKeyId:id,CryptoKey:&kmspb.CryptoKey{Purpose:kmspb.CryptoKey_ASYMMETRIC_SIGN,VersionTemplate:&kmspb.CryptoKeyVersionTemplate{ProtectionLevel:kmspb.ProtectionLevel_HSM,Algorithm:kmspb.CryptoKeyVersion_EC_SIGN_P256_SHA256,},// Ensure that only imported versions may be added to this key.ImportOnly:true,},SkipInitialVersionCreation:true,}// Call the API.result,err:=client.CreateCryptoKey(ctx,req)iferr!=nil{returnfmt.Errorf("failed to create key: %w",err)}fmt.Fprintf(w,"Created key: %s\n",result.Name)returnnil}Java
To run this code, firstset up a Java development environment andinstall the Cloud KMS Java SDK.
importcom.google.cloud.kms.v1.CreateCryptoKeyRequest;importcom.google.cloud.kms.v1.CryptoKey;importcom.google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose;importcom.google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionAlgorithm;importcom.google.cloud.kms.v1.CryptoKeyVersionTemplate;importcom.google.cloud.kms.v1.KeyManagementServiceClient;importcom.google.cloud.kms.v1.KeyRingName;importcom.google.cloud.kms.v1.ProtectionLevel;importjava.io.IOException;publicclassCreateKeyForImport{publicvoidcreateKeyForImport()throwsIOException{// TODO(developer): Replace these variables before running the sample.StringprojectId="your-project-id";StringlocationId="us-east1";StringkeyRingId="my-key-ring";Stringid="my-import-key";createKeyForImport(projectId,locationId,keyRingId,id);}// Create a new crypto key to hold imported key versions.publicvoidcreateKeyForImport(StringprojectId,StringlocationId,StringkeyRingId,Stringid)throwsIOException{// Initialize client that will be used to send requests. This client only// needs to be created once, and can be reused for multiple requests. After// completing all of your requests, call the "close" method on the client to// safely clean up any remaining background resources.try(KeyManagementServiceClientclient=KeyManagementServiceClient.create()){// Build the parent name from the project, location, and key ring.KeyRingNamekeyRingName=KeyRingName.of(projectId,locationId,keyRingId);// Create the crypto key.CryptoKeycreatedKey=client.createCryptoKey(CreateCryptoKeyRequest.newBuilder().setParent(keyRingName.toString()).setCryptoKeyId(id).setCryptoKey(CryptoKey.newBuilder().setPurpose(CryptoKeyPurpose.ASYMMETRIC_SIGN).setVersionTemplate(CryptoKeyVersionTemplate.newBuilder().setProtectionLevel(ProtectionLevel.HSM).setAlgorithm(CryptoKeyVersionAlgorithm.EC_SIGN_P256_SHA256))// Ensure that only imported versions may be// added to this key..setImportOnly(true)).setSkipInitialVersionCreation(true).build());System.out.printf("Created crypto key %s%n",createdKey.getName());}}}Node.js
To run this code, firstset up a Node.js development environment andinstall the Cloud KMS Node.js SDK.
//// TODO(developer): Uncomment these variables before running the sample.//// const projectId = 'my-project';// const locationId = 'us-east1';// const keyRingId = 'my-key-ring';// const id = 'my-imported-key';// Imports the Cloud KMS libraryconst{KeyManagementServiceClient}=require('@google-cloud/kms');// Instantiates a clientconstclient=newKeyManagementServiceClient();// Build the parent key ring nameconstkeyRingName=client.keyRingPath(projectId,locationId,keyRingId);asyncfunctioncreateKeyForImport(){const[key]=awaitclient.createCryptoKey({parent:keyRingName,cryptoKeyId:id,cryptoKey:{purpose:'ENCRYPT_DECRYPT',versionTemplate:{algorithm:'GOOGLE_SYMMETRIC_ENCRYPTION',protectionLevel:'HSM',},// Optional: ensure that only imported versions may be added to this// key.importOnly:true,},// Do not allow KMS to generate an initial version of this key.skipInitialVersionCreation:true,});console.log(`Created key for import:${key.name}`);returnkey;}returncreateKeyForImport();Python
To run this code, firstset up a Python development environment andinstall the Cloud KMS Python SDK.
fromgoogle.cloudimportkmsdefcreate_key_for_import(project_id:str,location_id:str,key_ring_id:str,crypto_key_id:str)->None:""" 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'). """# 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.htmlpurpose=kms.CryptoKey.CryptoKeyPurpose.ASYMMETRIC_SIGNalgorithm=kms.CryptoKeyVersion.CryptoKeyVersionAlgorithm.EC_SIGN_P256_SHA256protection_level=kms.ProtectionLevel.HSMkey={"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,# Do not allow KMS to generate an initial version of this key."skip_initial_version_creation":True,})print(f"Created hsm key:{created_key.name}")API
These examples usecurl as an HTTP client to demonstrate using the API. For more information about access control, seeAccessing the Cloud KMS API.
Create a new key ring:
curl "https://cloudkms.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/keyRings?keyRingId=KEY_RING" \ --request "POST" \ --header "authorization: BearerTOKEN" \ --header "content-type: application/json" \ --header "x-goog-user-project:PROJECT_ID" \ --data "{}"See the
KeyRing.createAPI documentationfor more information.Create an empty, import-only key:
curl "https://cloudkms.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/keyRings/KEY_RING/cryptoKeys?cryptoKeyId=KEY_NAME&skipInitialVersionCreation=true&importOnly=true" \ --request "POST" \ --header "authorization: BearerTOKEN" \ --header "content-type: application/json" \ --header "x-goog-user-project:PROJECT_ID" \ --data "{"purpose":"PURPOSE", "versionTemplate":{"protectionLevel":"PROTECTION_LEVEL","algorithm":"ALGORITHM"}}"See the
CryptoKey.createAPI documentationfor more information.If you want to create your key in a Single-tenant Cloud HSM, add thecryptoKeyBackendfield to the body of the command and add the resourceidentifier of the Single-tenant Cloud HSM instance where you want toimport the key:"crypto-key-backend":"projects/INSTANCE_PROJECT/locations/LOCATION/singleTenantHsmInstances/INSTANCE_NAME"
The key ring and key now exist, but the key contains no key material, has noversion, and is not active. Next, youcreate an import job.
Create the import job
Animport job defines the characteristics of the keys itimports, including properties that cannot be changed after the key is imported.
Theprotection level defines whetherkeys imported by this import job will reside in software, in a multi-tenant HSM,in a single-tenant HSM, or in an external key management system. The protectionlevel can't be changed after the key is eventuallyimported.
Theimport method defines thealgorithm used to create the wrapping key that protects imported keys duringtransit from your local system to the target Google Cloud project. Youcan choose a 3072-bit or a 4096- bit RSA key. Unless you have specificrequirements, the 3072-bit wrapping key is recommended.
Note: The import method is different from the algorithm of the key to beimported. The key's algorithm is specified during theimport request.You can create an import job using the gcloud CLI, theGoogle Cloud console, or the Cloud Key Management Service API.
Console
Go to theKey Management page in the Google Cloud console.
Click the name of the target key ring.
Set theProtection level toSoftware,HSM, orSingle-tenant HSM. Use the same protection level as you set for thetarget key.
ClickCreate import job.
In theName field, enter the name for your import job.
From theImport method dropdown, set the import method to either3072 bit RSA or4096 bit RSA.
ClickCreate.
gcloud
To use Cloud KMS on the command line, firstInstall or upgrade to the latest version of Google Cloud CLI.
Use a command like the following to create an import job.
gcloud kms import-jobs createIMPORT_JOB \ --locationLOCATION \ --keyringKEY_RING \ --import-methodIMPORT_METHOD \ --protection-levelPROTECTION_LEVEL
- Use the same key ring and location as the target key.
- Set the protection level to the same value you used for your target key.
- Set the import method to one of the following:
rsa-oaep-3072-sha1-aes-256rsa-oaep-4096-sha1-aes-256rsa-oaep-3072-sha256-aes-256rsa-oaep-4096-sha256-aes-256rsa-oaep-3072-sha256rsa-oaep-4096-sha256
Go
To run this code, firstset up a Go development environment andinstall the Cloud KMS Go SDK.
import("context""fmt""io"kms"cloud.google.com/go/kms/apiv1""cloud.google.com/go/kms/apiv1/kmspb")// createImportJob creates a new job for importing keys into KMS.funccreateImportJob(wio.Writer,parent,idstring)error{// parent := "projects/PROJECT_ID/locations/global/keyRings/my-key-ring"// id := "my-import-job"// Create the client.ctx:=context.Background()client,err:=kms.NewKeyManagementClient(ctx)iferr!=nil{returnfmt.Errorf("failed to create kms client: %w",err)}deferclient.Close()// Build the request.req:=&kmspb.CreateImportJobRequest{Parent:parent,ImportJobId:id,ImportJob:&kmspb.ImportJob{// See allowed values and their descriptions at// https://cloud.google.com/kms/docs/algorithms#protection_levelsProtectionLevel:kmspb.ProtectionLevel_HSM,// See allowed values and their descriptions at// https://cloud.google.com/kms/docs/key-wrapping#import_methodsImportMethod:kmspb.ImportJob_RSA_OAEP_3072_SHA1_AES_256,},}// Call the API.result,err:=client.CreateImportJob(ctx,req)iferr!=nil{returnfmt.Errorf("failed to create import job: %w",err)}fmt.Fprintf(w,"Created import job: %s\n",result.Name)returnnil}Java
To run this code, firstset up a Java development environment andinstall the Cloud KMS Java SDK.
importcom.google.cloud.kms.v1.ImportJob;importcom.google.cloud.kms.v1.ImportJob.ImportMethod;importcom.google.cloud.kms.v1.KeyManagementServiceClient;importcom.google.cloud.kms.v1.KeyRingName;importcom.google.cloud.kms.v1.ProtectionLevel;importjava.io.IOException;publicclassCreateImportJob{publicvoidcreateImportJob()throwsIOException{// TODO(developer): Replace these variables before running the sample.StringprojectId="your-project-id";StringlocationId="us-east1";StringkeyRingId="my-key-ring";Stringid="my-import-job";createImportJob(projectId,locationId,keyRingId,id);}// Create a new import job.publicvoidcreateImportJob(StringprojectId,StringlocationId,StringkeyRingId,Stringid)throwsIOException{// Initialize client that will be used to send requests. This client only// needs to be created once, and can be reused for multiple requests. After// completing all of your requests, call the "close" method on the client to// safely clean up any remaining background resources.try(KeyManagementServiceClientclient=KeyManagementServiceClient.create()){// Build the parent name from the project, location, and key ring.KeyRingNamekeyRingName=KeyRingName.of(projectId,locationId,keyRingId);// Build the import job to create, with parameters.ImportJobimportJob=ImportJob.newBuilder()// See allowed values and their descriptions at// https://cloud.google.com/kms/docs/algorithms#protection_levels.setProtectionLevel(ProtectionLevel.HSM)// See allowed values and their descriptions at// https://cloud.google.com/kms/docs/key-wrapping#import_methods.setImportMethod(ImportMethod.RSA_OAEP_3072_SHA1_AES_256).build();// Create the import job.ImportJobcreatedImportJob=client.createImportJob(keyRingName,id,importJob);System.out.printf("Created import job %s%n",createdImportJob.getName());}}}Node.js
To run this code, firstset up a Node.js development environment andinstall the Cloud KMS Node.js SDK.
//// TODO(developer): Uncomment these variables before running the sample.//// const projectId = 'my-project';// const locationId = 'us-east1';// const keyRingId = 'my-key-ring';// const id = 'my-import-job';// Imports the Cloud KMS libraryconst{KeyManagementServiceClient}=require('@google-cloud/kms');// Instantiates a clientconstclient=newKeyManagementServiceClient();// Build the parent key ring nameconstkeyRingName=client.keyRingPath(projectId,locationId,keyRingId);asyncfunctioncreateImportJob(){const[importJob]=awaitclient.createImportJob({parent:keyRingName,importJobId:id,importJob:{protectionLevel:'HSM',importMethod:'RSA_OAEP_3072_SHA256',},});console.log(`Created import job:${importJob.name}`);returnimportJob;}returncreateImportJob();Python
To run this code, firstset up a Python development environment andinstall the Cloud KMS Python SDK.
fromgoogle.cloudimportkmsdefcreate_import_job(project_id:str,location_id:str,key_ring_id:str,import_job_id:str)->None:""" 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'). """# 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.htmlimport_method=kms.ImportJob.ImportMethod.RSA_OAEP_3072_SHA1_AES_256protection_level=kms.ProtectionLevel.HSMimport_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(f"Created import job:{import_job.name}")API
These examples usecurl as an HTTP client to demonstrate using the API. For more information about access control, seeAccessing the Cloud KMS API.
To create an import job, use theImportJobs.createmethod:
curl "https://cloudkms.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/keyRings/KEY_RING/importJobs?import_job_id=IMPORT_JOB_ID" \ --request "POST" \ --header "authorization: BearerTOKEN" \ --header "content-type: application/json" \ --data '{"import_method": "IMPORT_METHOD", "protection_level": "PROTECTION_LEVEL"}'Replace the following:
- IMPORT_METHOD: a supportedkey-wrapping method.
- PROTECTION_LEVEL: theprotectionlevel of the key versionsimported by this import job.
Checking the state of the import job
The initial state for an import job isPENDING_GENERATION. When the state isACTIVE, you can use it to import keys.
An import job expires after three days. If the import job is expired, you mustcreate a new one.
You can check the status of an import job using the Google Cloud CLI, theGoogle Cloud console, or the Cloud Key Management Service API.
Console
Go to theKey Management page in the Google Cloud console.
Click the name of the key ring that contains your import job.
Click theImport Jobs tab at the top of the page.
The state will be visible underStatus next to your import job'sname.
gcloud
To use Cloud KMS on the command line, firstInstall or upgrade to the latest version of Google Cloud CLI.
When an import job is active, you can use it to import keys. This maytake a few minutes. Use this command to verify that the import job isactive. Use the location and keyring where you created the import job.
gcloud kms import-jobs describeIMPORT_JOB \ --locationLOCATION \ --keyringKEY_RING \ --format="value(state)"
The output is similar to the following:
state: ACTIVE
Go
To run this code, firstset up a Go development environment andinstall the Cloud KMS Go SDK.
import("context""fmt""io"kms"cloud.google.com/go/kms/apiv1""cloud.google.com/go/kms/apiv1/kmspb")// checkStateImportJob checks the state of an ImportJob in KMS.funccheckStateImportJob(wio.Writer,namestring)error{// name := "projects/PROJECT_ID/locations/global/keyRings/my-key-ring/importJobs/my-import-job"// Create the client.ctx:=context.Background()client,err:=kms.NewKeyManagementClient(ctx)iferr!=nil{returnfmt.Errorf("failed to create kms client: %w",err)}deferclient.Close()// Call the API.result,err:=client.GetImportJob(ctx,&kmspb.GetImportJobRequest{Name:name,})iferr!=nil{returnfmt.Errorf("failed to get import job: %w",err)}fmt.Fprintf(w,"Current state of import job %q: %s\n",result.Name,result.State)returnnil}Java
To run this code, firstset up a Java development environment andinstall the Cloud KMS Java SDK.
importcom.google.cloud.kms.v1.ImportJob;importcom.google.cloud.kms.v1.ImportJobName;importcom.google.cloud.kms.v1.KeyManagementServiceClient;importjava.io.IOException;publicclassCheckStateImportJob{publicvoidcheckStateImportJob()throwsIOException{// TODO(developer): Replace these variables before running the sample.StringprojectId="your-project-id";StringlocationId="us-east1";StringkeyRingId="my-key-ring";StringimportJobId="my-import-job";checkStateImportJob(projectId,locationId,keyRingId,importJobId);}// Check the state of an import job in Cloud KMS.publicvoidcheckStateImportJob(StringprojectId,StringlocationId,StringkeyRingId,StringimportJobId)throwsIOException{// Initialize client that will be used to send requests. This client only// needs to be created once, and can be reused for multiple requests. After// completing all of your requests, call the "close" method on the client to// safely clean up any remaining background resources.try(KeyManagementServiceClientclient=KeyManagementServiceClient.create()){// Build the parent name from the project, location, and key ring.ImportJobNameimportJobName=ImportJobName.of(projectId,locationId,keyRingId,importJobId);// Retrieve the state of an existing import job.ImportJobimportJob=client.getImportJob(importJobName);System.out.printf("Current state of import job %s: %s%n",importJob.getName(),importJob.getState());}}}Node.js
To run this code, firstset up a Node.js development environment andinstall the Cloud KMS Node.js SDK.
//// TODO(developer): Uncomment these variables before running the sample.//// const projectId = 'my-project';// const locationId = 'us-east1';// const keyRingId = 'my-key-ring';// const importJobId = 'my-import-job';// Imports the Cloud KMS libraryconst{KeyManagementServiceClient}=require('@google-cloud/kms');// Instantiates a clientconstclient=newKeyManagementServiceClient();// Build the import job nameconstimportJobName=client.importJobPath(projectId,locationId,keyRingId,importJobId);asyncfunctioncheckStateImportJob(){const[importJob]=awaitclient.getImportJob({name:importJobName,});console.log(`Current state of import job${importJob.name}:${importJob.state}`);returnimportJob;}returncheckStateImportJob();Python
To run this code, firstset up a Python development environment andinstall the Cloud KMS Python SDK.
fromgoogle.cloudimportkmsdefcheck_state_import_job(project_id:str,location_id:str,key_ring_id:str,import_job_id:str)->None:""" 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'). """# 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(f"Current state of import job{import_job.name}:{import_job.state}")API
These examples usecurl as an HTTP client to demonstrate using the API. For more information about access control, seeAccessing the Cloud KMS API.
To check the state of an import job, use theImportJobs.getmethod:
curl "https://cloudkms.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/keyRings/KEY_RING/importJobs/IMPORT_JOB_ID" \ --request "GET" \ --header "authorization: BearerTOKEN"
As soon as the import job is active, you canmake a request to import a key.
Preventing modification of import jobs
The import job determines many characteristics of the imported key, includingthe key's algorithm and whether an imported key is an HSM key or a softwarekey. You can configure IAM permissions to prevent users fromcreating import jobs, while allowing them touse import jobs to importkeys.
- Grant the
importjobs.createpermission only to key administrators. - Grant the
importjobs.useToImportpermission for a specific import job tothe operator who will use that job to import keys. - When you create the import job, specify the protection level and algorithmfor key versions imported using it.
Until the import job expires, users who have theimportjobs.useToImport anddo not have theimportjobs.create permission for a given import job can importkeys, but cannot modify the characteristics of the import job.
Import the key
Afterchecking the status of the import job, you can makean import request.
You use different flags to make the import request, depending on whether youwant the Google Cloud CLI to wrap your key automatically or if you have alreadywrapped your key manually.
Regardless of whether you wrapped your key manually or automatically, you mustset thealgorithm to a supported algorithm that matchesthe length of the actual key to be imported, and specifies the key's purpose.
Keys with purpose
ENCRYPT_DECRYPTuse thegoogle-symmetric-encryptionalgorithm, and have a length of 32.Keys with purpose
ASYMMETRIC_DECRYPTorASYMMETRIC_SIGNsupport a varietyof algorithms and lengths.A key's purpose cannot be changed after the key is created, but subsequent keyversions 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 Google Cloud CLI.Use a command like the following. Set--target-key-file to the location of theunwrapped key to wrap and import. Do not set--wrapped-key-file.
You can optionally set the--public-key-file flag to the location where the public key has already beendownloaded. When importing a large number of keys, this prevents the public keyfrom being downloaded during each import. For example, you could write a scriptthat downloaded the public key once, then provided its location when importingeach key.
gcloud kms keys versions import \ --import-jobIMPORT_JOB \ --locationLOCATION \ --keyringKEY_RING \ --keyKEY_NAME \ --algorithmALGORITHM \--target-key-filePATH_TO_UNWRAPPED_KEY
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 thetarget key.
Importing a manually-wrapped key
Use the instructions in this section to import a key thatyou have wrapped manually. Set--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 beendownloaded. When importing a large number of keys, this prevents the public keyfrom being downloaded during each import. For example, you could write a scriptthat downloaded the public key once, then provided its location when importingeach key.
Console
Open theKey Management page in theGoogle Cloud console.
Click the name of the key ring that contains your import job. The targetkey is shown, along with any other keys on the key ring.
Click the name of the target key, then clickImport key version.
Select your import job from theSelect import job dropdown.
In theUpload the wrapped key selector, select the key that you havealreadywrapped.
If you are importing an asymmetric key, select the algorithm from theAlgorithm dropdown. YourImport key version page should looksimilar to:

ClickImport.
gcloud
To use Cloud KMS on the command line, firstInstall or upgrade to the latest version of Google Cloud CLI.
Use a command like the following.
gcloud kms keys versions import \ --import-jobIMPORT_JOB \ --locationLOCATION \ --keyringKEY_RING \ --keyKEY_NAME \ --algorithmALGORITHM \--wrapped-key-filePATH_TO_WRAPPED_KEY
For more information, see the output of thegcloud kms keys versions import --help command.
Go
To run this code, firstset up a Go development environment andinstall the Cloud KMS Go SDK.
import("context""crypto/ecdsa""crypto/elliptic""crypto/rand""crypto/rsa""crypto/sha1""crypto/x509""encoding/pem""fmt""io"kms"cloud.google.com/go/kms/apiv1""cloud.google.com/go/kms/apiv1/kmspb""github.com/google/tink/go/kwp/subtle")// importManuallyWrappedKey wraps key material and imports it into KMS.funcimportManuallyWrappedKey(wio.Writer,importJobName,cryptoKeyNamestring)error{// importJobName := "projects/PROJECT_ID/locations/global/keyRings/my-key-ring/importJobs/my-import-job"// cryptoKeyName := "projects/PROJECT_ID/locations/global/keyRings/my-key-ring/cryptoKeys/my-imported-key"// Generate a ECDSA keypair, and format the private key as PKCS #8 DER.key,err:=ecdsa.GenerateKey(elliptic.P256(),rand.Reader)iferr!=nil{returnfmt.Errorf("failed to generate keypair: %w",err)}keyBytes,err:=x509.MarshalPKCS8PrivateKey(key)iferr!=nil{returnfmt.Errorf("failed to format private key: %w",err)}// Create the client.ctx:=context.Background()client,err:=kms.NewKeyManagementClient(ctx)iferr!=nil{returnfmt.Errorf("failed to create kms client: %w",err)}deferclient.Close()// Generate a temporary 32-byte key for AES-KWP and wrap the key material.kwpKey:=make([]byte,32)if_,err:=rand.Read(kwpKey);err!=nil{returnfmt.Errorf("failed to generate AES-KWP key: %w",err)}kwp,err:=subtle.NewKWP(kwpKey)iferr!=nil{returnfmt.Errorf("failed to create KWP cipher: %w",err)}wrappedTarget,err:=kwp.Wrap(keyBytes)iferr!=nil{returnfmt.Errorf("failed to wrap target key with KWP: %w",err)}// Retrieve the public key from the import job.importJob,err:=client.GetImportJob(ctx,&kmspb.GetImportJobRequest{Name:importJobName,})iferr!=nil{returnfmt.Errorf("failed to retrieve import job: %w",err)}pubBlock,_:=pem.Decode([]byte(importJob.PublicKey.Pem))pubAny,err:=x509.ParsePKIXPublicKey(pubBlock.Bytes)iferr!=nil{returnfmt.Errorf("failed to parse import job public key: %w",err)}pub,ok:=pubAny.(*rsa.PublicKey)if!ok{returnfmt.Errorf("unexpected public key type %T, want *rsa.PublicKey",pubAny)}// Wrap the KWP key using the import job key.wrappedWrappingKey,err:=rsa.EncryptOAEP(sha1.New(),rand.Reader,pub,kwpKey,nil)iferr!=nil{returnfmt.Errorf("failed to wrap KWP key: %w",err)}// Concatenate the wrapped KWP key and the wrapped target key.combined:=append(wrappedWrappingKey,wrappedTarget...)// Build the request.req:=&kmspb.ImportCryptoKeyVersionRequest{Parent:cryptoKeyName,ImportJob:importJobName,Algorithm:kmspb.CryptoKeyVersion_EC_SIGN_P256_SHA256,WrappedKey:combined,}// Call the API.result,err:=client.ImportCryptoKeyVersion(ctx,req)iferr!=nil{returnfmt.Errorf("failed to import crypto key version: %w",err)}fmt.Fprintf(w,"Created crypto key version: %s\n",result.Name)returnnil}Java
To run this code, firstset up a Java development environment andinstall the Cloud KMS Java SDK.
importcom.google.cloud.kms.v1.CryptoKeyName;importcom.google.cloud.kms.v1.CryptoKeyVersion;importcom.google.cloud.kms.v1.ImportCryptoKeyVersionRequest;importcom.google.cloud.kms.v1.ImportJob;importcom.google.cloud.kms.v1.ImportJobName;importcom.google.cloud.kms.v1.KeyManagementServiceClient;importcom.google.crypto.tink.subtle.Kwp;importcom.google.protobuf.ByteString;importjava.io.IOException;importjava.security.GeneralSecurityException;importjava.security.KeyFactory;importjava.security.KeyPair;importjava.security.KeyPairGenerator;importjava.security.PublicKey;importjava.security.SecureRandom;importjava.security.spec.ECGenParameterSpec;importjava.security.spec.MGF1ParameterSpec;importjava.security.spec.X509EncodedKeySpec;importjava.util.Base64;importjavax.crypto.Cipher;importjavax.crypto.spec.OAEPParameterSpec;importjavax.crypto.spec.PSource;publicclassImportManuallyWrappedKey{publicvoidimportManuallyWrappedKey()throwsGeneralSecurityException,IOException{// TODO(developer): Replace these variables before running the sample.StringprojectId="your-project-id";StringlocationId="us-east1";StringkeyRingId="my-key-ring";StringcryptoKeyId="my-crypto-key";StringimportJobId="my-import-job";importManuallyWrappedKey(projectId,locationId,keyRingId,cryptoKeyId,importJobId);}// Generates and imports local key material into Cloud KMS.publicvoidimportManuallyWrappedKey(StringprojectId,StringlocationId,StringkeyRingId,StringcryptoKeyId,StringimportJobId)throwsGeneralSecurityException,IOException{// Generate a new ECDSA keypair, and format the private key as PKCS #8 DER.KeyPairGeneratorgenerator=KeyPairGenerator.getInstance("EC");generator.initialize(newECGenParameterSpec("secp256r1"));KeyPairkp=generator.generateKeyPair();byte[]privateBytes=kp.getPrivate().getEncoded();// Initialize client that will be used to send requests. This client only// needs to be created once, and can be reused for multiple requests. After// completing all of your requests, call the "close" method on the client to// safely clean up any remaining background resources.try(KeyManagementServiceClientclient=KeyManagementServiceClient.create()){// Build the crypto key and import job names from the project, location,// key ring, and ID.finalCryptoKeyNamecryptoKeyName=CryptoKeyName.of(projectId,locationId,keyRingId,cryptoKeyId);finalImportJobNameimportJobName=ImportJobName.of(projectId,locationId,keyRingId,importJobId);// Generate a temporary 32-byte key for AES-KWP and wrap the key material.byte[]kwpKey=newbyte[32];newSecureRandom().nextBytes(kwpKey);Kwpkwp=newKwp(kwpKey);finalbyte[]wrappedTargetKey=kwp.wrap(privateBytes);// Retrieve the public key from the import job.ImportJobimportJob=client.getImportJob(importJobName);StringpublicKeyStr=importJob.getPublicKey().getPem();// Manually convert PEM to DER. :-(publicKeyStr=publicKeyStr.replace("-----BEGIN PUBLIC KEY-----","");publicKeyStr=publicKeyStr.replace("-----END PUBLIC KEY-----","");publicKeyStr=publicKeyStr.replaceAll("\n","");byte[]publicKeyBytes=Base64.getDecoder().decode(publicKeyStr);PublicKeypublicKey=KeyFactory.getInstance("RSA").generatePublic(newX509EncodedKeySpec(publicKeyBytes));// Wrap the KWP key using the import job key.Ciphercipher=Cipher.getInstance("RSA/ECB/OAEPWithSHA-1AndMGF1Padding");cipher.init(Cipher.ENCRYPT_MODE,publicKey,newOAEPParameterSpec("SHA-1","MGF1",MGF1ParameterSpec.SHA1,PSource.PSpecified.DEFAULT));byte[]wrappedWrappingKey=cipher.doFinal(kwpKey);// Concatenate the wrapped KWP key and the wrapped target key.ByteStringcombinedWrappedKeys=ByteString.copyFrom(wrappedWrappingKey).concat(ByteString.copyFrom(wrappedTargetKey));// Import the wrapped key material.CryptoKeyVersionversion=client.importCryptoKeyVersion(ImportCryptoKeyVersionRequest.newBuilder().setParent(cryptoKeyName.toString()).setImportJob(importJobName.toString()).setAlgorithm(CryptoKeyVersion.CryptoKeyVersionAlgorithm.EC_SIGN_P256_SHA256).setRsaAesWrappedKey(combinedWrappedKeys).build());System.out.printf("Imported: %s%n",version.getName());}}}Node.js
To run this code, firstset up a Node.js development environment andinstall the Cloud KMS Node.js SDK.
//// TODO(developer): Uncomment these variables before running the sample.//// const projectId = 'my-project';// const locationId = 'us-east1';// const keyRingId = 'my-key-ring';// const cryptoKeyId = 'my-imported-key';// const importJobId = 'my-import-job';// Imports the Cloud KMS libraryconst{KeyManagementServiceClient}=require('@google-cloud/kms');// Instantiates a clientconstclient=newKeyManagementServiceClient();// Build the crypto key and importjob resource namesconstcryptoKeyName=client.cryptoKeyPath(projectId,locationId,keyRingId,cryptoKeyId);constimportJobName=client.importJobPath(projectId,locationId,keyRingId,importJobId);asyncfunctionwrapAndImportKey(){// Generate a 32-byte key to import.constcrypto=require('crypto');consttargetKey=crypto.randomBytes(32);const[importJob]=awaitclient.getImportJob({name:importJobName});// Wrap the target key using the import job keyconstwrappedTargetKey=crypto.publicEncrypt({key:importJob.publicKey.pem,oaepHash:'sha256',padding:crypto.constants.RSA_PKCS1_OAEP_PADDING,},targetKey);// Import the target key versionconst[version]=awaitclient.importCryptoKeyVersion({parent:cryptoKeyName,importJob:importJobName,algorithm:'GOOGLE_SYMMETRIC_ENCRYPTION',wrappedKey:wrappedTargetKey,});console.log(`Imported key version:${version.name}`);returnversion;}returnwrapAndImportKey();Python
To run this code, firstset up a Python development environment andinstall the Cloud KMS Python SDK.
importos# Import the client library and Python standard cryptographic libraries.fromcryptography.hazmatimportbackendsfromcryptography.hazmat.primitivesimporthashesfromcryptography.hazmat.primitivesimportkeywrapfromcryptography.hazmat.primitivesimportserializationfromcryptography.hazmat.primitives.asymmetricimportecfromcryptography.hazmat.primitives.asymmetricimportpaddingfromgoogle.cloudimportkmsdefimport_manually_wrapped_key(project_id:str,location_id:str,key_ring_id:str,crypto_key_id:str,import_job_id:str,)->None:""" 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'). """# 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(f"Generated key bytes:{formatted_key!r}")# 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(f"Imported:{import_job.name}")API
These examples usecurl as an HTTP client to demonstrate using the API. For more information about access control, seeAccessing the Cloud KMS API.
Use thecryptoKeyVersions.import method toimport a key.
curl "https://cloudkms.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/keyRings/KEY_RING/cryptoKeys/KEY_NAME/cryptoKeyVersions:import" \ --request "POST" \ --header "authorization: BearerTOKEN" \ --header "content-type: application/json" \ --data '{"importJob": "IMPORT_JOB_ID", "algorithm": "ALGORITHM", "wrappedKey": "WRAPPED_KEY"}'Replace the following:
IMPORT_JOB_ID: the full resource name of the corresponding importjob.
ALGORITHM: the
algorithmof thekey being imported, which is of typeCryptoKeyVersionAlgorithm.WRAPPED_KEY: the manually-wrapped key in base64 format.
The key-import request is initiated. You canmonitor its status.
Check the state of the imported key version
The initial state for an imported key version isPENDING_IMPORT. When thestate isENABLED, the key version has been imported successfully. If theimport fails, the status isIMPORT_FAILED.
You can check the status of an import request using the Google Cloud CLI, theGoogle Cloud console, or the Cloud Key Management Service API.
Console
Open theKey Management page in theGoogle Cloud console.
Click the name of the key ring that contains your import job.
Click theImport Jobs tab at the top of the page.
The state will be visible underStatus next to your import job'sname.
gcloud
To use Cloud KMS on the command line, firstInstall or upgrade to the latest version of Google Cloud CLI.
Use theversions list command to check the state. Use the samelocation, target key ring, and target key that you created earlier in thistopic.
gcloud kms keys versions list \ --keyringKEY_RING \ --locationLOCATION \ --keyKEY_NAME
Go
To run this code, firstset up a Go development environment andinstall the Cloud KMS Go SDK.
import("context""fmt""io"kms"cloud.google.com/go/kms/apiv1""cloud.google.com/go/kms/apiv1/kmspb")// checkStateImportedKey checks the state of a CryptoKeyVersion in KMS.funccheckStateImportedKey(wio.Writer,namestring)error{// name := "projects/PROJECT_ID/locations/global/keyRings/my-key-ring/cryptoKeys/my-imported-key/cryptoKeyVersions/1"// Create the client.ctx:=context.Background()client,err:=kms.NewKeyManagementClient(ctx)iferr!=nil{returnfmt.Errorf("failed to create kms client: %w",err)}deferclient.Close()// Call the API.result,err:=client.GetCryptoKeyVersion(ctx,&kmspb.GetCryptoKeyVersionRequest{Name:name,})iferr!=nil{returnfmt.Errorf("failed to get crypto key version: %w",err)}fmt.Fprintf(w,"Current state of crypto key version %q: %s\n",result.Name,result.State)returnnil}Java
To run this code, firstset up a Java development environment andinstall the Cloud KMS Java SDK.
importcom.google.cloud.kms.v1.CryptoKeyVersion;importcom.google.cloud.kms.v1.CryptoKeyVersionName;importcom.google.cloud.kms.v1.KeyManagementServiceClient;importjava.io.IOException;publicclassCheckStateImportedKey{publicvoidcheckStateImportedKey()throwsIOException{// TODO(developer): Replace these variables before running the sample.StringprojectId="your-project-id";StringlocationId="us-east1";StringkeyRingId="my-key-ring";StringcryptoKeyId="my-crypto-key";StringcryptoKeyVersionId="1";checkStateImportedKey(projectId,locationId,keyRingId,cryptoKeyId,cryptoKeyVersionId);}// Check the state of an imported key in Cloud KMS.publicvoidcheckStateImportedKey(StringprojectId,StringlocationId,StringkeyRingId,StringcryptoKeyId,StringcryptoKeyVersionId)throwsIOException{// Initialize client that will be used to send requests. This client only// needs to be created once, and can be reused for multiple requests. After// completing all of your requests, call the "close" method on the client to// safely clean up any remaining background resources.try(KeyManagementServiceClientclient=KeyManagementServiceClient.create()){// Build the version name from its path components.CryptoKeyVersionNameversionName=CryptoKeyVersionName.of(projectId,locationId,keyRingId,cryptoKeyId,cryptoKeyVersionId);// Retrieve the state of an existing version.CryptoKeyVersionversion=client.getCryptoKeyVersion(versionName);System.out.printf("Current state of crypto key version %s: %s%n",version.getName(),version.getState());}}}Node.js
To run this code, firstset up a Node.js development environment andinstall the Cloud KMS Node.js SDK.
//// TODO(developer): Uncomment these variables before running the sample.//// const projectId = 'my-project';// const locationId = 'us-east1';// const keyRingId = 'my-key-ring';// const cryptoKeyId = 'my-imported-key';// const cryptoKeyVersionId = '1';// Imports the Cloud KMS libraryconst{KeyManagementServiceClient}=require('@google-cloud/kms');// Instantiates a clientconstclient=newKeyManagementServiceClient();// Build the key version nameconstkeyVersionName=client.cryptoKeyVersionPath(projectId,locationId,keyRingId,cryptoKeyId,cryptoKeyVersionId);asyncfunctioncheckStateCryptoKeyVersion(){const[keyVersion]=awaitclient.getCryptoKeyVersion({name:keyVersionName,});console.log(`Current state of key version${keyVersion.name}:${keyVersion.state}`);returnkeyVersion;}returncheckStateCryptoKeyVersion();Python
To run this code, firstset up a Python development environment andinstall the Cloud KMS Python SDK.
fromgoogle.cloudimportkmsdefcheck_state_imported_key(project_id:str,location_id:str,key_ring_id:str,import_job_id:str)->None:""" 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'). """# 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(f"Current state of import job{import_job.name}:{import_job.state}")API
These examples usecurl as an HTTP client to demonstrate using the API. For more information about access control, seeAccessing the Cloud KMS API.
Call theImportJob.get method and check thestate field. Ifstate isPENDING_GENERATION, the import job is still being created.Periodically recheck the state until it isACTIVE.
After the initial key version is imported, the key's status changes toActive. For symmetric keys, you must set the imported key version as theprimary 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 forasymmetric keys. An asymmetric key does not have a primary version. You mustuse the Google Cloud CLI to set the primary version.
Tip:KEY_VERSION is usually1, because the imported version is thefirst version of the key.gcloud kms keys set-primary-versionKEY_NAME\ --location=LOCATION\ --keyring=KEY_RING\ --version=KEY_VERSION
Re-import a previously destroyed key
Cloud Key Management Service supports key re-import, which allows you to restore apreviously imported key version inDESTROYED orIMPORT_FAILED state toENABLED state by providing the original key material. If no original keymaterial has ever been imported due to initial import failure, any key materialmay be supplied.
Restrictions
- Only previously imported
CryptoKeyVersionscan be re-imported. - Re-imported key material must match the original key material exactly if theversion was previously successfully imported.
CryptoKeyVersionsdestroyed prior to the release of this feature can't bere-imported. Thereimport_eligiblefield of theCryptoKeyVersionistrueif the version is eligible for re-import andfalseif it isn't.
Software and Cloud HSM keys can be re-imported, but external keys can'tbe re-imported.
Re-importing a destroyed key
Create anImportJob for re-import by following the steps inCreate the import job. You may use either an existingImportJob or a newImportJob as long as the protection level matches theoriginal protection level.
Console
Go to theKey Management page in the Google Cloud console.
Click the name of the key ring that contains the key whose key version you will re-import.
Click the key whose key version you want to re-import.
Click the three dots next to the key version you want to re-import.
SelectRe-import key version
Select your import job from theSelect import job dropdown.
In theUpload the wrapped key selector, select the key that you havealreadywrapped. This key must match the original key material.
ClickRe-Import.
gcloud
To use Cloud KMS on the command line, firstInstall or upgrade to the latest version of Google Cloud CLI.
Re-import the key version using the original key material.
gcloud kms keys versions import \--locationLOCATION \--keyringKEY_RING \--keyKEY_NAME \--versionKEY_VERSION \--algorithmALGORITHM \--import-jobIMPORT_JOB \--target-key-filePATH_TO_KEY \
API
These examples usecurl as an HTTP client to demonstrate using the API. For more information about access control, seeAccessing the Cloud KMS API.
In the request body of the
cryptoKeyVersions.importmethod, set thecryptoKeyVersionfield to the key version name of the version being imported. This must be a child of the crypto key.In the request body, set the
algorithmfield to the algorithm of the key being imported.This value must match the algorithm of the original key version. Thealgorithmfieldis of typeCryptoKeyVersionAlgorithm.In the request body, set the
wrappedKeyMaterialfield tothe key material that you that you have alreadywrapped.Call the
cryptoKeyVersions.importmethod. ThecryptoKeyVersions.importresponse is of typeCryptoKeyVersion.When a key is successfully imported, its state isENABLEDand you can use it in Cloud KMS.
What's next
- Verify an imported key. After you confirmthat the imported key material is identical to the original key, you can usethe key for signing or to protect data.
- Troubleshoot a failed key import.
Except as otherwise noted, the content of this page is licensed under theCreative Commons Attribution 4.0 License, and code samples are licensed under theApache 2.0 License. For details, see theGoogle Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.
Last updated 2026-02-18 UTC.