Rotate a key Stay organized with collections Save and categorize content based on your preferences.
This page shows how to automatically or manually rotate a key. For moreinformation about key rotation in general, seeKey rotation.
Required roles
To get the permissions that you need to rotate keys, ask your administrator to grant you the following IAM roles on your key:
- Cloud KMS Admin (
roles/cloudkms.admin) - Re-encrypt data:Cloud KMS CryptoKey Encrypter/Decrypter (
roles/cloudkms.cryptoKeyEncrypterDecrypter)
For more information about granting roles, seeManage access to projects, folders, and organizations.
These predefined roles contain the permissions required to rotate keys. To see the exact permissions that are required, expand theRequired permissions section:
Required permissions
The following permissions are required to rotate keys:
- Change primary key version:
cloudkms.cryptoKeys.update - Change or disable auto-rotate:
cloudkms.cryptoKeys.update - Create new key version:
cloudkms.cryptoKeyVersions.create - Disable old key versions:
cloudkms.cryptoKeyVersions.update - Re-encrypt data:
cloudkms.cryptoKeyVersions.useToDecryptcloudkms.cryptoKeyVersions.useToEncrypt
You might also be able to get these permissions withcustom roles or otherpredefined roles.
A single user with a custom role containing all of these permissions canrotate keys and re-encrypt data on their own. Users in the Cloud KMS Admin roleand Cloud KMS CryptoKey Encrypter/Decrypter role can work together to rotatekeys and re-encrypt data. Follow the principle ofleast privilege when assigningroles. For more details, seePermissions and roles.
When you rotate a key, data that was encrypted with previous key versions isn'tautomatically re-encrypted. To learn more, seedecrypt andre-encrypt. Rotating a key does not automaticallydisable ordestroy anyexisting key versions. Destroying key versions that are no longer needed helpsto reduce costs.
Configure automatic rotation
Note: Automatic rotation isn't supported for asymmetric signing or asymmetricencryption keys. For more information, seeConsiderations for asymmetric keys.Create a new key with a custom rotation schedule
To configure automatic rotation when creating a new key:
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.
Update an existing key to add a rotation schedule
To configure automatic rotation on an existing key:
Console
Go to theKey Management page in the Google Cloud console.
Click the name of the key ring that contains the key for which you want toadd a rotation schedule.
Click the key you want to add a rotation schedule to.
In the header, clickEdit Rotation Period.
In the prompt, choose new values for theRotation period andStartingon fields.
In the prompt, clickSave.
gcloud
To use Cloud KMS on the command line, firstInstall or upgrade to the latest version of Google Cloud CLI.
gcloud kms keys updateKEY_NAME \ --locationLOCATION \ --keyringKEY_RING \ --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 nextrotation—for example,2023-01-01T01:02:03. You can omit--next-rotation-timeto schedule the next 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;publicclassUpdateKeyAddRotationSample{publicCryptoKeyUpdateKeyAddRotation(stringprojectId="my-project",stringlocationId="us-east1",stringkeyRingId="my-key-ring",stringkeyId="my-key"){// Create the client.KeyManagementServiceClientclient=KeyManagementServiceClient.Create();// Build the key.CryptoKeykey=newCryptoKey{// Provide the name of the key to update.CryptoKeyName=newCryptoKeyName(projectId,locationId,keyRingId,keyId),// 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(),}};// Build the update mask.FieldMaskfieldMask=newFieldMask{Paths={"rotation_period","next_rotation_time"},};// Call the API.CryptoKeyresult=client.UpdateCryptoKey(key,fieldMask);// Return the updated key.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"fieldmask"google.golang.org/genproto/protobuf/field_mask""google.golang.org/protobuf/types/known/durationpb""google.golang.org/protobuf/types/known/timestamppb")// addRotationSchedule updates a key to add a rotation schedule. If the key// already has a rotation schedule, it is overwritten.funcaddRotationSchedule(wio.Writer,namestring)error{// name := "projects/my-project/locations/us-east1/keyRings/my-key-ring/cryptoKeys/my-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.UpdateCryptoKeyRequest{CryptoKey:&kmspb.CryptoKey{// Provide the name of the key to updateName:name,// 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(),},},UpdateMask:&fieldmask.FieldMask{Paths:[]string{"rotation_period","next_rotation_time"},},}// Call the API.result,err:=client.UpdateCryptoKey(ctx,req)iferr!=nil{returnfmt.Errorf("failed to update key: %w",err)}fmt.Fprintf(w,"Updated 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.CryptoKeyName;importcom.google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionAlgorithm;importcom.google.cloud.kms.v1.CryptoKeyVersionTemplate;importcom.google.cloud.kms.v1.KeyManagementServiceClient;importcom.google.protobuf.Duration;importcom.google.protobuf.FieldMask;importcom.google.protobuf.Timestamp;importcom.google.protobuf.util.FieldMaskUtil;importjava.io.IOException;importjava.time.temporal.ChronoUnit;publicclassUpdateKeyAddRotation{publicvoidupdateKeyAddRotation()throwsIOException{// TODO(developer): Replace these variables before running the sample.StringprojectId="your-project-id";StringlocationId="us-east1";StringkeyRingId="my-key-ring";StringkeyId="my-key";updateKeyAddRotation(projectId,locationId,keyRingId,keyId);}// Update a key to add or change a rotation schedule.publicvoidupdateKeyAddRotation(StringprojectId,StringlocationId,StringkeyRingId,StringkeyId)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 name from the project, location, and key ring.CryptoKeyNamecryptoKeyName=CryptoKeyName.of(projectId,locationId,keyRingId,keyId);// 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 update with a rotation schedule.CryptoKeykey=CryptoKey.newBuilder().setName(cryptoKeyName.toString()).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();// Construct the field mask.FieldMaskfieldMask=FieldMaskUtil.fromString("rotation_period,next_rotation_time");// Update the key.CryptoKeyupdatedKey=client.updateCryptoKey(key,fieldMask);System.out.printf("Updated key %s%n",updatedKey.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 keyId = 'my-key';// const versionId = '123';// Imports the Cloud KMS libraryconst{KeyManagementServiceClient}=require('@google-cloud/kms');// Instantiates a clientconstclient=newKeyManagementServiceClient();// Build the key nameconstkeyName=client.cryptoKeyPath(projectId,locationId,keyRingId,keyId);asyncfunctionupdateKeyAddRotation(){const[key]=awaitclient.updateCryptoKey({cryptoKey:{name:keyName,// 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,},},updateMask:{paths:['rotation_period','next_rotation_time'],},});console.log(`Updated rotation for:${key.name}`);returnkey;}returnupdateKeyAddRotation();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\CryptoKey;use Google\Cloud\Kms\V1\UpdateCryptoKeyRequest;use Google\Protobuf\Duration;use Google\Protobuf\FieldMask;use Google\Protobuf\Timestamp;function update_key_add_rotation( string $projectId = 'my-project', string $locationId = 'us-east1', string $keyRingId = 'my-key-ring', string $keyId = 'my-key'): CryptoKey { // Create the Cloud KMS client. $client = new KeyManagementServiceClient(); // Build the key name. $keyName = $client->cryptoKeyName($projectId, $locationId, $keyRingId, $keyId); // Build the key. $key = (new CryptoKey()) ->setName($keyName) // 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) ); // Create the field mask. $updateMask = (new FieldMask()) ->setPaths(['rotation_period', 'next_rotation_time']); // Call the API. $updateCryptoKeyRequest = (new UpdateCryptoKeyRequest()) ->setCryptoKey($key) ->setUpdateMask($updateMask); $updatedKey = $client->updateCryptoKey($updateCryptoKeyRequest); printf('Updated key: %s' . PHP_EOL, $updatedKey->getName()); return $updatedKey;}Python
To run this code, firstset up a Python development environment andinstall the Cloud KMS Python SDK.
importtimefromgoogle.cloudimportkmsdefupdate_key_add_rotation(project_id:str,location_id:str,key_ring_id:str,key_id:str)->kms.CryptoKey:""" Add a rotation schedule to an existing 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'). Returns: CryptoKey: Updated Cloud KMS key. """# Create the client.client=kms.KeyManagementServiceClient()# Build the key name.key_name=client.crypto_key_path(project_id,location_id,key_ring_id,key_id)key={"name":key_name,"rotation_period":{"seconds":60*60*24*30# Rotate the key every 30 days.},"next_rotation_time":{"seconds":int(time.time())+60*60*24# Start the first rotation in 24 hours.},}# Build the update mask.update_mask={"paths":["rotation_period","next_rotation_time"]}# Call the API.updated_key=client.update_crypto_key(request={"crypto_key":key,"update_mask":update_mask})print(f"Updated key:{updated_key.name}")returnupdated_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"# key_id = "my-key"# Require the library.require"google/cloud/kms"# Create the client.client=Google::Cloud::Kms.key_management_service# Build the parent key name.key_name=client.crypto_key_pathproject:project_id,location:location_id,key_ring:key_ring_id,crypto_key:key_id# Build the key.key={name:key_name,# 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}}# Build the field mask.update_mask={paths:["rotation_period","next_rotation_time"]}# Call the API.updated_key=client.update_crypto_keycrypto_key:key,update_mask:update_maskputs"Updated key:#{updated_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 update a key, use theCryptoKey.patchmethod:
curl "https://cloudkms.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/keyRings/KEY_RING/cryptoKeys/KEY_NAME?updateMask=rotationPeriod,nextRotationTime" \ --request "PATCH" \ --header "authorization: BearerTOKEN" \ --header "content-type: application/json" \ --data '{"rotationPeriod": "ROTATION_PERIOD", "nextRotationTime": "NEXT_ROTATION_TIME"}'Replace the following:
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 nextrotation—for example,2023-01-01T01:02:03. For more information, seeCryptoKey.nextRotationTime.
Manually rotate a key
First, create a new key version:
Console
Go to theKey Management page in the Google Cloud console.
Click the name of the key ring that contains the key for which you willcreate a new key version.
Click the key for which you will create a new key version.
In the header, clickRotate.
In the prompt, clickRotate to confirm.
gcloud
To use Cloud KMS on the command line, firstInstall or upgrade to the latest version of Google Cloud CLI.
gcloud kms keys versions create \ --keyKEY_NAME \ --keyringKEY_RING \ --locationLOCATION
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.
Key versions are numbered sequentially.
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;publicclassCreateKeyVersionSample{publicCryptoKeyVersionCreateKeyVersion(stringprojectId="my-project",stringlocationId="us-east1",stringkeyRingId="my-key-ring",stringkeyId="my-key"){// Create the client.KeyManagementServiceClientclient=KeyManagementServiceClient.Create();// Build the parent key name.CryptoKeyNamekeyName=newCryptoKeyName(projectId,locationId,keyRingId,keyId);// Build the key version.CryptoKeyVersionkeyVersion=newCryptoKeyVersion{};// Call the API.CryptoKeyVersionresult=client.CreateCryptoKeyVersion(keyName,keyVersion);// 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")// createKeyVersion creates a new key version for the given key.funccreateKeyVersion(wio.Writer,parentstring)error{// parent := "projects/my-project/locations/us-east1/keyRings/my-key-ring/cryptoKeys/my-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.CreateCryptoKeyVersionRequest{Parent:parent,}// Call the API.result,err:=client.CreateCryptoKeyVersion(ctx,req)iferr!=nil{returnfmt.Errorf("failed to create key version: %w",err)}fmt.Fprintf(w,"Created 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.KeyManagementServiceClient;importjava.io.IOException;publicclassCreateKeyVersion{publicvoidcreateKeyVersion()throwsIOException{// TODO(developer): Replace these variables before running the sample.StringprojectId="your-project-id";StringlocationId="us-east1";StringkeyRingId="my-key-ring";StringkeyId="my-key";createKeyVersion(projectId,locationId,keyRingId,keyId);}// Create a new key version.publicvoidcreateKeyVersion(StringprojectId,StringlocationId,StringkeyRingId,StringkeyId)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.CryptoKeyNamecryptoKeyName=CryptoKeyName.of(projectId,locationId,keyRingId,keyId);// Build the key version to create.CryptoKeyVersionkeyVersion=CryptoKeyVersion.newBuilder().build();// Create the key.CryptoKeyVersioncreatedVersion=client.createCryptoKeyVersion(cryptoKeyName,keyVersion);System.out.printf("Created key version %s%n",createdVersion.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 keyId = 'my-key';// Imports the Cloud KMS libraryconst{KeyManagementServiceClient}=require('@google-cloud/kms');// Instantiates a clientconstclient=newKeyManagementServiceClient();// Build the parent key nameconstkeyName=client.cryptoKeyPath(projectId,locationId,keyRingId,keyId);asyncfunctioncreateKeyVersion(){const[version]=awaitclient.createCryptoKeyVersion({parent:keyName,});console.log(`Created key version:${version.name}`);returnversion;}returncreateKeyVersion();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\CreateCryptoKeyVersionRequest;use Google\Cloud\Kms\V1\CryptoKeyVersion;function create_key_version( string $projectId = 'my-project', string $locationId = 'us-east1', string $keyRingId = 'my-key-ring', string $keyId = 'my-key'): CryptoKeyVersion { // Create the Cloud KMS client. $client = new KeyManagementServiceClient(); // Build the parent key name. $keyName = $client->cryptoKeyName($projectId, $locationId, $keyRingId, $keyId); // Build the key version. $version = new CryptoKeyVersion(); // Call the API. $createCryptoKeyVersionRequest = (new CreateCryptoKeyVersionRequest()) ->setParent($keyName) ->setCryptoKeyVersion($version); $createdVersion = $client->createCryptoKeyVersion($createCryptoKeyVersionRequest); printf('Created key version: %s' . PHP_EOL, $createdVersion->getName()); return $createdVersion;}Python
To run this code, firstset up a Python development environment andinstall the Cloud KMS Python SDK.
fromgoogle.cloudimportkmsdefcreate_key_version(project_id:str,location_id:str,key_ring_id:str,key_id:str)->kms.CryptoKey:""" Creates a new version of the given 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 for which to create a new version (e.g. 'my-key'). Returns: CryptoKeyVersion: Cloud KMS key version. """# Create the client.client=kms.KeyManagementServiceClient()# Build the parent key name.key_name=client.crypto_key_path(project_id,location_id,key_ring_id,key_id)# Build the key version.version={}# Call the API.created_version=client.create_crypto_key_version(request={"parent":key_name,"crypto_key_version":version})print(f"Created key version:{created_version.name}")returncreated_versionRuby
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"# Require the library.require"google/cloud/kms"# Create the client.client=Google::Cloud::Kms.key_management_service# Build the parent key name.key_name=client.crypto_key_pathproject:project_id,location:location_id,key_ring:key_ring_id,crypto_key:key_id# Build the version.version={}# Call the API.created_version=client.create_crypto_key_versionparent:key_name,crypto_key_version:versionputs"Created key version:#{created_version.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 manually rotate a key, first create a new key version by calling theCryptoKeyVersions.createmethod.
curl "https://cloudkms.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/keyRings/KEY_RING/cryptoKeys/KEY_NAME/cryptoKeyVersions" \ --request "POST" \ --header "authorization: BearerTOKEN"
This command creates a new key version, but doesn't set it as the primary version.
To set your new key version as primary, seeSetting an existing version as theprimary key version.
If necessary,re-encrypt data that was encryptedusing the previous key version.
Set an existing version as the primary key version
To set different key version as the primary version for a key, updatethe key with the new primary version information. A key version must be enabledbefore you can configure it as the primary version.
Console
Go to theKey Management page in the Google Cloud console.
Click the name of the key ring that contains the key whose primary versionyou want to update.
Click the key whose primary version you want to update.
On the row corresponding to the key version you want to make primary, clickView More.
ClickMake primary version in menu.
In the confirmation prompt, clickMake primary.
gcloud
To use Cloud KMS on the command line, firstInstall or upgrade to the latest version of Google Cloud CLI.
gcloud kms keys updateKEY_NAME \ --keyringKEY_RING \ --locationLOCATION \--primary-versionKEY_VERSION
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.- KEY_VERSION: the version number of the new primary key version.
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;publicclassUpdateKeySetPrimarySample{publicCryptoKeyUpdateKeySetPrimary(stringprojectId="my-project",stringlocationId="us-east1",stringkeyRingId="my-key-ring",stringkeyId="my-key",stringkeyVersionId="123"){// Create the client.KeyManagementServiceClientclient=KeyManagementServiceClient.Create();// Build the key name.CryptoKeyNamekeyName=newCryptoKeyName(projectId,locationId,keyRingId,keyId);// Call the API.CryptoKeyresult=client.UpdateCryptoKeyPrimaryVersion(keyName,keyVersionId);// Return the updated key.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")// updateKeySetPrimary updates the primary key version on a Cloud KMS key.funcupdateKeySetPrimary(wio.Writer,name,versionstring)error{// name := "projects/my-project/locations/us-east1/keyRings/my-key-ring/cryptoKeys/my-key"// version := "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.UpdateCryptoKeyPrimaryVersionRequest{Name:name,CryptoKeyVersionId:version,}// Call the API.result,err:=client.UpdateCryptoKeyPrimaryVersion(ctx,req)iferr!=nil{returnfmt.Errorf("failed to update key: %w",err)}fmt.Fprintf(w,"Updated key primary: %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.CryptoKeyName;importcom.google.cloud.kms.v1.KeyManagementServiceClient;importjava.io.IOException;publicclassUpdateKeySetPrimary{publicvoidupdateKeySetPrimary()throwsIOException{// 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";updateKeySetPrimary(projectId,locationId,keyRingId,keyId,keyVersionId);}// Update a key's primary version.publicvoidupdateKeySetPrimary(StringprojectId,StringlocationId,StringkeyRingId,StringkeyId,StringkeyVersionId)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 name from the project, location, key ring, and keyId.CryptoKeyNamecryptoKeyName=CryptoKeyName.of(projectId,locationId,keyRingId,keyId);// Create the key.CryptoKeycreatedKey=client.updateCryptoKeyPrimaryVersion(cryptoKeyName,keyVersionId);System.out.printf("Updated key primary version %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 keyId = 'my-key';// const versionId = '123';// Imports the Cloud KMS libraryconst{KeyManagementServiceClient}=require('@google-cloud/kms');// Instantiates a clientconstclient=newKeyManagementServiceClient();// Build the key nameconstkeyName=client.cryptoKeyPath(projectId,locationId,keyRingId,keyId);asyncfunctionupdateKeySetPrimary(){const[key]=awaitclient.updateCryptoKeyPrimaryVersion({name:keyName,cryptoKeyVersionId:versionId,});console.log(`Set primary to${versionId}`);returnkey;}returnupdateKeySetPrimary();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\UpdateCryptoKeyPrimaryVersionRequest;function update_key_set_primary( 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 name. $keyName = $client->cryptoKeyName($projectId, $locationId, $keyRingId, $keyId); // Call the API. $updateCryptoKeyPrimaryVersionRequest = (new UpdateCryptoKeyPrimaryVersionRequest()) ->setName($keyName) ->setCryptoKeyVersionId($versionId); $updatedKey = $client->updateCryptoKeyPrimaryVersion($updateCryptoKeyPrimaryVersionRequest); printf('Updated primary %s to %s' . PHP_EOL, $updatedKey->getName(), $versionId); return $updatedKey;}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 parent key name.key_name=client.crypto_key_pathproject:project_id,location:location_id,key_ring:key_ring_id,crypto_key:key_id# Call the API.updated_key=client.update_crypto_key_primary_versionname:key_name,crypto_key_version_id:version_idputs"Updated primary#{updated_key.name} to#{version_id}"Python
To run this code, firstset up a Python development environment andinstall the Cloud KMS Python SDK.
fromgoogle.cloudimportkmsdefupdate_key_set_primary(project_id:str,location_id:str,key_ring_id:str,key_id:str,version_id:str)->kms.CryptoKey:""" Update the primary version of a 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 make primary (e.g. '2'). Returns: CryptoKey: Updated Cloud KMS key. """# Create the client.client=kms.KeyManagementServiceClient()# Build the key name.key_name=client.crypto_key_path(project_id,location_id,key_ring_id,key_id)# Call the API.updated_key=client.update_crypto_key_primary_version(request={"name":key_name,"crypto_key_version_id":version_id})print(f"Updated{updated_key.name} primary to{version_id}")returnupdated_keyAPI
These examples usecurl as an HTTP client to demonstrate using the API. For more information about access control, seeAccessing the Cloud KMS API.
Change the primary key version by calling theCryptoKey.updatePrimaryVersionmethod.
curl "https://cloudkms.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/keyRings/KEY_RING/cryptoKeys/KEY_NAME:updatePrimaryVersion" \ --request "POST" \ --header "authorization: BearerTOKEN" \ --header "content-type: application/json" \ --data '{"cryptoKeyVersionId": "KEY_VERSION"}'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 version number of the new primary key version.
When you change the primary key version, the change typically becomes consistentwithin 1 minute. However, this change can take up to 3 hours to propagate inexceptional cases. During this time, the prior primary version might be used toencrypt data. For more information, seeCloud KMS resource consistency.
Disable automatic rotation
To disable automatic rotation on a key, clear the rotation schedule of the key:
Console
Go to theKey Management page in the Google Cloud console.
Click the name of the key ring that contains the key for which you want toremove the rotation schedule.
Click the key you want to remove the rotation schedule from.
In the header, clickEdit Rotation Period.
In the prompt, click theRotation period field and selectNever(manual rotation).
In the prompt, clickSave.
gcloud
To use Cloud KMS on the command line, firstInstall or upgrade to the latest version of Google Cloud CLI.
gcloud kms keys updateKEY_NAME \ --keyringKEY_RING \ --locationLOCATION \--remove-rotation-schedule
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.
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;publicclassUpdateKeyRemoveRotationSample{publicCryptoKeyUpdateKeyRemoveRotation(stringprojectId="my-project",stringlocationId="us-east1",stringkeyRingId="my-key-ring",stringkeyId="my-key"){// Create the client.KeyManagementServiceClientclient=KeyManagementServiceClient.Create();// Build the key.CryptoKeykey=newCryptoKey{CryptoKeyName=newCryptoKeyName(projectId,locationId,keyRingId,keyId),RotationPeriod=null,NextRotationTime=null,};// Build the update mask.FieldMaskfieldMask=newFieldMask{Paths={"rotation_period","next_rotation_time"},};// Call the API.CryptoKeyresult=client.UpdateCryptoKey(key,fieldMask);// Return the updated key.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"fieldmask"google.golang.org/genproto/protobuf/field_mask")// removeRotationSchedule updates a key to remove a rotation schedule, if one// exists.funcremoveRotationSchedule(wio.Writer,namestring)error{// name := "projects/my-project/locations/us-east1/keyRings/my-key-ring/cryptoKeys/my-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.UpdateCryptoKeyRequest{CryptoKey:&kmspb.CryptoKey{// Provide the name of the key to updateName:name,// Remove any rotation fields.RotationSchedule:nil,NextRotationTime:nil,},UpdateMask:&fieldmask.FieldMask{Paths:[]string{"rotation_period","next_rotation_time"},},}// Call the API.result,err:=client.UpdateCryptoKey(ctx,req)iferr!=nil{returnfmt.Errorf("failed to update key: %w",err)}fmt.Fprintf(w,"Updated 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.CryptoKeyName;importcom.google.cloud.kms.v1.KeyManagementServiceClient;importcom.google.protobuf.FieldMask;importcom.google.protobuf.util.FieldMaskUtil;importjava.io.IOException;publicclassUpdateKeyRemoveRotation{publicvoidupdateKeyRemoveRotation()throwsIOException{// TODO(developer): Replace these variables before running the sample.StringprojectId="your-project-id";StringlocationId="us-east1";StringkeyRingId="my-key-ring";StringkeyId="my-key";updateKeyRemoveRotation(projectId,locationId,keyRingId,keyId);}// Update a key to remove all labels.publicvoidupdateKeyRemoveRotation(StringprojectId,StringlocationId,StringkeyRingId,StringkeyId)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 name from the project, location, key ring, and keyId.CryptoKeyNamecryptoKeyName=CryptoKeyName.of(projectId,locationId,keyRingId,keyId);// Build an empty key with no labels.CryptoKeykey=CryptoKey.newBuilder().setName(cryptoKeyName.toString()).clearRotationPeriod().clearNextRotationTime().build();// Construct the field mask.FieldMaskfieldMask=FieldMaskUtil.fromString("rotation_period,next_rotation_time");// Create the key.CryptoKeycreatedKey=client.updateCryptoKey(key,fieldMask);System.out.printf("Updated 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 keyId = 'my-key';// Imports the Cloud KMS libraryconst{KeyManagementServiceClient}=require('@google-cloud/kms');// Instantiates a clientconstclient=newKeyManagementServiceClient();// Build the key nameconstkeyName=client.cryptoKeyPath(projectId,locationId,keyRingId,keyId);asyncfunctionupdateKeyRemoveRotation(){const[key]=awaitclient.updateCryptoKey({cryptoKey:{name:keyName,rotationPeriod:null,nextRotationTime:null,},updateMask:{paths:['rotation_period','next_rotation_time'],},});console.log(`Removed rotation for:${key.name}`);returnkey;}returnupdateKeyRemoveRotation();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\CryptoKey;use Google\Cloud\Kms\V1\UpdateCryptoKeyRequest;use Google\Protobuf\FieldMask;function update_key_remove_rotation( string $projectId = 'my-project', string $locationId = 'us-east1', string $keyRingId = 'my-key-ring', string $keyId = 'my-key'): CryptoKey { // Create the Cloud KMS client. $client = new KeyManagementServiceClient(); // Build the key name. $keyName = $client->cryptoKeyName($projectId, $locationId, $keyRingId, $keyId); // Build the key. $key = (new CryptoKey()) ->setName($keyName); // Create the field mask. $updateMask = (new FieldMask()) ->setPaths(['rotation_period', 'next_rotation_time']); // Call the API. $updateCryptoKeyRequest = (new UpdateCryptoKeyRequest()) ->setCryptoKey($key) ->setUpdateMask($updateMask); $updatedKey = $client->updateCryptoKey($updateCryptoKeyRequest); printf('Updated key: %s' . PHP_EOL, $updatedKey->getName()); return $updatedKey;}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"# Require the library.require"google/cloud/kms"# Create the client.client=Google::Cloud::Kms.key_management_service# Build the parent key name.key_name=client.crypto_key_pathproject:project_id,location:location_id,key_ring:key_ring_id,crypto_key:key_id# Build the key.key={name:key_name,rotation_period:nil,next_rotation_time:nil}# Build the field mask.update_mask={paths:["rotation_period","next_rotation_time"]}# Call the API.updated_key=client.update_crypto_keycrypto_key:key,update_mask:update_maskputs"Updated key:#{updated_key.name}"Python
To run this code, firstset up a Python development environment andinstall the Cloud KMS Python SDK.
fromgoogle.cloudimportkmsdefupdate_key_remove_rotation(project_id:str,location_id:str,key_ring_id:str,key_id:str)->kms.CryptoKey:""" Remove a rotation schedule from an existing 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'). Returns: CryptoKey: Updated Cloud KMS key. """# Create the client.client=kms.KeyManagementServiceClient()# Build the key name.key_name=client.crypto_key_path(project_id,location_id,key_ring_id,key_id)key={"name":key_name}# Build the update mask.update_mask={"paths":["rotation_period","next_rotation_time"]}# Call the API.updated_key=client.update_crypto_key(request={"crypto_key":key,"update_mask":update_mask})print(f"Updated key:{updated_key.name}")returnupdated_keyAPI
These examples usecurl as an HTTP client to demonstrate using the API. For more information about access control, seeAccessing the Cloud KMS API.
To update a key, use theCryptoKey.patchmethod:
curl "https://cloudkms.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/keyRings/KEY_RING/cryptoKeys/KEY_NAME?updateMask=rotationPeriod,nextRotationTime" \ --request "PATCH" \ --header "authorization: BearerTOKEN" \ --header "content-type: application/json" \ --data '{"rotationPeriod": null, "nextRotationTime": null}'For additional details aboutrotationPeriod andnextRotationTime, seekeyRings.cryptoKeys.
Rotate an external key
Rotate a coordinated external key
You canconfigure automatic rotation for symmetric coordinatedexternal keys. You can also manually create a new key version for symmetric orasymmetric coordinated external keys.
Rotating or creating a new key version causes all newly created data protectedwith that key to be encrypted with the new key version. Data protected witha previous key version isn't re-encrypted. As a result, your external keymanager must continue to make the key material of the previous key versionavailable to be used.
To create a new key version for a coordinated external key, complete the following steps:
Console
In the Google Cloud console, go to theKey Management page.
Select the key ring, and then select the key.
ClickCreate version. A message indicates that your new key versionwill be generated in both Cloud KMS and your EKM. If you see aKey path orKey URI field, the selected key isn't a coordinatedexternal key.
To confirm that you want to create a new key version, clickCreateversion.
The new key version appears inPending generation state. For symmetrickeys, manually created key versions aren't automatically set as theprimary key version. You canset your new key version asprimary.
gcloud CLI
To create a new symmetric key version and set it as the primary key version,use thekms keys versions create command with the--primary flag:
gcloud kms keys versions create \ --keyKEY_NAME \ --keyringKEY_RING \ --locationLOCATION \ --primary
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.
To create a new asymmetric key version or to create a new symmetric keyversion that isn't the primary key version, use thekms keys versionscreate command:
gcloud kms keys versions create \ --keyKEY_NAME \ --keyringKEY_RING \ --locationLOCATION
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.
Rotate a manually managed Cloud EKM via VPC key
First, rotate the external key material on your external key manager. If thatresults in a new key path, you need to rotate or create a new Cloud EKMkey version with the new key path. For symmetric encryption keys,rotate theCloud EKM key and specify the new key path from your external keymanager. For asymmetric keys,create a new key version and specify the new keypath.
Rotating or creating a new key version causes all newly created data protectedwith that key to be encrypted with the new key version. Data protected witha previous key version isn't re-encrypted. As a result, your external keymanager must continue to make the key material of the previous key versionavailable to be used.
If the key material in the external key management partner system doesn't change, but the keypath changes, you canupdate the key's externalpath without rotating the key.
Console
In the Google Cloud console, go to theKey Management page.
Select the key ring, and then select the key.
ClickRotate key.
ForKey path, enter the key path for the new version.
ClickRotate Key to confirm.
gcloud
To use Cloud KMS on the command line, firstInstall or upgrade to the latest version of Google Cloud CLI.
To create a new symmetric key version and set it as the primary key version,use thekms keys versions create command with the--primary flag:
gcloud kms keys versions create \ --keyKEY_NAME \ --keyringKEY_RING \ --locationLOCATION \ --ekm-connection-key-pathEXTERNAL_KEY_PATH \ --primary
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.EXTERNAL_KEY_PATH: the path to the new externalkey version.
To create a new asymmetric key version or to create a new symmetric keyversion that isn't the primary key version, use thekms keys versionscreate command:
gcloud kms keys versions create \ --keyKEY_NAME \ --keyringKEY_RING \ --locationLOCATION \ --ekm-connection-key-pathEXTERNAL_KEY_PATH
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.EXTERNAL_KEY_PATH: the path to the new externalkey version.
For information on all flags and possible values, run the command with the--help flag.
After the key version is successfully created, you can use it just as you woulduse any other Cloud KMS key version.
Rotate a manually managed Cloud EKM via internet key
First, rotate the external key material on your external key manager. If thatresults in a new URI, you need to rotate or create a new Cloud EKM keyversion with the new URI. For symmetric encryption keys,rotate theCloud EKM key and specify the new key URI from your external keymanager. For asymmetric keys,create a new key version and specify the new keyURI.
Rotating or creating a new key version causes all newly created data protectedwith that key to be encrypted with the new key version. Data protected witha previous key version isn't re-encrypted. As a result, your external keymanager must continue to make the key material of the previous key versionavailable to be used.
If the key material in the external key management partner system doesn't change, but the URIchanges, you canupdate the key's externalURI without rotating the key.
Console
In the Google Cloud console, go to theKey Management page.
Select the key ring, and then select the key.
SelectRotate key for symmetric keys orCreate version forasymmetric keys.
Enter the new key URI, then selectRotate Key for symmetric keys orCreate version for asymmetric keys.
The new key version becomes the primary version.
gcloud CLI
To create a new symmetric key version and set it as the primary key version,use thekms keys versions create command with the--primary flag:
gcloud kms keys versions create \ --keyKEY_NAME \ --keyringKEY_RING \ --locationLOCATION \ --external-key-uriEXTERNAL_KEY_URI \ --primary
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.EXTERNAL_KEY_URI: the key URI of the new externalkey version.
To create a new asymmetric key version or to create a new symmetric keyversion that isn't the primary key version, use thekms keys versionscreate command:
gcloud kms keys versions create \ --keyKEY_NAME \ --keyringKEY_RING \ --locationLOCATION \ --external-key-uriEXTERNAL_KEY_URI
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.EXTERNAL_KEY_URI: the key URI of the new externalkey version.
What's next
- After rotating a key, you canre-encryptdata that was encrypted with that key.
- After you re-encrypt your data, you cancheck whether the key version is inuse.
- After you have confirmed that a key version is no longer in use, you candestroy a key version.
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 2025-12-17 UTC.