Rotate a key

This page shows how to automatically or manually rotate a key. For more information about key rotation in general, see Key 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:

For more information about granting roles, see Manage 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 the Required 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.useToDecrypt
    • cloudkms.cryptoKeyVersions.useToEncrypt

You might also be able to get these permissions with custom roles or other predefined roles.

A single user with a custom role containing all of these permissions can rotate keys and re-encrypt data on their own. Users in the Cloud KMS Admin role and Cloud KMS CryptoKey Encrypter/Decrypter role can work together to rotate keys and re-encrypt data. Follow the principle of least privilege when assigning roles. For more details, see Permissions and roles.

When you rotate a key, data that was encrypted with previous key versions isn't automatically re-encrypted. To learn more, see decrypt and re-encrypt. Rotating a key does not automatically disable or destroy any existing key versions. Destroying key versions that are no longer needed helps to reduce costs.

Configure automatic rotation

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 the rotation period and next rotation time automatically. You can choose to use the default values or specify different values.

To specify a different rotation period and starting time, when you're creating your key, but before you click the Create button:

  1. For Key rotation period, select an option.

  2. For Starting on, select the date when you want the first automatic rotation to happen. You can leave Starting on at its default value to start the first automatic rotation one key rotation period from when you create the key.

gcloud

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

gcloud kms keys create KEY_NAME \
    --keyring KEY_RING \
    --location LOCATION \
    --purpose "encryption" \
    --rotation-period ROTATION_PERIOD \
    --next-rotation-time NEXT_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 to rotate the key—for example, 30d to rotate the key every 30 days. The rotation period must be at least 1 day and at most 100 years. For more information, see CryptoKey.rotationPeriod.
  • NEXT_ROTATION_TIME: the timestamp at which to complete the first rotation—for example, 2023-01-01T01:02:03. You can omit --next-rotation-time to schedule the first rotation for one rotation period from when you run the command. For more information, see CryptoKey.nextRotationTime.

For information on all flags and possible values, run the command with the --help flag.

C#

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


using Google.Cloud.Kms.V1;
using Google.Protobuf.WellKnownTypes;
using System;

public class CreateKeyRotationScheduleSample
{
    public CryptoKey CreateKeyRotationSchedule(
      string projectId = "my-project", string locationId = "us-east1", string keyRingId = "my-key-ring",
      string id = "my-key-with-rotation-schedule")
    {
        // Create the client.
        KeyManagementServiceClient client = KeyManagementServiceClient.Create();

        // Build the parent key ring name.
        KeyRingName keyRingName = new KeyRingName(projectId, locationId, keyRingId);

        // Build the key.
        CryptoKey key = new CryptoKey
        {
            Purpose = CryptoKey.Types.CryptoKeyPurpose.EncryptDecrypt,
            VersionTemplate = new CryptoKeyVersionTemplate
            {
                Algorithm = CryptoKeyVersion.Types.CryptoKeyVersionAlgorithm.GoogleSymmetricEncryption,
            },

            // Rotate the key every 30 days.
            RotationPeriod = new Duration
            {
                Seconds = 60 * 60 * 24 * 30, // 30 days
            },

            // Start the first rotation in 24 hours.
            NextRotationTime = new Timestamp
            {
                Seconds = new DateTimeOffset(DateTime.UtcNow.AddHours(24)).ToUnixTimeSeconds(),
            }
        };

        // Call the API.
        CryptoKey result = client.CreateCryptoKey(keyRingName, id, key);

        // Return the result.
        return result;
    }
}

Go

To run this code, first set up a Go development environment and install 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.
func createKeyRotationSchedule(w io.Writer, parent, id string) 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)
	if err != nil {
		return fmt.Errorf("failed to create kms client: %w", err)
	}
	defer client.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 days
			RotationSchedule: &kmspb.CryptoKey_RotationPeriod{
				RotationPeriod: &durationpb.Duration{
					Seconds: int64(60 * 60 * 24 * 30), // 30 days
				},
			},

			// Start the first rotation in 24 hours
			NextRotationTime: &timestamppb.Timestamp{
				Seconds: time.Now().Add(24 * time.Hour).Unix(),
			},
		},
	}

	// Call the API.
	result, err := client.CreateCryptoKey(ctx, req)
	if err != nil {
		return fmt.Errorf("failed to create key: %w", err)
	}
	fmt.Fprintf(w