Create a key Stay organized with collections Save and categorize content based on your preferences.
This page shows how to create a key in Cloud KMS. A key can be asymmetric or asymmetric encryption key, an asymmetric signing key, or a MACsigning key.
When you create a key, you add it to a key ring in a specificCloud KMS location. You cancreate a new keyring or use an existing one.In this page, you generate a new Cloud KMS or Cloud HSM keyand add it to an existing key ring.To create a Cloud EKM key, seeCreate an externalkey. To import a Cloud KMS or Cloud HSM key,seeImport a key.
Before you begin
Before completing the tasks on this page, you need the following:
- A Google Cloud project resource to contain your Cloud KMS resources. We recommend using a separate project for your Cloud KMS resources that does not contain any other Google Cloud resources.
- The name and location of the key ring where you want to create your key. Choose a key ring in a location that is near your other resources and that supports your chosenprotection level. To view available locations and the protection levels that they support, seeCloud KMS locations. To create a key ring, seeCreate a key ring.
- Optional: To use the gcloud CLI, prepare your environment.
In the Google Cloud console, activate Cloud Shell.
Required roles
To get the permissions that you need to create keys, ask your administrator to grant you the following IAM roles on the project or a parent resource:
- Cloud KMS Admin (
roles/cloudkms.admin) - To create single-tenant HSM keys:Cloud KMS single-tenant HSM Key Creator (
roles/cloudkms.hsmSingleTenantKeyCreator)
For more information about granting roles, seeManage access to projects, folders, and organizations.
These predefined roles contain the permissions required to create keys. To see the exact permissions that are required, expand theRequired permissions section:
Required permissions
The following permissions are required to create keys:
cloudkms.cryptoKeys.createcloudkms.cryptoKeys.getcloudkms.cryptoKeys.listcloudkms.cryptoKeyVersions.createcloudkms.cryptoKeyVersions.getcloudkms.cryptoKeyVersions.listcloudkms.keyRings.getcloudkms.keyRings.listcloudkms.locations.getcloudkms.locations.listresourcemanager.projects.get- To retrieve a public key:
cloudkms.cryptoKeyVersions.viewPublicKey - To create single-tenant HSM keys:
cloudkms.singleTenantHsmInstances.getcloudkms.singleTenantHsmInstances.use
You might also be able to get these permissions withcustom roles or otherpredefined roles.
Caution: TheCloud KMS Adminrole contains permissions for keymaintenance and key version destruction. To protect your Cloud KMSresources, this role should only be assigned to individuals responsible for keyadministration.Create a symmetric encryption key
Console
In the Google Cloud console, go to theKey Management page.
Click the name of the key ring for which you will create a key.
ClickCreate key.
ForKey name, enter a 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, selectGenerated key.
ForPurpose, selectSymmetric encrypt/decrypt.
Accept the default values forRotation period andStarting on.
ClickCreate.
gcloud
To use Cloud KMS on the command line, firstInstall or upgrade to the latest version of Google Cloud CLI.
To create a software or Multi-tenant Cloud HSM key, use thekms keys createcommand:
gcloud kms keys createKEY_NAME \ --keyringKEY_RING \ --locationLOCATION \ --purpose "encryption" \ --protection-level "PROTECTION_LEVEL"
Replace the following:
KEY_NAME: the name of the key.KEY_RING: the name of the key ring that contains the key.LOCATION: the Cloud KMS location of the key ring.PROTECTION_LEVEL: the protection level to usefor the key—for example,softwareorhsm. You can omitthe--protection-levelflag forsoftwarekeys.
For information on all flags and possible values, run the command with the--help flag.
--crypto-key-backend flag to thekms keys create command:gcloud kms keys createKEY_NAME \ --keyringKEY_RING \ --locationLOCATION \ --purpose "encryption" \ --protection-level "hsm-single-tenant" \ --crypto-key-backend="projects/INSTANCE_PROJECT/locations/LOCATION/singleTenantHsmInstances/INSTANCE_NAME"
Replace the following:
INSTANCE_PROJECT: the identifier of the project whereyour Single-tenant Cloud HSM instance exists.INSTANCE_NAME: the name of the Single-tenant Cloud HSMinstance where you want to create the key. For more information aboutSingle-tenant Cloud HSM instances, seeCreate and manage a Single-tenant Cloud HSMinstance.
For information on all flags and possible values, run the command with the--help flag.
C#
To run this code, firstset up a C# development environment andinstall the Cloud KMS C# SDK.
usingGoogle.Cloud.Kms.V1;publicclassCreateKeySymmetricEncryptDecryptSample{publicCryptoKeyCreateKeySymmetricEncryptDecrypt(stringprojectId="my-project",stringlocationId="us-east1",stringkeyRingId="my-key-ring",stringid="my-symmetric-encryption-key"){// Create the client.KeyManagementServiceClientclient=KeyManagementServiceClient.Create();// Build the parent key ring name.KeyRingNamekeyRingName=newKeyRingName(projectId,locationId,keyRingId);// Build the key.CryptoKeykey=newCryptoKey{Purpose=CryptoKey.Types.CryptoKeyPurpose.EncryptDecrypt,VersionTemplate=newCryptoKeyVersionTemplate{Algorithm=CryptoKeyVersion.Types.CryptoKeyVersionAlgorithm.GoogleSymmetricEncryption,}};// Call the API.CryptoKeyresult=client.CreateCryptoKey(keyRingName,id,key);// Return the result.returnresult;}}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")// createKeySymmetricEncryptDecrypt creates a new symmetric encrypt/decrypt key// on Cloud KMS.funccreateKeySymmetricEncryptDecrypt(wio.Writer,parent,idstring)error{// parent := "projects/my-project/locations/us-east1/keyRings/my-key-ring"// id := "my-symmetric-encryption-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_ENCRYPT_DECRYPT,VersionTemplate:&kmspb.CryptoKeyVersionTemplate{Algorithm:kmspb.CryptoKeyVersion_GOOGLE_SYMMETRIC_ENCRYPTION,},},}// 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.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;importjava.io.IOException;publicclassCreateKeySymmetricEncryptDecrypt{publicvoidcreateKeySymmetricEncryptDecrypt()throwsIOException{// TODO(developer): Replace these variables before running the sample.StringprojectId="your-project-id";StringlocationId="us-east1";StringkeyRingId="my-key-ring";Stringid="my-key";createKeySymmetricEncryptDecrypt(projectId,locationId,keyRingId,id);}// Create a new key that is used for symmetric encryption and decryption.publicvoidcreateKeySymmetricEncryptDecrypt(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 symmetric key to create.CryptoKeykey=CryptoKey.newBuilder().setPurpose(CryptoKeyPurpose.ENCRYPT_DECRYPT).setVersionTemplate(CryptoKeyVersionTemplate.newBuilder().setAlgorithm(CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION)).build();// Create the key.CryptoKeycreatedKey=client.createCryptoKey(keyRingName,id,key);System.out.printf("Created symmetric 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-symmetric-encryption-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);asyncfunctioncreateKeySymmetricEncryptDecrypt(){const[key]=awaitclient.createCryptoKey({parent:keyRingName,cryptoKeyId:id,cryptoKey:{purpose:'ENCRYPT_DECRYPT',versionTemplate:{algorithm:'GOOGLE_SYMMETRIC_ENCRYPTION',},},});console.log(`Created symmetric key:${key.name}`);returnkey;}returncreateKeySymmetricEncryptDecrypt();PHP
To run this code, first learn aboutusing PHP on Google Cloud andinstall the Cloud KMS PHP SDK.
use Google\Cloud\Kms\V1\Client\KeyManagementServiceClient;use Google\Cloud\Kms\V1\CreateCryptoKeyRequest;use Google\Cloud\Kms\V1\CryptoKey;use Google\Cloud\Kms\V1\CryptoKey\CryptoKeyPurpose;use Google\Cloud\Kms\V1\CryptoKeyVersion\CryptoKeyVersionAlgorithm;use Google\Cloud\Kms\V1\CryptoKeyVersionTemplate;function create_key_symmetric_encrypt_decrypt( string $projectId = 'my-project', string $locationId = 'us-east1', string $keyRingId = 'my-key-ring', string $id = 'my-symmetric-key'): CryptoKey { // Create the Cloud KMS client. $client = new KeyManagementServiceClient(); // Build the parent key ring name. $keyRingName = $client->keyRingName($projectId, $locationId, $keyRingId); // Build the key. $key = (new CryptoKey()) ->setPurpose(CryptoKeyPurpose::ENCRYPT_DECRYPT) ->setVersionTemplate((new CryptoKeyVersionTemplate()) ->setAlgorithm(CryptoKeyVersionAlgorithm::GOOGLE_SYMMETRIC_ENCRYPTION) ); // Call the API. $createCryptoKeyRequest = (new CreateCryptoKeyRequest()) ->setParent($keyRingName) ->setCryptoKeyId($id) ->setCryptoKey($key); $createdKey = $client->createCryptoKey($createCryptoKeyRequest); printf('Created symmetric key: %s' . PHP_EOL, $createdKey->getName()); return $createdKey;}Python
To run this code, firstset up a Python development environment andinstall the Cloud KMS Python SDK.
fromgoogle.cloudimportkmsdefcreate_key_symmetric_encrypt_decrypt(project_id:str,location_id:str,key_ring_id:str,key_id:str)->kms.CryptoKey:""" Creates a new symmetric encryption/decryption key 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'). key_id (string): ID of the key to create (e.g. 'my-symmetric-key'). Returns: CryptoKey: Cloud KMS key. """# Create the client.client=kms.KeyManagementServiceClient()# Build the parent key ring name.key_ring_name=client.key_ring_path(project_id,location_id,key_ring_id)# Build the key.purpose=kms.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPTalgorithm=(kms.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION)key={"purpose":purpose,"version_template":{"algorithm":algorithm,},}# Call the API.created_key=client.create_crypto_key(request={"parent":key_ring_name,"crypto_key_id":key_id,"crypto_key":key})print(f"Created symmetric key:{created_key.name}")returncreated_keyRuby
To run this code, firstset up a Ruby development environment andinstall the Cloud KMS Ruby SDK.
# TODO(developer): uncomment these values before running the sample.# project_id = "my-project"# location_id = "us-east1"# key_ring_id = "my-key-ring"# id = "my-symmetric-key"# Require the library.require"google/cloud/kms"# Create the client.client=Google::Cloud::Kms.key_management_service# Build the parent key ring name.key_ring_name=client.key_ring_pathproject:project_id,location:location_id,key_ring:key_ring_id# Build the key.key={purpose::ENCRYPT_DECRYPT,version_template:{algorithm::GOOGLE_SYMMETRIC_ENCRYPTION}}# Call the API.created_key=client.create_crypto_keyparent:key_ring_name,crypto_key_id:id,crypto_key:keyputs"Created symmetric 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.
To create a software or Multi-tenant Cloud HSM key, use theCryptoKey.createmethod:
curl "https://cloudkms.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/keyRings/KEY_RING/cryptoKeys?crypto_key_id=KEY_NAME" \ --request "POST" \ --header "authorization: BearerTOKEN" \ --header "content-type: application/json" \ --data '{"purpose": "ENCRYPT_DECRYPT", "versionTemplate": { "protectionLevel": "PROTECTION_LEVEL", "algorithm": "ALGORITHM" }}'Replace the following:
PROJECT_ID: the ID of the project that contains the key ring.LOCATION: the Cloud KMS location of the key ring.KEY_RING: the name of the key ring that contains the key.KEY_NAME: the name of the key.PROTECTION_LEVEL: the protection level of thekey—for example,SOFTWAREorHSM.ALGORITHM: the HMAC signing algorithm—for example,HMAC_SHA256. To see all supported HMAC algorithms, seeHMAC signingalgorithms.
PROTECTION_LEVEL toHSM_SINGLE_TENANT and add the--crypto-key-backend flag to thekms keys create command:curl "https://cloudkms.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/keyRings/KEY_RING/cryptoKeys?crypto_key_id=KEY_NAME" \ --request "POST" \ --header "authorization: BearerTOKEN" \ --header "content-type: application/json" \ --data '{"purpose": "ENCRYPT_DECRYPT", "versionTemplate": { "protectionLevel": "HSM_SINGLE_TENANT", "algorithm": "ALGORITHM", "crypto-key-backend": "projects/INSTANCE_PROJECT/locations/LOCATION/singleTenantHsmInstances/INSTANCE_NAME" }}'Replace the following:
INSTANCE_PROJECT: the identifier of the project whereyour Single-tenant Cloud HSM instance exists.INSTANCE_NAME: the name of the Single-tenant Cloud HSMinstance where you want to create the key. For more information aboutSingle-tenant Cloud HSM instances, seeCreate and manage a Single-tenant Cloud HSMinstance.
For information on all flags and possible values, run the command with the--help flag.
Create a symmetric encryption key with custom automatic rotation
When you create a key, you can specify itsrotationperiod, which is the time between the automatic creation ofnew key versions. You can also independently specify the next rotation time,so that the next rotation happens earlier or later than one rotation period fromnow.
Console
When you use the Google Cloud console to create a key, Cloud KMS sets therotation period and next rotation time automatically. You can choose to usethe default values or specify different values.
To specify a different rotation period and starting time, when you'recreatingyour key, butbefore you clicktheCreate button:
ForKey rotation period, select an option.
ForStarting on, select the date when you want the first automaticrotation to happen. You can leaveStarting on at its default value tostart the first automatic rotation one key rotation period from when youcreate the key.
gcloud
To use Cloud KMS on the command line, firstInstall or upgrade to the latest version of Google Cloud CLI.
gcloud kms keys createKEY_NAME \ --keyringKEY_RING \ --locationLOCATION \ --purpose "encryption" \ --rotation-periodROTATION_PERIOD \ --next-rotation-timeNEXT_ROTATION_TIME
Replace the following:
KEY_NAME: the name of the key.KEY_RING: the name of the key ring that contains the key.LOCATION: the Cloud KMS location of the key ring.ROTATION_PERIOD: the interval torotate the key—for example,30dto rotate the key every 30 days. The rotationperiod must be at least 1 day and at most 100 years. For more information, seeCryptoKey.rotationPeriod.NEXT_ROTATION_TIME: the timestamp at which to complete the firstrotation—for example,2023-01-01T01:02:03. You can omit--next-rotation-timeto schedule the first rotation for one rotationperiod from when you run the command. For more information, seeCryptoKey.nextRotationTime.
For information on all flags and possible values, run the command with the--help flag.
C#
To run this code, firstset up a C# development environment andinstall the Cloud KMS C# SDK.
usingGoogle.Cloud.Kms.V1;usingGoogle.Protobuf.WellKnownTypes;usingSystem;publicclassCreateKeyRotationScheduleSample{publicCryptoKeyCreateKeyRotationSchedule(stringprojectId="my-project",stringlocationId="us-east1",stringkeyRingId="my-key-ring",stringid="my-key-with-rotation-schedule"){// Create the client.KeyManagementServiceClientclient=KeyManagementServiceClient.Create();// Build the parent key ring name.KeyRingNamekeyRingName=newKeyRingName(projectId,locationId,keyRingId);// Build the key.CryptoKeykey=newCryptoKey{Purpose=CryptoKey.Types.CryptoKeyPurpose.EncryptDecrypt,VersionTemplate=newCryptoKeyVersionTemplate{Algorithm=CryptoKeyVersion.Types.CryptoKeyVersionAlgorithm.GoogleSymmetricEncryption,},// Rotate the key every 30 days.RotationPeriod=newDuration{Seconds=60*60*24*30,// 30 days},// Start the first rotation in 24 hours.NextRotationTime=newTimestamp{Seconds=newDateTimeOffset(DateTime.UtcNow.AddHours(24)).ToUnixTimeSeconds(),}};// Call the API.CryptoKeyresult=client.CreateCryptoKey(keyRingName,id,key);// Return the result.returnresult;}}Go
To run this code, firstset up a Go development environment andinstall the Cloud KMS Go SDK.
import("context""fmt""io""time"kms"cloud.google.com/go/kms/apiv1""cloud.google.com/go/kms/apiv1/kmspb""google.golang.org/protobuf/types/known/durationpb""google.golang.org/protobuf/types/known/timestamppb")// createKeyRotationSchedule creates a key with a rotation schedule.funccreateKeyRotationSchedule(wio.Writer,parent,idstring)error{// name := "projects/my-project/locations/us-east1/keyRings/my-key-ring"// id := "my-key-with-rotation-schedule"// 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_ENCRYPT_DECRYPT,VersionTemplate:&kmspb.CryptoKeyVersionTemplate{Algorithm:kmspb.CryptoKeyVersion_GOOGLE_SYMMETRIC_ENCRYPTION,},// Rotate the key every 30 daysRotationSchedule:&kmspb.CryptoKey_RotationPeriod{RotationPeriod:&durationpb.Duration{Seconds:int64(60*60*24*30),// 30 days},},// Start the first rotation in 24 hoursNextRotationTime:×tamppb.Timestamp{Seconds:time.Now().Add(24*time.Hour).Unix(),},},}// 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.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.protobuf.Duration;importcom.google.protobuf.Timestamp;importjava.io.IOException;importjava.time.temporal.ChronoUnit;publicclassCreateKeyRotationSchedule{publicvoidcreateKeyRotationSchedule()throwsIOException{// TODO(developer): Replace these variables before running the sample.StringprojectId="your-project-id";StringlocationId="us-east1";StringkeyRingId="my-key-ring";Stringid="my-key";createKeyRotationSchedule(projectId,locationId,keyRingId,id);}// Create a new key that automatically rotates on a schedule.publicvoidcreateKeyRotationSchedule(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);// Calculate the date 24 hours from now (this is used below).longtomorrow=java.time.Instant.now().plus(24,ChronoUnit.HOURS).getEpochSecond();// Build the key to create with a rotation schedule.CryptoKeykey=CryptoKey.newBuilder().setPurpose(CryptoKeyPurpose.ENCRYPT_DECRYPT).setVersionTemplate(CryptoKeyVersionTemplate.newBuilder().setAlgorithm(CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION))// Rotate every 30 days..setRotationPeriod(Duration.newBuilder().setSeconds(java.time.Duration.ofDays(30).getSeconds()))// Start the first rotation in 24 hours..setNextRotationTime(Timestamp.newBuilder().setSeconds(tomorrow)).build();// Create the key.CryptoKeycreatedKey=client.createCryptoKey(keyRingName,id,key);System.out.printf("Created key with rotation schedule %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-rotating-encryption-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);asyncfunctioncreateKeyRotationSchedule(){const[key]=awaitclient.createCryptoKey({parent:keyRingName,cryptoKeyId:id,cryptoKey:{purpose:'ENCRYPT_DECRYPT',versionTemplate:{algorithm:'GOOGLE_SYMMETRIC_ENCRYPTION',},// Rotate the key every 30 days.rotationPeriod:{seconds:60*60*24*30,},// Start the first rotation in 24 hours.nextRotationTime:{seconds:newDate().getTime()/1000+60*60*24,},},});console.log(`Created rotating key:${key.name}`);returnkey;}returncreateKeyRotationSchedule();PHP
To run this code, first learn aboutusing PHP on Google Cloud andinstall the Cloud KMS PHP SDK.
use Google\Cloud\Kms\V1\Client\KeyManagementServiceClient;use Google\Cloud\Kms\V1\CreateCryptoKeyRequest;use Google\Cloud\Kms\V1\CryptoKey;use Google\Cloud\Kms\V1\CryptoKey\CryptoKeyPurpose;use Google\Cloud\Kms\V1\CryptoKeyVersion\CryptoKeyVersionAlgorithm;use Google\Cloud\Kms\V1\CryptoKeyVersionTemplate;use Google\Protobuf\Duration;use Google\Protobuf\Timestamp;function create_key_rotation_schedule( string $projectId = 'my-project', string $locationId = 'us-east1', string $keyRingId = 'my-key-ring', string $id = 'my-key-with-rotation-schedule'): CryptoKey { // Create the Cloud KMS client. $client = new KeyManagementServiceClient(); // Build the parent key ring name. $keyRingName = $client->keyRingName($projectId, $locationId, $keyRingId); // Build the key. $key = (new CryptoKey()) ->setPurpose(CryptoKeyPurpose::ENCRYPT_DECRYPT) ->setVersionTemplate((new CryptoKeyVersionTemplate()) ->setAlgorithm(CryptoKeyVersionAlgorithm::GOOGLE_SYMMETRIC_ENCRYPTION)) // Rotate the key every 30 days. ->setRotationPeriod((new Duration()) ->setSeconds(60 * 60 * 24 * 30) ) // Start the first rotation in 24 hours. ->setNextRotationTime((new Timestamp()) ->setSeconds(time() + 60 * 60 * 24) ); // Call the API. $createCryptoKeyRequest = (new CreateCryptoKeyRequest()) ->setParent($keyRingName) ->setCryptoKeyId($id) ->setCryptoKey($key); $createdKey = $client->createCryptoKey($createCryptoKeyRequest); printf('Created key with rotation: %s' . PHP_EOL, $createdKey->getName()); return $createdKey;}Python
To run this code, firstset up a Python development environment andinstall the Cloud KMS Python SDK.
importtimefromgoogle.cloudimportkmsdefcreate_key_rotation_schedule(project_id:str,location_id:str,key_ring_id:str,key_id:str)->kms.CryptoKey:""" Creates a new key in Cloud KMS that automatically rotates. 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'). key_id (string): ID of the key to create (e.g. 'my-rotating-key'). Returns: CryptoKey: Cloud KMS key. """# Create the client.client=kms.KeyManagementServiceClient()# Build the parent key ring name.key_ring_name=client.key_ring_path(project_id,location_id,key_ring_id)# Build the key.purpose=kms.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPTalgorithm=(kms.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION)key={"purpose":purpose,"version_template":{"algorithm":algorithm,},# Rotate the key every 30 days."rotation_period":{"seconds":60*60*24*30},# Start the first rotation in 24 hours."next_rotation_time":{"seconds":int(time.time())+60*60*24},}# Call the API.created_key=client.create_crypto_key(request={"parent":key_ring_name,"crypto_key_id":key_id,"crypto_key":key})print(f"Created labeled key:{created_key.name}")returncreated_keyRuby
To run this code, firstset up a Ruby development environment andinstall the Cloud KMS Ruby SDK.
# TODO(developer): uncomment these values before running the sample.# project_id = "my-project"# location_id = "us-east1"# key_ring_id = "my-key-ring"# id = "my-key-with-rotation"# Require the library.require"google/cloud/kms"# Create the client.client=Google::Cloud::Kms.key_management_service# Build the parent key ring name.key_ring_name=client.key_ring_pathproject:project_id,location:location_id,key_ring:key_ring_id# Build the key.key={purpose::ENCRYPT_DECRYPT,version_template:{algorithm::GOOGLE_SYMMETRIC_ENCRYPTION},# Rotate the key every 30 days.rotation_period:{seconds:60*60*24*30},# Start the first rotation in 24 hours.next_rotation_time:{seconds:(Time.now+(60*60*24)).to_i}}# Call the API.created_key=client.create_crypto_keyparent:key_ring_name,crypto_key_id:id,crypto_key:keyputs"Created rotating 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.
To create a key, use theCryptoKey.createmethod:
curl "https://cloudkms.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/keyRings/KEY_RING/cryptoKeys?crypto_key_id=KEY_NAME" \ --request "POST" \ --header "authorization: BearerTOKEN" \ --header "content-type: application/json" \ --data '{"purpose": "PURPOSE", "rotationPeriod": "ROTATION_PERIOD", "nextRotationTime": "NEXT_ROTATION_TIME"}'Replace the following:
PURPOSE: thepurposeof the key.ROTATION_PERIOD: the interval torotate the key—for example,30dto rotate the key every 30 days. The rotationperiod must be at least 1 day and at most 100 years. For more information, seeCryptoKey.rotationPeriod.NEXT_ROTATION_TIME: the timestamp at which to complete the firstrotation—for example,2023-01-01T01:02:03. For more information, seeCryptoKey.nextRotationTime.
Set the duration of the 'scheduled for destruction' state
By default, key versions in Cloud KMS spend30 days in the scheduled for destruction(DESTROY_SCHEDULED) state before they aredestroyed. The scheduled for destruction state is sometimes called thesoft deleted state. The duration for which key versions remain in this stateis configurable, with the following constraints:
- You can only set the duration during key creation.
- After the duration for the key has been specified, it can't be changed.
- The duration applies to all versions of the key created in the future.
- The minimum duration is 24 hours for all keys, except for import-only keyswhich have a minimum duration of 0.
- The maximum duration is 120 days.
- The default duration is 30 days.
Your organization might have a minimum scheduled for destruction durationvalue defined by organization policies. For more information, seeControlkey destruction.
To create a key which uses a custom duration for thescheduled for destructionstate, use the following steps:
Console
In the Google Cloud console, go to theKey Management page.
Click the name of the key ring for which you will create a key.
ClickCreate key.
Configure the settings of the key for your application.
ClickAdditional settings.
InDuration of 'scheduled for destruction' state, choose the number ofdays the key will remainscheduled for destruction before beingpermanently destroyed.
ClickCreate key.
gcloud
To use Cloud KMS on the command line, firstInstall or upgrade to the latest version of Google Cloud CLI.
gcloud kms keys createKEY_NAME \ --keyringKEY_RING \ --locationLOCATION \ --purposePURPOSE \ --destroy-scheduled-durationDURATION
Replace the following:
KEY_NAME: the name of the key.KEY_RING: the name of the key ring that contains the key.LOCATION: the Cloud KMS location of the key ring.PURPOSE: the purpose of the key—for example,encryption.DURATION: the amount of time for the key to remain in thescheduled for destruction state before being permanently destroyed.
For information on all flags and possible values, run the command with the--help flag.
We recommend using the default duration of 30 daysfor all keys unless you have specific application or regulatory requirementsthat require a different value.
Create an asymmetric key
The following sections show you how to create asymmetric keys.
Note: A key created with a post-quantum (PQC) (Preview) default algorithmcan't be updated later to a non-PQC algorithm, and a key created with anon-PQC default algorithmcan't be updated later to a PQC algorithm.Create an asymmetric decryption key
Follow these steps to create an asymmetric decryption key on the specified keyring and location. These examples can be adapted to specify a differentprotection level or algorithm. For more information and alternative values, seeAlgorithms andProtection levels.
When you first create the key, the initial key version has a state ofPending generation. When the state changes toEnabled, you can usethe key. To learn more about key version states, seeKey versionstates.
Console
In the Google Cloud console, go to theKey Management page.
Click the name of the key ring for which you will create a key.
ClickCreate key.
ForKey name, enter a 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, selectGenerated key.
ForPurpose, selectAsymmetric decrypt.
ForAlgorithm, select3072 bit RSA - OAEP Padding - SHA256 Digest.You can change this value on future key versions.
ClickCreate.
gcloud
To use Cloud KMS on the command line, firstInstall or upgrade to the latest version of Google Cloud CLI.
gcloud kms keys createKEY_NAME \ --keyringKEY_RING \ --locationLOCATION \ --purpose "asymmetric-encryption" \ --default-algorithm "ALGORITHM" \ --protection-level "PROTECTION_LEVEL"
Replace the following:
KEY_NAME: the name of the key.KEY_RING: the name of the key ring that contains the key.LOCATION: the Cloud KMS location of the key ring.ALGORITHM: the algorithm to use for the key—forexample,rsa-decrypt-oaep-3072-sha256. For a list of supported asymmetricencryption algorithms, seeAsymmetric encryptionalgorithms.PROTECTION_LEVEL: the protection level that you want to use forthe key.
hsm-single-tenant protection level, add the--cryptoKeyBackend flag, andspecify the resource identifier of the Single-tenant Cloud HSM instance whereyou want to create the key:--crypto-key-backend"projects/INSTANCE_PROJECT/locations/LOCATION/singleTenantHsmInstances/INSTANCE_NAME"C#
To run this code, firstset up a C# development environment andinstall the Cloud KMS C# SDK.
usingGoogle.Cloud.Kms.V1;usingGoogle.Protobuf.WellKnownTypes;publicclassCreateKeyAsymmetricDecryptSample{publicCryptoKeyCreateKeyAsymmetricDecrypt(stringprojectId="my-project",stringlocationId="us-east1",stringkeyRingId="my-key-ring",stringid="my-asymmetric-encrypt-key"){// Create the client.KeyManagementServiceClientclient=KeyManagementServiceClient.Create();// Build the parent key ring name.KeyRingNamekeyRingName=newKeyRingName(projectId,locationId,keyRingId);// Build the key.CryptoKeykey=newCryptoKey{Purpose=CryptoKey.Types.CryptoKeyPurpose.AsymmetricDecrypt,VersionTemplate=newCryptoKeyVersionTemplate{Algorithm=CryptoKeyVersion.Types.CryptoKeyVersionAlgorithm.RsaDecryptOaep2048Sha256,},// Optional: customize how long key versions should be kept before destroying.DestroyScheduledDuration=newDuration{Seconds=24*60*60,}};// Call the API.CryptoKeyresult=client.CreateCryptoKey(keyRingName,id,key);// Return the result.returnresult;}}Go
To run this code, firstset up a Go development environment andinstall the Cloud KMS Go SDK.
import("context""fmt""io""time"kms"cloud.google.com/go/kms/apiv1""cloud.google.com/go/kms/apiv1/kmspb""google.golang.org/protobuf/types/known/durationpb")// createKeyAsymmetricDecrypt creates a new asymmetric RSA encrypt/decrypt key// pair where the private key is stored in Cloud KMS.funccreateKeyAsymmetricDecrypt(wio.Writer,parent,idstring)error{// parent := "projects/my-project/locations/us-east1/keyRings/my-key-ring"// id := "my-asymmetric-encryption-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_DECRYPT,VersionTemplate:&kmspb.CryptoKeyVersionTemplate{Algorithm:kmspb.CryptoKeyVersion_RSA_DECRYPT_OAEP_2048_SHA256,},// Optional: customize how long key versions should be kept before destroying.DestroyScheduledDuration:durationpb.New(24*time.Hour),},}// 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.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.protobuf.Duration;importjava.io.IOException;publicclassCreateKeyAsymmetricDecrypt{publicvoidcreateKeyAsymmetricDecrypt()throwsIOException{// TODO(developer): Replace these variables before running the sample.StringprojectId="your-project-id";StringlocationId="us-east1";StringkeyRingId="my-key-ring";Stringid="my-asymmetric-decryption-key";createKeyAsymmetricDecrypt(projectId,locationId,keyRingId,id);}// Create a new asymmetric key for the purpose of encrypting and decrypting// data.publicvoidcreateKeyAsymmetricDecrypt(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 asymmetric key to create.CryptoKeykey=CryptoKey.newBuilder().setPurpose(CryptoKeyPurpose.ASYMMETRIC_DECRYPT).setVersionTemplate(CryptoKeyVersionTemplate.newBuilder().setAlgorithm(CryptoKeyVersionAlgorithm.RSA_DECRYPT_OAEP_2048_SHA256))// Optional: customize how long key versions should be kept before destroying..setDestroyScheduledDuration(Duration.newBuilder().setSeconds(24*60*60)).build();// Create the key.CryptoKeycreatedKey=client.createCryptoKey(keyRingName,id,key);System.out.printf("Created asymmetric 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-asymmetric-decrypt-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);asyncfunctioncreateKeyAsymmetricDecrypt(){const[key]=awaitclient.createCryptoKey({parent:keyRingName,cryptoKeyId:id,cryptoKey:{purpose:'ASYMMETRIC_DECRYPT',versionTemplate:{algorithm:'RSA_DECRYPT_OAEP_2048_SHA256',},// Optional: customize how long key versions should be kept before// destroying.destroyScheduledDuration:{seconds:60*60*24},},});console.log(`Created asymmetric key:${key.name}`);returnkey;}returncreateKeyAsymmetricDecrypt();PHP
To run this code, first learn aboutusing PHP on Google Cloud andinstall the Cloud KMS PHP SDK.
use Google\Cloud\Kms\V1\Client\KeyManagementServiceClient;use Google\Cloud\Kms\V1\CreateCryptoKeyRequest;use Google\Cloud\Kms\V1\CryptoKey;use Google\Cloud\Kms\V1\CryptoKey\CryptoKeyPurpose;use Google\Cloud\Kms\V1\CryptoKeyVersion\CryptoKeyVersionAlgorithm;use Google\Cloud\Kms\V1\CryptoKeyVersionTemplate;use Google\Protobuf\Duration;function create_key_asymmetric_decrypt( string $projectId = 'my-project', string $locationId = 'us-east1', string $keyRingId = 'my-key-ring', string $id = 'my-asymmetric-decrypt-key'): CryptoKey { // Create the Cloud KMS client. $client = new KeyManagementServiceClient(); // Build the parent key ring name. $keyRingName = $client->keyRingName($projectId, $locationId, $keyRingId); // Build the key. $key = (new CryptoKey()) ->setPurpose(CryptoKeyPurpose::ASYMMETRIC_DECRYPT) ->setVersionTemplate((new CryptoKeyVersionTemplate()) ->setAlgorithm(CryptoKeyVersionAlgorithm::RSA_DECRYPT_OAEP_2048_SHA256) ) // Optional: customize how long key versions should be kept before destroying. ->setDestroyScheduledDuration((new Duration()) ->setSeconds(24 * 60 * 60) ); // Call the API. $createCryptoKeyRequest = (new CreateCryptoKeyRequest()) ->setParent($keyRingName) ->setCryptoKeyId($id) ->setCryptoKey($key); $createdKey = $client->createCryptoKey($createCryptoKeyRequest); printf('Created asymmetric decryption key: %s' . PHP_EOL, $createdKey->getName()); return $createdKey;}Python
To run this code, firstset up a Python development environment andinstall the Cloud KMS Python SDK.
importdatetime# Import the client library.fromgoogle.cloudimportkmsfromgoogle.protobufimportduration_pb2# type: ignoredefcreate_key_asymmetric_decrypt(project_id:str,location_id:str,key_ring_id:str,key_id:str)->kms.CryptoKey:""" Creates a new asymmetric decryption key 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'). key_id (string): ID of the key to create (e.g. 'my-asymmetric-decrypt-key'). Returns: CryptoKey: Cloud KMS key. """# Create the client.client=kms.KeyManagementServiceClient()# Build the parent key ring name.key_ring_name=client.key_ring_path(project_id,location_id,key_ring_id)# Build the key.purpose=kms.CryptoKey.CryptoKeyPurpose.ASYMMETRIC_DECRYPTalgorithm=(kms.CryptoKeyVersion.CryptoKeyVersionAlgorithm.RSA_DECRYPT_OAEP_2048_SHA256)key={"purpose":purpose,"version_template":{"algorithm":algorithm,},# Optional: customize how long key versions should be kept before# destroying."destroy_scheduled_duration":duration_pb2.Duration().FromTimedelta(datetime.timedelta(days=1)),}# Call the API.created_key=client.create_crypto_key(request={"parent":key_ring_name,"crypto_key_id":key_id,"crypto_key":key})print(f"Created asymmetric decrypt key:{created_key.name}")returncreated_keyRuby
To run this code, firstset up a Ruby development environment andinstall the Cloud KMS Ruby SDK.
# TODO(developer): uncomment these values before running the sample.# project_id = "my-project"# location_id = "us-east1"# key_ring_id = "my-key-ring"# id = "my-asymmetric-decrypt-key"# Require the library.require"google/cloud/kms"# Create the client.client=Google::Cloud::Kms.key_management_service# Build the parent key ring name.key_ring_name=client.key_ring_pathproject:project_id,location:location_id,key_ring:key_ring_id# Build the key.key={purpose::ASYMMETRIC_DECRYPT,version_template:{algorithm::RSA_DECRYPT_OAEP_2048_SHA256},# Optional: customize how long key versions should be kept before destroying.destroy_scheduled_duration:{seconds:24*60*60}}# Call the API.created_key=client.create_crypto_keyparent:key_ring_name,crypto_key_id:id,crypto_key:keyputs"Created asymmetric decryption 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 an asymmetric decryption key using theCryptoKey.create method.curl "https://cloudkms.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/keyRings/KEY_RING/cryptoKeys?crypto_key_id=KEY_NAME" \ --request "POST" \ --header "authorization: BearerTOKEN" \ --header "content-type: application/json" \ --data '{"purpose": "ASYMMETRIC_DECRYPT", "protectionLevel": "PROTECTION_LEVEL", "versionTemplate": {"algorithm": "ALGORITHM"}}'Replace the following:
PROJECT_ID: the ID of the project that contains the key ring.LOCATION: the Cloud KMS location of the key ring.KEY_RING: the name of the key ring that contains the key.KEY_NAME: the name of the key.ALGORITHM: the algorithm to use forthe key—for example,RSA_DECRYPT_OAEP_3072_SHA256. For a list ofsupported asymmetric encryption algorithms, seeAsymmetric encryptionalgorithms.PROTECTION_LEVEL: the protection level that you want to use forthe key.
PROTECTION_LEVEL toHSM_SINGLE_TENANT and add thecryptoKeyBackend field to the body of the command with the resourceidentifier of the Single-tenant Cloud HSM instance where you want toimport the key:"cryptoKeyBackend": "projects/INSTANCE_PROJECT/locations/LOCATION/singleTenantHsmInstances/INSTANCE_NAME"
Create an asymmetric signing key
Follow these steps to create an asymmetric signing key on the specified key ringand location. These examples can be adapted to specify a differentprotection level or algorithm. For more information and alternative values, seeAlgorithms andProtection levels.
When you first create the key, the initial key version has a state ofPending generation. When the state changes toEnabled, you can usethe key. To learn more about key version states, seeKey versionstates.
Console
In the Google Cloud console, go to theKey Management page.
Click the name of the key ring for which you will create a key.
ClickCreate key.
ForKey name, enter a 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, selectGenerated key.
ForPurpose, selectAsymmetric sign.
ForAlgorithm, selectElliptic Curve P-256 - SHA256 Digest. You canchange this value on future key versions.
ClickCreate.
gcloud
To use Cloud KMS on the command line, firstInstall or upgrade to the latest version of Google Cloud CLI.
gcloud kms keys createKEY_NAME \ --keyringKEY_RING \ --locationLOCATION \ --purpose "asymmetric-signing" \ --default-algorithm "ALGORITHM" \ --protection-level "PROTECTION_LEVEL"
Replace the following:
KEY_NAME: the name of the key.KEY_RING: the name of the key ring that contains the key.LOCATION: the Cloud KMS location of the key ring.ALGORITHM: the algorithm to use for the key—for example,ec-sign-p256-sha256. For a list of supported algorithms, seeAsymmetricsigning algorithms.PROTECTION_LEVEL: the protection level that you want to use forthe key.
PROTECTION_LEVEL tohsm-single-tenant and add the--cryptoKeyBackend flag to specify the resource identifier of theSingle-tenant Cloud HSM instance where you want to create the key:--crypto-key-backend"projects/INSTANCE_PROJECT/locations/LOCATION/singleTenantHsmInstances/INSTANCE_NAME"C#
To run this code, firstset up a C# development environment andinstall the Cloud KMS C# SDK.
usingGoogle.Cloud.Kms.V1;usingGoogle.Protobuf.WellKnownTypes;publicclassCreateKeyAsymmetricSignSample{publicCryptoKeyCreateKeyAsymmetricSign(stringprojectId="my-project",stringlocationId="us-east1",stringkeyRingId="my-key-ring",stringid="my-asymmetric-signing-key"){// Create the client.KeyManagementServiceClientclient=KeyManagementServiceClient.Create();// Build the parent key ring name.KeyRingNamekeyRingName=newKeyRingName(projectId,locationId,keyRingId);// Build the key.CryptoKeykey=newCryptoKey{Purpose=CryptoKey.Types.CryptoKeyPurpose.AsymmetricSign,VersionTemplate=newCryptoKeyVersionTemplate{Algorithm=CryptoKeyVersion.Types.CryptoKeyVersionAlgorithm.RsaSignPkcs12048Sha256,},// Optional: customize how long key versions should be kept before destroying.DestroyScheduledDuration=newDuration{Seconds=24*60*60,}};// Call the API.CryptoKeyresult=client.CreateCryptoKey(keyRingName,id,key);// Return the result.returnresult;}}Go
To run this code, firstset up a Go development environment andinstall the Cloud KMS Go SDK.
import("context""fmt""io""time"kms"cloud.google.com/go/kms/apiv1""cloud.google.com/go/kms/apiv1/kmspb""google.golang.org/protobuf/types/known/durationpb")// createKeyAsymmetricSign creates a new asymmetric RSA sign/verify key pair// where the private key is stored in Cloud KMS.funccreateKeyAsymmetricSign(wio.Writer,parent,idstring)error{// parent := "projects/my-project/locations/us-east1/keyRings/my-key-ring"// id := "my-asymmetric-signing-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{Algorithm:kmspb.CryptoKeyVersion_RSA_SIGN_PKCS1_2048_SHA256,},// Optional: customize how long key versions should be kept before destroying.DestroyScheduledDuration:durationpb.New(24*time.Hour),},}// 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.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.protobuf.Duration;importjava.io.IOException;publicclassCreateKeyAsymmetricSign{publicvoidcreateKeyAsymmetricSign()throwsIOException{// TODO(developer): Replace these variables before running the sample.StringprojectId="your-project-id";StringlocationId="us-east1";StringkeyRingId="my-key-ring";Stringid="my-asymmetric-signing-key";createKeyAsymmetricSign(projectId,locationId,keyRingId,id);}// Create a new asymmetric key for the purpose of signing and verifying data.publicvoidcreateKeyAsymmetricSign(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 asymmetric key to create.CryptoKeykey=CryptoKey.newBuilder().setPurpose(CryptoKeyPurpose.ASYMMETRIC_SIGN).setVersionTemplate(CryptoKeyVersionTemplate.newBuilder().setAlgorithm(CryptoKeyVersionAlgorithm.RSA_SIGN_PKCS1_2048_SHA256))// Optional: customize how long key versions should be kept before destroying..setDestroyScheduledDuration(Duration.newBuilder().setSeconds(24*60*60)).build();// Create the key.CryptoKeycreatedKey=client.createCryptoKey(keyRingName,id,key);System.out.printf("Created asymmetric 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-asymmetric-sign-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);asyncfunctioncreateKeyAsymmetricSign(){const[key]=awaitclient.createCryptoKey({parent:keyRingName,cryptoKeyId:id,cryptoKey:{purpose:'ASYMMETRIC_SIGN',versionTemplate:{algorithm:'RSA_SIGN_PKCS1_2048_SHA256',},// Optional: customize how long key versions should be kept before// destroying.destroyScheduledDuration:{seconds:60*60*24},},});console.log(`Created asymmetric key:${key.name}`);returnkey;}returncreateKeyAsymmetricSign();PHP
To run this code, first learn aboutusing PHP on Google Cloud andinstall the Cloud KMS PHP SDK.
use Google\Cloud\Kms\V1\Client\KeyManagementServiceClient;use Google\Cloud\Kms\V1\CreateCryptoKeyRequest;use Google\Cloud\Kms\V1\CryptoKey;use Google\Cloud\Kms\V1\CryptoKey\CryptoKeyPurpose;use Google\Cloud\Kms\V1\CryptoKeyVersion\CryptoKeyVersionAlgorithm;use Google\Cloud\Kms\V1\CryptoKeyVersionTemplate;use Google\Protobuf\Duration;function create_key_asymmetric_sign( string $projectId = 'my-project', string $locationId = 'us-east1', string $keyRingId = 'my-key-ring', string $id = 'my-asymmetric-signing-key'): CryptoKey { // Create the Cloud KMS client. $client = new KeyManagementServiceClient(); // Build the parent key ring name. $keyRingName = $client->keyRingName($projectId, $locationId, $keyRingId); // Build the key. $key = (new CryptoKey()) ->setPurpose(CryptoKeyPurpose::ASYMMETRIC_SIGN) ->setVersionTemplate((new CryptoKeyVersionTemplate()) ->setAlgorithm(CryptoKeyVersionAlgorithm::RSA_SIGN_PKCS1_2048_SHA256) ) // Optional: customize how long key versions should be kept before destroying. ->setDestroyScheduledDuration((new Duration()) ->setSeconds(24 * 60 * 60) ); // Call the API. $createCryptoKeyRequest = (new CreateCryptoKeyRequest()) ->setParent($keyRingName) ->setCryptoKeyId($id) ->setCryptoKey($key); $createdKey = $client->createCryptoKey($createCryptoKeyRequest); printf('Created asymmetric signing key: %s' . PHP_EOL, $createdKey->getName()); return $createdKey;}Python
To run this code, firstset up a Python development environment andinstall the Cloud KMS Python SDK.
importdatetime# Import the client library.fromgoogle.cloudimportkmsfromgoogle.protobufimportduration_pb2# type: ignoredefcreate_key_asymmetric_sign(project_id:str,location_id:str,key_ring_id:str,key_id:str)->kms.CryptoKey:""" Creates a new asymmetric signing key 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'). key_id (string): ID of the key to create (e.g. 'my-asymmetric-signing-key'). Returns: CryptoKey: Cloud KMS key. """# Create the client.client=kms.KeyManagementServiceClient()# Build the parent key ring name.key_ring_name=client.key_ring_path(project_id,location_id,key_ring_id)# Build the key.purpose=kms.CryptoKey.CryptoKeyPurpose.ASYMMETRIC_SIGNalgorithm=(kms.CryptoKeyVersion.CryptoKeyVersionAlgorithm.RSA_SIGN_PKCS1_2048_SHA256)key={"purpose":purpose,"version_template":{"algorithm":algorithm,},# Optional: customize how long key versions should be kept before# destroying."destroy_scheduled_duration":duration_pb2.Duration().FromTimedelta(datetime.timedelta(days=1)),}# Call the API.created_key=client.create_crypto_key(request={"parent":key_ring_name,"crypto_key_id":key_id,"crypto_key":key})print(f"Created asymmetric signing key:{created_key.name}")returncreated_keyRuby
To run this code, firstset up a Ruby development environment andinstall the Cloud KMS Ruby SDK.
# TODO(developer): uncomment these values before running the sample.# project_id = "my-project"# location_id = "us-east1"# key_ring_id = "my-key-ring"# id = "my-asymmetric-signing-key"# Require the library.require"google/cloud/kms"# Create the client.client=Google::Cloud::Kms.key_management_service# Build the parent key ring name.key_ring_name=client.key_ring_pathproject:project_id,location:location_id,key_ring:key_ring_id# Build the key.key={purpose::ASYMMETRIC_SIGN,version_template:{algorithm::RSA_SIGN_PKCS1_2048_SHA256},# Optional: customize how long key versions should be kept before destroying.destroy_scheduled_duration:{seconds:24*60*60}}# Call the API.created_key=client.create_crypto_keyparent:key_ring_name,crypto_key_id:id,crypto_key:keyputs"Created asymmetric signing 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 an asymmetric signing key by calling[`CryptoKey.create`](/kms/docs/reference/rest/v1/projects.locations.keyRings.cryptoKeys/create).curl "https://cloudkms.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/keyRings/KEY_RING/cryptoKeys?crypto_key_id=KEY_NAME" \ --request "POST" \ --header "authorization: BearerTOKEN" \ --header "content-type: application/json" \ --data '{"purpose": "ASYMMETRIC_SIGN", "versionTemplate": {"protectionLevel": "PROTECTION_LEVEL", "algorithm": "ALGORITHM"}}'Replace the following:
PROJECT_ID: the ID of the project that contains the key ring.LOCATION: the Cloud KMS location of the key ring.KEY_RING: the name of the key ring that contains the key.KEY_NAME: the name of the key.PROTECTION_LEVEL: the protection level that you want to use forthe key.ALGORITHM: the algorithm to use forthe key—for example,EC_SIGN_P256_SHA256. For a list of supportedalgorithms, seeAsymmetric signingalgorithms.If you want to create your key in a Single-tenant Cloud HSM, set
PROTECTION_LEVELtoHSM_SINGLE_TENANTand 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"
Create a KEM key
Follow these steps to create a key for use in a key encapsulation mechanism (KEM) for the specified key ringand location. These examples can be adapted to specify a differentprotection level or algorithm. For more information and alternative values, seeAlgorithms andProtection levels.
When you first create the key, the initial key version has a state ofPending generation. When the state changes toEnabled, you can usethe key. To learn more about key version states, seeKey versionstates.
gcloud
To use Cloud KMS on the command line, firstInstall or upgrade to the latest version of Google Cloud CLI.
gcloud kms keys createKEY_NAME \ --keyringKEY_RING \ --locationLOCATION \ --purpose "key-encapsulation" \ --default-algorithm "ALGORITHM"
Replace the following:
KEY_NAME: the name of the key.KEY_RING: the name of the key ring that contains the key.LOCATION: the Cloud KMS location of the key ring.ALGORITHM: the algorithm to use for the key—forexample,ml-kem-768. For a list of supported key encapsulation algorithms, seeKey encapsulationalgorithms.
For information on all flags and possible values, run the command with the--help flag.
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 key with purposeKEY_ENCAPSULATION by callingCryptoKey.create.
curl "https://cloudkms.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/keyRings/KEY_RING/cryptoKeys?crypto_key_id=KEY_NAME" \ --request "POST" \ --header "authorization: BearerTOKEN" \ --header "content-type: application/json" \ --data '{"purpose": "KEY_ENCAPSULATION", "versionTemplate": {"algorithm": "ALGORITHM"}}'Replace the following:
PROJECT_ID: the ID of the project that contains the key ring.LOCATION: the Cloud KMS location of the key ring.KEY_RING: the name of the key ring that contains the key.KEY_NAME: the name of the key.ALGORITHM: the algorithm to use forthe key—for example,ML_KEM_768. For a list ofsupported key encapsulation algorithms, seeKey encapsulation algorithms.
Retrieve the public key
When you create an asymmetric key, Cloud KMS creates a public/privatekey pair. You can retrieve the public key of an enabled asymmetric key at anytime after the key is generated.
The public key is in the Privacy-enhanced Electronic Mail (PEM) format. For moreinformation, see theRFC 7468 sectionsGeneralConsiderations andTextual Encoding of Subject PublicKey Info.
To download the public key for an existing asymmetric key version, follow thesesteps:
Console
In the Google Cloud console, go to theKey Management page.
Click the name of the key ring that contains the asymmetric key for whichyou want to retrieve the public key.
Click the name of the key for which you want to retrieve the public key.
On the row corresponding to the key version for which you want to retrievethe public key, clickView More.
ClickGet public key.
The public key is displayed in the prompt. You can copy the public key toyour clipboard. To download the public key, clickDownload.
If you do not see theGet public key option, verify the following:
- The key is an asymmetric key.
- The key version is enabled.
- You have the
cloudkms.cryptoKeyVersions.viewPublicKeypermission.
The filename of a public key downloaded from the Google Cloud console is ofthe form:
KEY_RING-KEY_NAME-KEY_VERSION.pub
Each portion of the filename is separated by a hyphen, for exampleringname-keyname-version.pub.
gcloud
To use Cloud KMS on the command line, firstInstall or upgrade to the latest version of Google Cloud CLI.
Note: Thegcloud kms keys versions get-public-key command must be run froma local shell. Do not attempt to run this command using the Cloud Shell.gcloud kms keys versions get-public-keyKEY_VERSION \ --keyKEY_NAME \ --keyringKEY_RING \ --locationLOCATION \ --public-key-formatPUBLIC_KEY_FORMAT \ --output-fileOUTPUT_FILE_PATH
Replace the following:
KEY_VERSION: the key version number.KEY_NAME: the name of the key.KEY_RING: the name of the key ring that contains the key.LOCATION: the Cloud KMS location of the key ring.PUBLIC_KEY_FORMAT: the format in which you want to exportthe public key. For NIST PQC algorithms(Preview), usenist-pqcandfor X-Wing (Preview) usexwing-raw-bytes. For all otherkeys, you can usepem,der, or omit this parameter.OUTPUT_FILE_PATH: the path where you want to save thepublic key file—for example,public-key.pub.
For information on all flags and possible values, run the command with the--help flag.
C#
To run this code, firstset up a C# development environment andinstall the Cloud KMS C# SDK.
usingGoogle.Cloud.Kms.V1;publicclassGetPublicKeySample{publicPublicKeyGetPublicKey(stringprojectId="my-project",stringlocationId="us-east1",stringkeyRingId="my-key-ring",stringkeyId="my-key",stringkeyVersionId="123"){// Create the client.KeyManagementServiceClientclient=KeyManagementServiceClient.Create();// Build the key version name.CryptoKeyVersionNamekeyVersionName=newCryptoKeyVersionName(projectId,locationId,keyRingId,keyId,keyVersionId);// Call the API.PublicKeyresult=client.GetPublicKey(keyVersionName);// Return the ciphertext.returnresult;}}Go
To run this code, firstset up a Go development environment andinstall the Cloud KMS Go SDK.
import("context""crypto/x509""encoding/pem""fmt""hash/crc32""io"kms"cloud.google.com/go/kms/apiv1""cloud.google.com/go/kms/apiv1/kmspb")// getPublicKey retrieves the public key from an asymmetric key pair on// Cloud KMS.funcgetPublicKey(wio.Writer,namestring)error{// name := "projects/my-project/locations/us-east1/keyRings/my-key-ring/cryptoKeys/my-key/cryptoKeyVersions/123"// 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.GetPublicKeyRequest{Name:name,}// Call the API.result,err:=client.GetPublicKey(ctx,req)iferr!=nil{returnfmt.Errorf("failed to get public key: %w",err)}// The 'Pem' field is the raw string representation of the public key.// Convert 'Pem' into bytes for further processing.key:=[]byte(result.Pem)// Optional, but recommended: perform integrity verification on result.// For more details on ensuring E2E in-transit integrity to and from Cloud KMS visit:// https://cloud.google.com/kms/docs/data-integrity-guidelinescrc32c:=func(data[]byte)uint32{t:=crc32.MakeTable(crc32.Castagnoli)returncrc32.Checksum(data,t)}ifint64(crc32c(key))!=result.PemCrc32C.Value{returnfmt.Errorf("getPublicKey: response corrupted in-transit")}// Optional - parse the public key. This transforms the string key into a Go// PublicKey.block,_:=pem.Decode(key)publicKey,err:=x509.ParsePKIXPublicKey(block.Bytes)iferr!=nil{returnfmt.Errorf("failed to parse public key: %w",err)}fmt.Fprintf(w,"Retrieved public key: %v\n",publicKey)returnnil}Java
To run this code, firstset up a Java development environment andinstall the Cloud KMS Java SDK.
importcom.google.cloud.kms.v1.CryptoKeyVersionName;importcom.google.cloud.kms.v1.KeyManagementServiceClient;importcom.google.cloud.kms.v1.PublicKey;importjava.io.IOException;importjava.security.GeneralSecurityException;publicclassGetPublicKey{publicvoidgetPublicKey()throwsIOException,GeneralSecurityException{// TODO(developer): Replace these variables before running the sample.StringprojectId="your-project-id";StringlocationId="us-east1";StringkeyRingId="my-key-ring";StringkeyId="my-key";StringkeyVersionId="123";getPublicKey(projectId,locationId,keyRingId,keyId,keyVersionId);}// Get the public key associated with an asymmetric key.publicvoidgetPublicKey(StringprojectId,StringlocationId,StringkeyRingId,StringkeyId,StringkeyVersionId)throwsIOException,GeneralSecurityException{// 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 key version name from the project, location, key ring, key,// and key version.CryptoKeyVersionNamekeyVersionName=CryptoKeyVersionName.of(projectId,locationId,keyRingId,keyId,keyVersionId);// Get the public key.PublicKeypublicKey=client.getPublicKey(keyVersionName);System.out.printf("Public key: %s%n",publicKey.getPem());}}}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 keyId = 'my-key';// Imports the Cloud KMS libraryconst{KeyManagementServiceClient}=require('@google-cloud/kms');// Instantiates a clientconstclient=newKeyManagementServiceClient();// Build the key version nameconstversionName=client.cryptoKeyVersionPath(projectId,locationId,keyRingId,keyId,versionId);asyncfunctiongetPublicKey(){const[publicKey]=awaitclient.getPublicKey({name:versionName,});// Optional, but recommended: perform integrity verification on publicKey.// For more details on ensuring E2E in-transit integrity to and from Cloud KMS visit:// https://cloud.google.com/kms/docs/data-integrity-guidelinesconstcrc32c=require('fast-crc32c');if(publicKey.name!==versionName){thrownewError('GetPublicKey: request corrupted in-transit');}if(crc32c.calculate(publicKey.pem)!==Number(publicKey.pemCrc32c.value)){thrownewError('GetPublicKey: response corrupted in-transit');}console.log(`Public key pem:${publicKey.pem}`);returnpublicKey;}returngetPublicKey();PHP
To run this code, first learn aboutusing PHP on Google Cloud andinstall the Cloud KMS PHP SDK.
use Google\Cloud\Kms\V1\Client\KeyManagementServiceClient;use Google\Cloud\Kms\V1\GetPublicKeyRequest;function get_public_key( string $projectId = 'my-project', string $locationId = 'us-east1', string $keyRingId = 'my-key-ring', string $keyId = 'my-key', string $versionId = '123') { // Create the Cloud KMS client. $client = new KeyManagementServiceClient(); // Build the key version name. $keyVersionName = $client->cryptoKeyVersionName($projectId, $locationId, $keyRingId, $keyId, $versionId); // Call the API. $getPublicKeyRequest = (new GetPublicKeyRequest()) ->setName($keyVersionName); $publicKey = $client->getPublicKey($getPublicKeyRequest); printf('Public key: %s' . PHP_EOL, $publicKey->getPem()); return $publicKey;}Python
To run this code, firstset up a Python development environment andinstall the Cloud KMS Python SDK.
fromgoogle.cloudimportkmsdefget_public_key(project_id:str,location_id:str,key_ring_id:str,key_id:str,version_id:str)->kms.PublicKey:""" Get the public key for an asymmetric key. 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'). key_id (string): ID of the key to use (e.g. 'my-key'). version_id (string): ID of the key to use (e.g. '1'). Returns: PublicKey: Cloud KMS public key response. """# Create the client.client=kms.KeyManagementServiceClient()# Build the key version name.key_version_name=client.crypto_key_version_path(project_id,location_id,key_ring_id,key_id,version_id)# Call the API.public_key=client.get_public_key(request={"name":key_version_name})# Optional, but recommended: perform integrity verification on public_key.# For more details on ensuring E2E in-transit integrity to and from Cloud KMS visit:# https://cloud.google.com/kms/docs/data-integrity-guidelinesifnotpublic_key.name==key_version_name:raiseException("The request sent to the server was corrupted in-transit.")# See crc32c() function defined below.ifnotpublic_key.pem_crc32c==crc32c(public_key.pem.encode("utf-8")):raiseException("The response received from the server was corrupted in-transit.")# End integrity verificationprint(f"Public key:{public_key.pem}")returnpublic_keydefcrc32c(data:bytes)->int:""" Calculates the CRC32C checksum of the provided data. Args: data: the bytes over which the checksum should be calculated. Returns: An int representing the CRC32C checksum of the provided bytes. """importcrcmod# type: ignorecrc32c_fun=crcmod.predefined.mkPredefinedCrcFun("crc-32c")returncrc32c_fun(data)Ruby
To run this code, firstset up a Ruby development environment andinstall the Cloud KMS Ruby SDK.
# TODO(developer): uncomment these values before running the sample.# project_id = "my-project"# location_id = "us-east1"# key_ring_id = "my-key-ring"# key_id = "my-key"# version_id = "123"# Require the library.require"google/cloud/kms"# Create the client.client=Google::Cloud::Kms.key_management_service# Build the key version name.key_version_name=client.crypto_key_version_pathproject:project_id,location:location_id,key_ring:key_ring_id,crypto_key:key_id,crypto_key_version:version_id# Call the API.public_key=client.get_public_keyname:key_version_nameputs"Public key:#{public_key.pem}"API
These examples usecurl as an HTTP client to demonstrate using the API. For more information about access control, seeAccessing the Cloud KMS API.
Retrieve the public key by calling theCryptoKeyVersions.getPublicKeymethod.
curl "https://cloudkms.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/keyRings/KEY_RING/cryptoKeys/KEY_NAME/cryptoKeyVersions/KEY_VERSION/publicKey?public_key_format=PUBLIC_KEY_FORMAT" \ --request "GET" \ --header "authorization: BearerTOKEN"
Replace the following:
PROJECT_ID: the ID of the project that contains the key ring.LOCATION: the Cloud KMS location of the key ring.KEY_RING: the name of the key ring that contains the key.KEY_NAME: the name of the key.KEY_VERSION: the key version number.PUBLIC_KEY_FORMAT: the format in which you want to exportthe public key. For PQC algorithms(Preview), useNIST_PQC. For all otherkeys, you can usePEMor omit this parameter.
If the public key format is omitted for a non-PQC key, the output is similar tothe following:
{"pem":"-----BEGINPUBLICKEY-----\nQ29uZ3JhdHVsYXRpb25zLCB5b3UndmUgZGlzY292ZXJlZCB0aGF0IHRoaXMgaXNuJ3QgYWN0dWFsbHkgYSBwdWJsaWMga2V5ISBIYXZlIGEgbmljZSBkYXkgOik=\n-----ENDPUBLICKEY-----\n","algorithm":"ALGORITHM","pemCrc32c":"2561089887","name":"projects/PROJECT_ID/locations/LOCATION/keyRings/KEY_RING/cryptoKeys/KEY_NAME/cryptoKeyVersions/KEY_VERSION","protectionLevel":"PROTECTION_LEVEL"}
For a PQC algorithm with public key formatNIST_PQC, the output is similar tothe following:
{"publicKeyFormat":"NIST_PQC","publicKey":{"crc32cChecksum":"1985843562","data":"kdcOIrFCC5kN8S4i0+R+AoSc9gYIJ9jEQ6zG235ZmCQ="}"algorithm":"ALGORITHM","name":"projects/PROJECT_ID/locations/LOCATION/keyRings/KEY_RING/cryptoKeys/KEY_NAME/cryptoKeyVersions/KEY_VERSION","protectionLevel":"PROTECTION_LEVEL"}
Convert a public key to JWK format
Cloud KMS lets you retrieve a public key in PEM format.Some applications might require other key formats such as JSON Web Key (JWK).For more information about the JWK format, seeRFC 7517.
Note: Cloud KMS generates and verifies only DER encoded signatures,which are different fromIEEE-P1363 encoded signatures thatare often used in JSON-based implementations.Caution: We don't recommend using these third-party libraries for anythingother than JWK conversion.To convert a public key to JWK format, follow these steps:
Go
To run this code, firstset up a Go development environment andinstall the Cloud KMS Go SDK.
import("context""crypto/x509""encoding/json""encoding/pem""fmt""hash/crc32""io"kms"cloud.google.com/go/kms/apiv1""cloud.google.com/go/kms/apiv1/kmspb""github.com/lestrrat-go/jwx/v2/jwk")// getPublicKeyJwk retrieves the public key from an asymmetric key pair on Cloud KMS.funcgetPublicKeyJwk(wio.Writer,cryptoKeyVersionNamestring)error{// name := "projects/my-project/locations/us-east1/keyRings/my-key-ring/cryptoKeys/my-key/cryptoKeyVersions/123"// 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.GetPublicKeyRequest{Name:cryptoKeyVersionName,}// Call the API to get the public key.result,err:=client.GetPublicKey(ctx,req)iferr!=nil{returnfmt.Errorf("failed to get public key: %w",err)}// The 'Pem' field is the raw string representation of the public key.// Convert 'Pem' into bytes for further processing.key:=[]byte(result.Pem)// Optional, but recommended: perform integrity verification on result.// For more details on ensuring E2E in-transit integrity to and from Cloud KMS visit:// https://cloud.google.com/kms/docs/data-integrity-guidelinescrc32c:=func(data[]byte)uint32{t:=crc32.MakeTable(crc32.Castagnoli)returncrc32.Checksum(data,t)}ifint64(crc32c(key))!=result.PemCrc32C.Value{returnfmt.Errorf("getPublicKey: response corrupted in-transit")}// Optional - parse the public key.// This transforms the string key into a Go PublicKey.block,_:=pem.Decode(key)_,err=x509.ParsePKIXPublicKey(block.Bytes)iferr!=nil{returnfmt.Errorf("failed to parse public key: %w",err)}// If all above checks pass, convert it into JWK format.jwkKey,err:=jwk.ParseKey(key,jwk.WithPEM(true))iferr!=nil{returnfmt.Errorf("Failed to parse the PEM public key: %w",err)}fmt.Fprintf(w,"The public key in JWK format: ")json.NewEncoder(w).Encode(jwkKey)returnnil}Java
To run this code, firstset up a Java development environment andinstall the Cloud KMS Java SDK.
importcom.google.cloud.kms.v1.CryptoKeyVersionName;importcom.google.cloud.kms.v1.KeyManagementServiceClient;importcom.google.cloud.kms.v1.PublicKey;// NOTE: The library nimbusds is NOT endorsed for anything beyond conversion to JWK.importcom.nimbusds.jose.JOSEException;importcom.nimbusds.jose.jwk.JWK;importjava.io.IOException;importjava.security.GeneralSecurityException;publicclassConvertPublicKeyToJwk{publicvoidconvertPublicKey()throwsIOException,GeneralSecurityException,JOSEException{// TODO(developer): Replace these variables before running the sample.StringprojectId="your-project-id";StringlocationId="us-east1";StringkeyRingId="my-key-ring";StringkeyId="my-key";StringkeyVersionId="123";convertPublicKey(projectId,locationId,keyRingId,keyId,keyVersionId);}// (Get and) Convert the public key associated with an asymmetric key.publicvoidconvertPublicKey(StringprojectId,StringlocationId,StringkeyRingId,StringkeyId,StringkeyVersionId)throwsIOException,GeneralSecurityException,JOSEException{// 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 key version name from the project, location, key ring, key,// and key version.CryptoKeyVersionNamekeyVersionName=CryptoKeyVersionName.of(projectId,locationId,keyRingId,keyId,keyVersionId);// Get the public key and convert it to JWK format.PublicKeypublicKey=client.getPublicKey(keyVersionName);JWKjwk=JWK.parseFromPEMEncodedObjects(publicKey.getPem());System.out.println(jwk.toJSONString());}}}Python
To run this code, firstset up a Python development environment andinstall the Cloud KMS Python SDK.
fromgoogle.cloudimportkmsfromjwcryptoimportjwkdefget_public_key_jwk(project_id:str,location_id:str,key_ring_id:str,key_id:str,version_id:str)->kms.PublicKey:""" Get the public key of an asymmetric key in JWK format. 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'). key_id (string): ID of the key to use (e.g. 'my-key'). version_id (string): ID of the key to use (e.g. '1'). Returns: PublicKey: Cloud KMS public key response. """# Create the client.client=kms.KeyManagementServiceClient()# Build the key version name.key_version_name=client.crypto_key_version_path(project_id,location_id,key_ring_id,key_id,version_id)# Call the API.public_key=client.get_public_key(request={"name":key_version_name})# Optional, but recommended: perform integrity verification on public_key.# For more details on ensuring E2E in-transit integrity to and from Cloud KMS visit:# https://cloud.google.com/kms/docs/data-integrity-guidelinesifnotpublic_key.name==key_version_name:raiseException("The request sent to the server was corrupted in-transit.")# See crc32c() function defined below.ifnotpublic_key.pem_crc32c==crc32c(public_key.pem.encode("utf-8")):raiseException("The response received from the server was corrupted in-transit.")# End integrity verification# Convert to JWK format.jwk_key=jwk.JWK.from_pem(public_key.pem.encode())returnjwk_key.export(private_key=False)defcrc32c(data:bytes)->int:""" Calculates the CRC32C checksum of the provided data. Args: data: the bytes over which the checksum should be calculated. Returns: An int representing the CRC32C checksum of the provided bytes. """importcrcmod# type: ignorecrc32c_fun=crcmod.predefined.mkPredefinedCrcFun("crc-32c")returncrc32c_fun(data)Control access to asymmetric keys
A signer or validator requires the appropriate permission or role on theasymmetric key.
For a user or service that will perform signing, grant the
cloudkms.cryptoKeyVersions.useToSignpermission on the asymmetric key.For a user or service that will retrieve the public key, grant the
cloudkms.cryptoKeyVersions.viewPublicKeyon the asymmetric key. The public keyis required for signature validation.
Learn about permissions and roles in Cloud KMS release atPermissions and roles.
Create a MAC signing key
Console
In the Google Cloud console, go to theKey Management page.
Click the name of the key ring for which you will create a key.
ClickCreate key.
ForKey name, enter a 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, selectGenerated key.
ForPurpose, selectMAC signing/verification.
Optional: forAlgorithm, select anHMAC signingalgorithm.
ClickCreate.
gcloud
To use Cloud KMS on the command line, firstInstall or upgrade to the latest version of Google Cloud CLI.
To create a software or Multi-tenant Cloud HSM key, use thekms keyscreate command:gcloud kms keys createKEY_NAME \ --keyringKEY_RING \ --locationLOCATION \ --purpose "mac" \ --default-algorithm "ALGORITHM" \ --protection-level "PROTECTION_LEVEL"
Replace the following:
KEY_NAME: the name of the key.KEY_RING: the name of the key ring that contains the key.LOCATION: the Cloud KMS location of the key ring.ALGORITHM: the HMAC signing algorithm—for example,hmac-sha256. To see all supported HMAC algorithms, seeHMAC signingalgorithms.PROTECTION_LEVEL: the protection level of the key—forexample,hsm. You can omit the--protection-levelflag forsoftwarekeys.
For the details on all flags and possible values, run the command with the--help flag.
--crypto-key-backend flag to thekms keys create command:gcloud kms keys createKEY_NAME \ --keyringKEY_RING \ --locationLOCATION \ --purpose "mac" \ --default-algorithm "ALGORITHM" \ --protection-level "PROTECTION_LEVEL" \ --crypto-key-backend="projects/INSTANCE_PROJECT/locations/LOCATION/singleTenantHsmInstances/INSTANCE_NAME"
Replace the following:
INSTANCE_PROJECT: the identifier of the project whereyour Single-tenant Cloud HSM instance exists.INSTANCE_NAME: the name of the Single-tenant Cloud HSMinstance where you want to create the key. For more information aboutSingle-tenant Cloud HSM instances, seeCreate and manage a Single-tenant Cloud HSMinstance.
For information on all flags and possible values, run the command with the--help flag.
C#
To run this code, firstset up a C# development environment andinstall the Cloud KMS C# SDK.
usingGoogle.Cloud.Kms.V1;usingGoogle.Protobuf.WellKnownTypes;publicclassCreateKeyMacSample{publicCryptoKeyCreateKeyMac(stringprojectId="my-project",stringlocationId="us-east1",stringkeyRingId="my-key-ring",stringid="my-mac-key"){// Create the client.KeyManagementServiceClientclient=KeyManagementServiceClient.Create();// Build the parent key ring name.KeyRingNamekeyRingName=newKeyRingName(projectId,locationId,keyRingId);// Build the key.CryptoKeykey=newCryptoKey{Purpose=CryptoKey.Types.CryptoKeyPurpose.Mac,VersionTemplate=newCryptoKeyVersionTemplate{Algorithm=CryptoKeyVersion.Types.CryptoKeyVersionAlgorithm.HmacSha256,},// Optional: customize how long key versions should be kept before destroying.DestroyScheduledDuration=newDuration{Seconds=24*60*60,}};// Call the API.CryptoKeyresult=client.CreateCryptoKey(keyRingName,id,key);// Return the result.returnresult;}}Go
To run this code, firstset up a Go development environment andinstall the Cloud KMS Go SDK.
import("context""fmt""io""time"kms"cloud.google.com/go/kms/apiv1""cloud.google.com/go/kms/apiv1/kmspb""google.golang.org/protobuf/types/known/durationpb")// createKeyMac creates a new key for use with MacSign.funccreateKeyMac(wio.Writer,parent,idstring)error{// parent := "projects/my-project/locations/us-east1/keyRings/my-key-ring"// id := "my-mac-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_MAC,VersionTemplate:&kmspb.CryptoKeyVersionTemplate{Algorithm:kmspb.CryptoKeyVersion_HMAC_SHA256,},// Optional: customize how long key versions should be kept before destroying.DestroyScheduledDuration:durationpb.New(24*time.Hour),},}// 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.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;importjava.io.IOException;publicclassCreateKeyMac{publicvoidcreateKeyMac()throwsIOException{// TODO(developer): Replace these variables before running the sample.StringprojectId="your-project-id";StringlocationId="us-east1";StringkeyRingId="my-key-ring";Stringid="my-mac-key";createKeyMac(projectId,locationId,keyRingId,id);}// Create a new key for use with MacSign.publicvoidcreateKeyMac(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 mac key to create.CryptoKeykey=CryptoKey.newBuilder().setPurpose(CryptoKeyPurpose.MAC).setVersionTemplate(CryptoKeyVersionTemplate.newBuilder().setAlgorithm(CryptoKeyVersionAlgorithm.HMAC_SHA256)).build();// Create the key.CryptoKeycreatedKey=client.createCryptoKey(keyRingName,id,key);System.out.printf("Created mac 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-mac-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);asyncfunctioncreateKeyMac(){const[key]=awaitclient.createCryptoKey({parent:keyRingName,cryptoKeyId:id,cryptoKey:{purpose:'MAC',versionTemplate:{algorithm:'HMAC_SHA256',},// Optional: customize how long key versions should be kept before// destroying.destroyScheduledDuration:{seconds:60*60*24},},});console.log(`Created mac key:${key.name}`);returnkey;}returncreateKeyMac();PHP
To run this code, first learn aboutusing PHP on Google Cloud andinstall the Cloud KMS PHP SDK.
use Google\Cloud\Kms\V1\Client\KeyManagementServiceClient;use Google\Cloud\Kms\V1\CreateCryptoKeyRequest;use Google\Cloud\Kms\V1\CryptoKey;use Google\Cloud\Kms\V1\CryptoKey\CryptoKeyPurpose;use Google\Cloud\Kms\V1\CryptoKeyVersion\CryptoKeyVersionAlgorithm;use Google\Cloud\Kms\V1\CryptoKeyVersionTemplate;use Google\Protobuf\Duration;function create_key_mac( string $projectId = 'my-project', string $locationId = 'us-east1', string $keyRingId = 'my-key-ring', string $id = 'my-mac-key'): CryptoKey { // Create the Cloud KMS client. $client = new KeyManagementServiceClient(); // Build the parent key ring name. $keyRingName = $client->keyRingName($projectId, $locationId, $keyRingId); // Build the key. $key = (new CryptoKey()) ->setPurpose(CryptoKeyPurpose::MAC) ->setVersionTemplate((new CryptoKeyVersionTemplate()) ->setAlgorithm(CryptoKeyVersionAlgorithm::HMAC_SHA256) ) // Optional: customize how long key versions should be kept before destroying. ->setDestroyScheduledDuration((new Duration()) ->setSeconds(24 * 60 * 60) ); // Call the API. $createCryptoKeyRequest = (new CreateCryptoKeyRequest()) ->setParent($keyRingName) ->setCryptoKeyId($id) ->setCryptoKey($key); $createdKey = $client->createCryptoKey($createCryptoKeyRequest); printf('Created mac key: %s' . PHP_EOL, $createdKey->getName()); return $createdKey;}Python
To run this code, firstset up a Python development environment andinstall the Cloud KMS Python SDK.
importdatetimefromgoogle.cloudimportkmsfromgoogle.protobufimportduration_pb2# type: ignoredefcreate_key_mac(project_id:str,location_id:str,key_ring_id:str,key_id:str)->kms.CryptoKey:""" Creates a new key in Cloud KMS for HMAC operations. 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'). key_id (string): ID of the key to create (e.g. 'my-mac-key'). Returns: CryptoKey: Cloud KMS key. """# Create the client.client=kms.KeyManagementServiceClient()# Build the parent key ring name.key_ring_name=client.key_ring_path(project_id,location_id,key_ring_id)# Build the key.purpose=kms.CryptoKey.CryptoKeyPurpose.MACalgorithm=kms.CryptoKeyVersion.CryptoKeyVersionAlgorithm.HMAC_SHA256key={"purpose":purpose,"version_template":{"algorithm":algorithm,},# Optional: customize how long key versions should be kept before# destroying."destroy_scheduled_duration":duration_pb2.Duration().FromTimedelta(datetime.timedelta(days=1)),}# Call the API.created_key=client.create_crypto_key(request={"parent":key_ring_name,"crypto_key_id":key_id,"crypto_key":key})print(f"Created mac key:{created_key.name}")returncreated_keyRuby
To run this code, firstset up a Ruby development environment andinstall the Cloud KMS Ruby SDK.
# TODO(developer): uncomment these values before running the sample.# project_id = "my-project"# location_id = "us-east1"# key_ring_id = "my-key-ring"# id = "my-mac-key"# Require the library.require"google/cloud/kms"# Create the client.client=Google::Cloud::Kms.key_management_service# Build the parent key ring name.key_ring_name=client.key_ring_pathproject:project_id,location:location_id,key_ring:key_ring_id# Build the key.key={purpose::MAC,version_template:{algorithm::HMAC_SHA256}}# Call the API.created_key=client.create_crypto_keyparent:key_ring_name,crypto_key_id:id,crypto_key:keyputs"Created mac 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.
To create a software or Multi-tenant Cloud HSM key, use theCryptoKey.createmethod:
curl "https://cloudkms.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/keyRings/KEY_RING/cryptoKeys?crypto_key_id=KEY_NAME" \ --request "POST" \ --header "authorization: BearerTOKEN" \ --header "content-type: application/json" \ --data '{"purpose": "MAC", "versionTemplate": { "protectionLevel": "PROTECTION_LEVEL", "algorithm": "ALGORITHM" }}'Replace the following:
PROJECT_ID: the ID of the project that contains the key ring.LOCATION: the Cloud KMS location of the key ring.KEY_RING: the name of the key ring that contains the key.KEY_NAME: the name of the key.PROTECTION_LEVEL: the protection level of the key, for exampleSOFTWAREorHSM.ALGORITHM: the HMAC signing algorithm, for exampleHMAC_SHA256.To see all supported HMAC algorithms, seeHMAC signingalgorithms.
To create a Single-tenant Cloud HSM key, add thecryptoKeyBackend field totheCryptoKey.create request body:
curl "https://cloudkms.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/keyRings/KEY_RING/cryptoKeys?crypto_key_id=KEY_NAME" \ --request "POST" \ --header "authorization: BearerTOKEN" \ --header "content-type: application/json" \ --data '{"purpose": "MAC", "versionTemplate": { "protectionLevel": "PROTECTION_LEVEL", "algorithm": "ALGORITHM", "cryptoKeyBackend": "projects/INSTANCE_PROJECT/locations/LOCATION/singleTenantHsmInstances/INSTANCE_NAME" }}'Replace the following:
INSTANCE_PROJECT: the identifier of the project whereyour Single-tenant Cloud HSM instance exists.INSTANCE_NAME: the name of the Single-tenant Cloud HSMinstance where you want to create the key. For more information aboutSingle-tenant Cloud HSM instances, seeCreate and manage a Single-tenant Cloud HSMinstance.
What's next
- Learn aboutkey rotation.
- Learn aboutCreating and validatingsignatures.
- Learn aboutEncrypting and decrypting data with an RSAkey.
- Learn aboutRetrieving a public key.
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-19 UTC.