Schlüssel rotieren

Auf dieser Seite wird beschrieben, wie Sie einen Schlüssel automatisch oder manuell rotieren können. Weitere Informationen zur Schlüsselrotation im Allgemeinen finden Sie unter Schlüsselrotation.

Erforderliche Rollen

Bitten Sie Ihren Administrator, Ihnen die folgenden IAM-Rollen für den Schlüssel zu gewähren, damit Sie die Berechtigungen erhalten, die Sie zum Rotieren von Schlüsseln benötigen:

Weitere Informationen zum Zuweisen von Rollen finden Sie unter Zugriff verwalten.

Diese vordefinierten Rollen enthalten die Berechtigungen, die zum Rotieren von Schlüsseln erforderlich sind. Erweitern Sie den Abschnitt Erforderliche Berechtigungen, um die erforderlichen Berechtigungen anzuzeigen:

Erforderliche Berechtigungen

Die folgenden Berechtigungen sind für das Rotieren von Schlüsseln erforderlich:

  • Primärschlüsselversion ändern: cloudkms.cryptoKeys.update
  • Automatisches Drehen ändern oder deaktivieren: cloudkms.cryptoKeys.update
  • Neue Schlüsselversion erstellen: cloudkms.cryptoKeyVersions.create
  • Alte Schlüsselversionen deaktivieren: cloudkms.cryptoKeyVersions.update
  • Daten neu verschlüsseln:
    • cloudkms.cryptoKeyVersions.useToDecrypt
    • cloudkms.cryptoKeyVersions.useToEncrypt

Möglicherweise können Sie diese Berechtigungen auch mit benutzerdefinierten Rollen oder anderen vordefinierten Rollen erhalten.

Ein einzelner Nutzer mit einer benutzerdefinierten Rolle, die alle diese Berechtigungen enthält, kann Schlüssel rotieren und Daten neu verschlüsseln. Nutzer mit den Rollen „Cloud KMS-Administrator“ und „Cloud KMS CryptoKey Encrypter/Decrypter“ können gemeinsam Schlüssel rotieren und Daten neu verschlüsseln. Folgen Sie beim Zuweisen von Rollen dem Prinzip der geringsten Berechtigung. Weitere Informationen finden Sie unter Berechtigungen und Rollen.

Wenn Sie einen Schlüssel rotieren, werden Daten, die mit früheren Schlüsselversionen verschlüsselt wurden, nicht automatisch neu verschlüsselt. Weitere Informationen finden Sie unter Entschlüsseln und neu verschlüsseln. Durch die Rotation eines Schlüssels werden vorhandene Schlüsselversionen nicht automatisch deaktiviert oder destroy.

Automatische Rotation konfigurieren

So konfigurieren Sie die automatische Rotation beim Erstellen eines neuen Schlüssels:

Console

Wenn Sie die Google Cloud Console zum Erstellen eines Schlüssels verwenden, legt Cloud KMS den Rotationszeitraum und die nächste Rotationszeit automatisch fest. Sie können die Standardwerte verwenden oder andere Werte angeben.

So können Sie beim Erstellen des Schlüssels, aber bevor Sie auf die Schaltfläche Erstellen klicken, einen anderen Rotationszeitraum und einen anderen Beginn angeben:

  1. Wählen Sie für Schlüsselrotationszeitraum eine Option aus.

  2. Wählen Sie unter Ab dem das Datum aus, an dem die erste automatische Rotation erfolgen soll. Sie können Beginnt am auf dem Standardwert belassen, um die erste automatische Rotation um einen Schlüsselrotationszeitraum nach dem Erstellen des Schlüssels zu starten.

gcloud

Wenn Sie Cloud KMS in der Befehlszeile verwenden möchten, müssen Sie zuerst die neueste Version der Google Cloud CLI installieren oder ein Upgrade auf die neueste Version durchführen.

gcloud kms keys create KEY_NAME \
    --keyring KEY_RING \
    --location LOCATION \
    --purpose "encryption" \
    --rotation-period ROTATION_PERIOD \
    --next-rotation-time NEXT_ROTATION_TIME

Ersetzen Sie Folgendes:

  • KEY_NAME: Der Name des Schlüssels.
  • KEY_RING: der Name des Schlüsselbunds, der den Schlüssel enthält.
  • LOCATION: der Cloud KMS-Speicherort des Schlüsselbunds.
  • ROTATION_PERIOD: Das Intervall, in dem der Schlüssel rotiert wird, z. B. 30d, damit der Schlüssel alle 30 Tage rotiert wird. Der Rotationszeitraum muss mindestens 1 Tag und darf höchstens 100 Jahre betragen. Weitere Informationen finden Sie unter CryptoKey.rotationPeriod.
  • NEXT_ROTATION_TIME: der Zeitstempel, zu dem die erste Rotation abgeschlossen werden soll, z. B. "2023-01-01T01:02:03". Sie können --next-rotation-time weglassen, um die erste Rotation 7 Tage nach Ausführung des Befehls zu planen. Weitere Informationen finden Sie unter CryptoKey.nextRotationTime.

Wenn Sie Informationen zu allen Flags und möglichen Werten erhalten möchten, führen Sie den Befehl mit dem Flag --help aus.

C#

Um diesen Code auszuführen, müssen Sie zuerst eine C#-Entwicklungsumgebung einrichten und das Cloud KMS C# SDK installieren.


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

Um diesen Code auszuführen, müssen Sie zuerst eine Go-Entwicklungsumgebung einrichten und das Cloud KMS Go SDK installieren.

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, "Created key: %s\n", result.Name)
	return nil
}

Java

Um diesen Code auszuführen, müssen Sie zuerst eine Java-Entwicklungsumgebung einrichten und das Cloud KMS Java SDK installieren.

import com.google.cloud.kms.v1.CryptoKey;
import com.google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose;
import com.google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionAlgorithm;
import com.google.cloud.kms.v1.CryptoKeyVersionTemplate;
import com.google.cloud.kms.v1.KeyManagementServiceClient;
import com.google.cloud.kms.v1.KeyRingName;
import com.google.protobuf.Duration;
import com.google.protobuf.Timestamp;
import java.io.IOException;
import java.time.temporal.ChronoUnit;

public class CreateKeyRotationSchedule {

  public void createKeyRotationSchedule() throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "your-project-id";
    String locationId = "us-east1";
    String keyRingId = "my-key-ring";
    String id = "my-key";
    createKeyRotationSchedule(projectId, locationId, keyRingId, id);
  }

  // Create a new key that automatically rotates on a schedule.
  public void createKeyRotationSchedule(
      String projectId, String locationId, String keyRingId, String id) throws IOException {
    // 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 (KeyManagementServiceClient client = KeyManagementServiceClient.create()) {
      // Build the parent name from the project, location, and key ring.
      KeyRingName keyRingName = KeyRingName.of(projectId, locationId, keyRingId);

      // Calculate the date 24 hours from now (this is used below).
      long tomorrow = java.time.Instant.now().plus(24, ChronoUnit.HOURS).getEpochSecond();

      // Build the key to create with a rotation schedule.
      CryptoKey key =
          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.
      CryptoKey createdKey = client.createCryptoKey(keyRingName, id, key);
      System.out.printf("Created key with rotation schedule %s%n", createdKey.getName());
    }
  }
}

Node.js

Um diesen Code auszuführen, richten Sie zuerst eine Node.js-Entwicklungsumgebung ein und installieren Sie das 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 library
const {KeyManagementServiceClient} = require('@google-cloud/kms');

// Instantiates a client
const client = new KeyManagementServiceClient();

// Build the parent key ring name
const keyRingName = client.keyRingPath(projectId, locationId, keyRingId);

async function createKeyRotationSchedule() {
  const [key] = await client.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: new Date().getTime() / 1000 + 60 * 60 * 24,
      },
    },
  });

  console.log(`Created rotating key: ${key.name}`);
  return key;
}

return createKeyRotationSchedule();

PHP

Um diesen Code auszuführen, müssen Sie zuerst PHP in Google Cloud verwenden lernen und das Cloud KMS PHP SDK installieren.

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

Um diesen Code auszuführen, müssen Sie zuerst eine Python-Entwicklungsumgebung einrichten und das Cloud KMS Python SDK installieren.

import time

from google.cloud import kms

def create_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_DECRYPT
    algorithm = (
        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}")
    return created_key

Ruby

Um diesen Code auszuführen, müssen Sie zuerst eine Ruby-Entwicklungsumgebung einrichten und das Cloud KMS Ruby SDK installieren.

# 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_path project: 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_key parent: key_ring_name, crypto_key_id: id, crypto_key: key
puts "Created rotating key: #{created_key.name}"

API

In diesen Beispielen wird curl als HTTP-Client verwendet, um die Verwendung der API zu demonstrieren. Weitere Informationen zur Zugriffssteuerung finden Sie unter Auf die Cloud KMS API zugreifen.

Verwenden Sie zum Erstellen eines Schlüssels die Methode CryptoKey.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: Bearer TOKEN" \
    --header "content-type: application/json" \
    --data '{"purpose": "PURPOSE", "rotationPeriod": "ROTATION_PERIOD", "nextRotationTime": "NEXT_ROTATION_TIME"}'

Ersetzen Sie Folgendes:

  • PURPOSE: der Zweck des Schlüssels.
  • ROTATION_PERIOD: Das Intervall, in dem der Schlüssel rotiert wird, z. B. 30d, damit der Schlüssel alle 30 Tage rotiert wird. Der Rotationszeitraum muss mindestens 1 Tag und darf höchstens 100 Jahre betragen. Weitere Informationen finden Sie unter CryptoKey.rotationPeriod.
  • NEXT_ROTATION_TIME: der Zeitstempel, zu dem die erste Rotation abgeschlossen werden soll, z. B. "2023-01-01T01:02:03". Sie können --next-rotation-time weglassen, um die erste Rotation 7 Tage nach Ausführung des Befehls zu planen. Weitere Informationen finden Sie unter CryptoKey.nextRotationTime.

So konfigurieren Sie die automatische Rotation für einen vorhandenen Schlüssel:

Console

  1. Rufen Sie in der Google Cloud Console die Seite Schlüsselverwaltung auf.

    Zur Seite „Schlüsselverwaltung“

  2. Klicken Sie auf den Namen des Schlüsselbunds, der den Schlüssel enthält, für den Sie einen Rotationsplan hinzufügen möchten.

  3. Klicken Sie auf den Schlüssel, dem Sie einen Rotationsplan hinzufügen möchten.

  4. Klicken Sie in der Kopfzeile auf Rotationszeitraum bearbeiten.

  5. Wählen Sie in der Eingabeaufforderung neue Werte für die Felder Rotationszeitraum und Beginnt am aus.

  6. Klicken Sie in der Eingabeaufforderung auf Speichern.

gcloud

Wenn Sie Cloud KMS in der Befehlszeile verwenden möchten, müssen Sie zuerst die neueste Version der Google Cloud CLI installieren oder ein Upgrade auf die neueste Version durchführen.

gcloud kms keys update KEY_NAME \
    --location LOCATION \
    --keyring KEY_RING \
    --rotation-period ROTATION_PERIOD \
    --next-rotation-time NEXT_ROTATION_TIME

Ersetzen Sie Folgendes:

  • KEY_NAME: Der Name des Schlüssels.
  • KEY_RING: der Name des Schlüsselbunds, der den Schlüssel enthält.
  • LOCATION: der Cloud KMS-Speicherort des Schlüsselbunds.
  • ROTATION_PERIOD: Das Intervall, in dem der Schlüssel rotiert wird, z. B. 30d, damit der Schlüssel alle 30 Tage rotiert wird. Der Rotationszeitraum muss mindestens 1 Tag und darf höchstens 100 Jahre betragen. Weitere Informationen finden Sie unter CryptoKey.rotationPeriod.
  • NEXT_ROTATION_TIME: der Zeitstempel, zu dem die erste Rotation abgeschlossen werden soll, z. B. "2023-01-01T01:02:03". Sie können --next-rotation-time weglassen, um die erste Rotation 7 Tage nach Ausführung des Befehls zu planen. Weitere Informationen finden Sie unter CryptoKey.nextRotationTime.

Wenn Sie Informationen zu allen Flags und möglichen Werten erhalten möchten, führen Sie den Befehl mit dem Flag --help aus.

C#

Um diesen Code auszuführen, müssen Sie zuerst eine C#-Entwicklungsumgebung einrichten und das Cloud KMS C# SDK installieren.


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

public class UpdateKeyAddRotationSample
{
    public CryptoKey UpdateKeyAddRotation(string projectId = "my-project", string locationId = "us-east1", string keyRingId = "my-key-ring", string keyId = "my-key")
    {
        // Create the client.
        KeyManagementServiceClient client = KeyManagementServiceClient.Create();

        // Build the key.
        CryptoKey key = new CryptoKey
        {
            // Provide the name of the key to update.
            CryptoKeyName = new CryptoKeyName(projectId, locationId, keyRingId, keyId),

            // 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(),
            }
        };

        // Build the update mask.
        FieldMask fieldMask = new FieldMask
        {
            Paths = { "rotation_period", "next_rotation_time" },
        };

        // Call the API.
        CryptoKey result = client.UpdateCryptoKey(key, fieldMask);

        // Return the updated key.
        return result;
    }
}

Go

Um diesen Code auszuführen, müssen Sie zuerst eine Go-Entwicklungsumgebung einrichten und das Cloud KMS Go SDK installieren.

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.
func addRotationSchedule(w io.Writer, name string) 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)
	if err != nil {
		return fmt.Errorf("failed to create kms client: %w", err)
	}
	defer client.Close()

	// Build the request.
	req := &kmspb.UpdateCryptoKeyRequest{
		CryptoKey: &kmspb.CryptoKey{
			// Provide the name of the key to update
			Name: name,

			// 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(),
			},
		},
		UpdateMask: &fieldmask.FieldMask{
			Paths: []string{"rotation_period", "next_rotation_time"},
		},
	}

	// Call the API.
	result, err := client.UpdateCryptoKey(ctx, req)
	if err != nil {
		return fmt.Errorf("failed to update key: %w", err)
	}
	fmt.Fprintf(w, "Updated key: %s\n", result.Name)
	return nil
}

Java

Um diesen Code auszuführen, müssen Sie zuerst eine Java-Entwicklungsumgebung einrichten und das Cloud KMS Java SDK installieren.

import com.google.cloud.kms.v1.CryptoKey;
import com.google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose;
import com.google.cloud.kms.v1.CryptoKeyName;
import com.google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionAlgorithm;
import com.google.cloud.kms.v1.CryptoKeyVersionTemplate;
import com.google.cloud.kms.v1.KeyManagementServiceClient;
import com.google.protobuf.Duration;
import com.google.protobuf.FieldMask;
import com.google.protobuf.Timestamp;
import com.google.protobuf.util.FieldMaskUtil;
import java.io.IOException;
import java.time.temporal.ChronoUnit;

public class UpdateKeyAddRotation {

  public void updateKeyAddRotation() throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "your-project-id";
    String locationId = "us-east1";
    String keyRingId = "my-key-ring";
    String keyId = "my-key";
    updateKeyAddRotation(projectId, locationId, keyRingId, keyId);
  }

  // Update a key to add or change a rotation schedule.
  public void updateKeyAddRotation(
      String projectId, String locationId, String keyRingId, String keyId) throws IOException {
    // 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 (KeyManagementServiceClient client = KeyManagementServiceClient.create()) {
      // Build the name from the project, location, and key ring.
      CryptoKeyName cryptoKeyName = CryptoKeyName.of(projectId, locationId, keyRingId, keyId);

      // Calculate the date 24 hours from now (this is used below).
      long tomorrow = java.time.Instant.now().plus(24, ChronoUnit.HOURS).getEpochSecond();

      // Build the key to update with a rotation schedule.
      CryptoKey key =
          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.
      FieldMask fieldMask = FieldMaskUtil.fromString("rotation_period,next_rotation_time");

      // Update the key.
      CryptoKey updatedKey = client.updateCryptoKey(key, fieldMask);
      System.out.printf("Updated key %s%n", updatedKey.getName());
    }
  }
}

Node.js

Um diesen Code auszuführen, richten Sie zuerst eine Node.js-Entwicklungsumgebung ein und installieren Sie das 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 library
const {KeyManagementServiceClient} = require('@google-cloud/kms');

// Instantiates a client
const client = new KeyManagementServiceClient();

// Build the key name
const keyName = client.cryptoKeyPath(projectId, locationId, keyRingId, keyId);

async function updateKeyAddRotation() {
  const [key] = await client.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: new Date().getTime() / 1000 + 60 * 60 * 24,
      },
    },
    updateMask: {
      paths: ['rotation_period', 'next_rotation_time'],
    },
  });

  console.log(`Updated rotation for: ${key.name}`);
  return key;
}

return updateKeyAddRotation();

PHP

Um diesen Code auszuführen, müssen Sie zuerst PHP in Google Cloud verwenden lernen und das Cloud KMS PHP SDK installieren.

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

Um diesen Code auszuführen, müssen Sie zuerst eine Python-Entwicklungsumgebung einrichten und das Cloud KMS Python SDK installieren.

import time

from google.cloud import kms

def update_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}")
    return updated_key

Ruby

Um diesen Code auszuführen, müssen Sie zuerst eine Ruby-Entwicklungsumgebung einrichten und das Cloud KMS Ruby SDK installieren.

# 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_path project:    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_key crypto_key: key, update_mask: update_mask
puts "Updated key: #{updated_key.name}"

API

In diesen Beispielen wird curl als HTTP-Client verwendet, um die Verwendung der API zu demonstrieren. Weitere Informationen zur Zugriffssteuerung finden Sie unter Auf die Cloud KMS API zugreifen.

Verwenden Sie die Methode CryptoKey.patch, um einen Schlüssel zu aktualisieren:

curl "https://cloudkms.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/keyRings/KEY_RING/cryptoKeys/KEY_NAME?updateMask=rotationPeriod,nextRotationTime" \
    --request "PATCH" \
    --header "authorization: Bearer TOKEN" \
    --header "content-type: application/json" \
    --data '{"rotationPeriod": "ROTATION_PERIOD", "nextRotationTime": "NEXT_ROTATION_TIME"}'

Ersetzen Sie Folgendes:

  • ROTATION_PERIOD: Das Intervall, in dem der Schlüssel rotiert wird, z. B. 30d, damit der Schlüssel alle 30 Tage rotiert wird. Der Rotationszeitraum muss mindestens 1 Tag und darf höchstens 100 Jahre betragen. Weitere Informationen finden Sie unter CryptoKey.rotationPeriod.
  • NEXT_ROTATION_TIME: der Zeitstempel, zu dem die erste Rotation abgeschlossen werden soll, z. B. "2023-01-01T01:02:03". Sie können --next-rotation-time weglassen, um die erste Rotation 7 Tage nach Ausführung des Befehls zu planen. Weitere Informationen finden Sie unter CryptoKey.nextRotationTime.

Schlüssel manuell rotieren

Erstellen Sie zuerst eine neue Schlüsselversion:

Console

  1. Rufen Sie in der Google Cloud Console die Seite Schlüsselverwaltung auf.

    Zur Seite „Schlüsselverwaltung“

  2. Klicken Sie auf den Namen des Schlüsselbunds, der den Schlüssel enthält, für den Sie eine neue Schlüsselversion erstellen möchten.

  3. Klicken Sie auf den Schlüssel, für den Sie eine neue Schlüsselversion erstellen möchten.

  4. Klicken Sie in der Kopfzeile auf Rotieren.

  5. Klicken Sie in der Eingabeaufforderung zur Bestätigung auf Rotieren.

gcloud

Wenn Sie Cloud KMS in der Befehlszeile verwenden möchten, müssen Sie zuerst die neueste Version der Google Cloud CLI installieren oder ein Upgrade auf die neueste Version durchführen.

gcloud kms keys versions create \
    --key KEY_NAME \
    --keyring KEY_RING \
    --location LOCATION

Ersetzen Sie Folgendes:

  • KEY_NAME: Der Name des Schlüssels.
  • KEY_RING: der Name des Schlüsselbunds, der den Schlüssel enthält.
  • LOCATION: der Cloud KMS-Speicherort des Schlüsselbunds.

Schlüsselversionen werden sequenziell nummeriert.

Wenn Sie Informationen zu allen Flags und möglichen Werten erhalten möchten, führen Sie den Befehl mit dem Flag --help aus.

C#

Um diesen Code auszuführen, müssen Sie zuerst eine C#-Entwicklungsumgebung einrichten und das Cloud KMS C# SDK installieren.


using Google.Cloud.Kms.V1;

public class CreateKeyVersionSample
{
    public CryptoKeyVersion CreateKeyVersion(string projectId = "my-project", string locationId = "us-east1", string keyRingId = "my-key-ring", string keyId = "my-key")
    {
        // Create the client.
        KeyManagementServiceClient client = KeyManagementServiceClient.Create();

        // Build the parent key name.
        CryptoKeyName keyName = new CryptoKeyName(projectId, locationId, keyRingId, keyId);

        // Build the key version.
        CryptoKeyVersion keyVersion = new CryptoKeyVersion { };

        // Call the API.
        CryptoKeyVersion result = client.CreateCryptoKeyVersion(keyName, keyVersion);

        // Return the result.
        return result;
    }
}

Go

Um diesen Code auszuführen, müssen Sie zuerst eine Go-Entwicklungsumgebung einrichten und das Cloud KMS Go SDK installieren.

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.
func createKeyVersion(w io.Writer, parent string) 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)
	if err != nil {
		return fmt.Errorf("failed to create kms client: %w", err)
	}
	defer client.Close()

	// Build the request.
	req := &kmspb.CreateCryptoKeyVersionRequest{
		Parent: parent,
	}

	// Call the API.
	result, err := client.CreateCryptoKeyVersion(ctx, req)
	if err != nil {
		return fmt.Errorf("failed to create key version: %w", err)
	}
	fmt.Fprintf(w, "Created key version: %s\n", result.Name)
	return nil
}

Java

Um diesen Code auszuführen, müssen Sie zuerst eine Java-Entwicklungsumgebung einrichten und das Cloud KMS Java SDK installieren.

import com.google.cloud.kms.v1.CryptoKeyName;
import com.google.cloud.kms.v1.CryptoKeyVersion;
import com.google.cloud.kms.v1.KeyManagementServiceClient;
import java.io.IOException;

public class CreateKeyVersion {

  public void createKeyVersion() throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "your-project-id";
    String locationId = "us-east1";
    String keyRingId = "my-key-ring";
    String keyId = "my-key";
    createKeyVersion(projectId, locationId, keyRingId, keyId);
  }

  // Create a new key version.
  public void createKeyVersion(String projectId, String locationId, String keyRingId, String keyId)
      throws IOException {
    // 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 (KeyManagementServiceClient client = KeyManagementServiceClient.create()) {
      // Build the parent name from the project, location, and key ring.
      CryptoKeyName cryptoKeyName = CryptoKeyName.of(projectId, locationId, keyRingId, keyId);

      // Build the key version to create.
      CryptoKeyVersion keyVersion = CryptoKeyVersion.newBuilder().build();

      // Create the key.
      CryptoKeyVersion createdVersion = client.createCryptoKeyVersion(cryptoKeyName, keyVersion);
      System.out.printf("Created key version %s%n", createdVersion.getName());
    }
  }
}

Node.js

Um diesen Code auszuführen, richten Sie zuerst eine Node.js-Entwicklungsumgebung ein und installieren Sie das 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 library
const {KeyManagementServiceClient} = require('@google-cloud/kms');

// Instantiates a client
const client = new KeyManagementServiceClient();

// Build the parent key name
const keyName = client.cryptoKeyPath(projectId, locationId, keyRingId, keyId);

async function createKeyVersion() {
  const [version] = await client.createCryptoKeyVersion({
    parent: keyName,
  });

  console.log(`Created key version: ${version.name}`);
  return version;
}

return createKeyVersion();

PHP

Um diesen Code auszuführen, müssen Sie zuerst PHP in Google Cloud verwenden lernen und das Cloud KMS PHP SDK installieren.

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

Um diesen Code auszuführen, müssen Sie zuerst eine Python-Entwicklungsumgebung einrichten und das Cloud KMS Python SDK installieren.

from google.cloud import kms

def create_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}")
    return created_version

Ruby

Um diesen Code auszuführen, müssen Sie zuerst eine Ruby-Entwicklungsumgebung einrichten und das Cloud KMS Ruby SDK installieren.

# 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_path project:    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_version parent: key_name, crypto_key_version: version
puts "Created key version: #{created_version.name}"

API

In diesen Beispielen wird curl als HTTP-Client verwendet, um die Verwendung der API zu demonstrieren. Weitere Informationen zur Zugriffssteuerung finden Sie unter Auf die Cloud KMS API zugreifen.

Wenn Sie einen Schlüssel manuell rotieren möchten, erstellen Sie zuerst eine neue Schlüsselversion. Rufen Sie dazu die Methode CryptoKeyVersions.create auf.

curl "https://cloudkms.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/keyRings/KEY_RING/cryptoKeys/KEY_NAME/cryptoKeyVersions" \
    --request "POST" \
    --header "authorization: Bearer TOKEN"

Mit diesem Befehl wird eine neue Schlüsselversion erstellt, aber nicht als primäre Version festgelegt.

Informationen zum Festlegen Ihrer neuen Schlüsselversion als primäre Schlüsselversion finden Sie unter Vorhandene Version als Primärschlüsselversion festlegen.

Falls erforderlich, verschlüsseln Sie Daten neu, die mit der vorherigen Schlüsselversion verschlüsselt wurden.

Vorhandene Version als Primärschlüsselversion festlegen

Wenn Sie eine andere Schlüsselversion als primäre Version für einen Schlüssel festlegen möchten, aktualisieren Sie den Schlüssel mit den neuen primären Versionsinformationen. Eine Schlüsselversion muss aktiviert sein, bevor Sie sie als primäre Version konfigurieren können.

Console

  1. Rufen Sie in der Google Cloud Console die Seite Schlüsselverwaltung auf.

    Zur Seite „Schlüsselverwaltung“

  2. Klicken Sie auf den Namen des Schlüsselbunds, der den Schlüssel enthält, dessen primäre Version Sie aktualisieren möchten.

  3. Klicken Sie auf den Schlüssel, dessen primäre Version Sie aktualisieren möchten.

  4. Klicken Sie in der Zeile für die Schlüsselversion, die Sie als primäre Version festlegen möchten, auf Mehr anzeigen .

  5. Klicken Sie im Menü auf Als primäre Version festlegen.

  6. Klicken Sie in der Bestätigungsaufforderung auf Als primäre E-Mail-Adresse festlegen.

gcloud

Wenn Sie Cloud KMS in der Befehlszeile verwenden möchten, müssen Sie zuerst die neueste Version der Google Cloud CLI installieren oder ein Upgrade auf die neueste Version durchführen.

gcloud kms keys update KEY_NAME \
    --keyring KEY_RING \
    --location LOCATION \
    --primary-version KEY_VERSION

Ersetzen Sie Folgendes:

  • KEY_NAME: Der Name des Schlüssels.
  • KEY_RING: der Name des Schlüsselbunds, der den Schlüssel enthält.
  • LOCATION: der Cloud KMS-Speicherort des Schlüsselbunds.
  • KEY_VERSION: die Versionsnummer der neuen Primärschlüsselversion.

Wenn Sie Informationen zu allen Flags und möglichen Werten erhalten möchten, führen Sie den Befehl mit dem Flag --help aus.

C#

Um diesen Code auszuführen, müssen Sie zuerst eine C#-Entwicklungsumgebung einrichten und das Cloud KMS C# SDK installieren.


using Google.Cloud.Kms.V1;

public class UpdateKeySetPrimarySample
{
    public CryptoKey UpdateKeySetPrimary(
      string projectId = "my-project", string locationId = "us-east1", string keyRingId = "my-key-ring", string keyId = "my-key",
      string keyVersionId = "123")
    {
        // Create the client.
        KeyManagementServiceClient client = KeyManagementServiceClient.Create();

        // Build the key name.
        CryptoKeyName keyName = new CryptoKeyName(projectId, locationId, keyRingId, keyId);

        // Call the API.
        CryptoKey result = client.UpdateCryptoKeyPrimaryVersion(keyName, keyVersionId);

        // Return the updated key.
        return result;
    }
}

Go

Um diesen Code auszuführen, müssen Sie zuerst eine Go-Entwicklungsumgebung einrichten und das Cloud KMS Go SDK installieren.

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.
func updateKeySetPrimary(w io.Writer, name, version string) 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)
	if err != nil {
		return fmt.Errorf("failed to create kms client: %w", err)
	}
	defer client.Close()

	// Build the request.
	req := &kmspb.UpdateCryptoKeyPrimaryVersionRequest{
		Name:               name,
		CryptoKeyVersionId: version,
	}

	// Call the API.
	result, err := client.UpdateCryptoKeyPrimaryVersion(ctx, req)
	if err != nil {
		return fmt.Errorf("failed to update key: %w", err)
	}
	fmt.Fprintf(w, "Updated key primary: %s\n", result.Name)

	return nil
}

Java

Um diesen Code auszuführen, müssen Sie zuerst eine Java-Entwicklungsumgebung einrichten und das Cloud KMS Java SDK installieren.

import com.google.cloud.kms.v1.CryptoKey;
import com.google.cloud.kms.v1.CryptoKeyName;
import com.google.cloud.kms.v1.KeyManagementServiceClient;
import java.io.IOException;

public class UpdateKeySetPrimary {

  public void updateKeySetPrimary() throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "your-project-id";
    String locationId = "us-east1";
    String keyRingId = "my-key-ring";
    String keyId = "my-key";
    String keyVersionId = "123";
    updateKeySetPrimary(projectId, locationId, keyRingId, keyId, keyVersionId);
  }

  // Update a key's primary version.
  public void updateKeySetPrimary(
      String projectId, String locationId, String keyRingId, String keyId, String keyVersionId)
      throws IOException {
    // 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 (KeyManagementServiceClient client = KeyManagementServiceClient.create()) {
      // Build the name from the project, location, key ring, and keyId.
      CryptoKeyName cryptoKeyName = CryptoKeyName.of(projectId, locationId, keyRingId, keyId);

      // Create the key.
      CryptoKey createdKey = client.updateCryptoKeyPrimaryVersion(cryptoKeyName, keyVersionId);
      System.out.printf("Updated key primary version %s%n", createdKey.getName());
    }
  }
}

Node.js

Um diesen Code auszuführen, richten Sie zuerst eine Node.js-Entwicklungsumgebung ein und installieren Sie das 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 library
const {KeyManagementServiceClient} = require('@google-cloud/kms');

// Instantiates a client
const client = new KeyManagementServiceClient();

// Build the key name
const keyName = client.cryptoKeyPath(projectId, locationId, keyRingId, keyId);

async function updateKeySetPrimary() {
  const [key] = await client.updateCryptoKeyPrimaryVersion({
    name: keyName,
    cryptoKeyVersionId: versionId,
  });

  console.log(`Set primary to ${versionId}`);
  return key;
}

return updateKeySetPrimary();

PHP

Um diesen Code auszuführen, müssen Sie zuerst PHP in Google Cloud verwenden lernen und das Cloud KMS PHP SDK installieren.

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

Um diesen Code auszuführen, müssen Sie zuerst eine Ruby-Entwicklungsumgebung einrichten und das Cloud KMS Ruby SDK installieren.

# 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_path project:    project_id,
                                  location:   location_id,
                                  key_ring:   key_ring_id,
                                  crypto_key: key_id

# Call the API.
updated_key = client.update_crypto_key_primary_version name: key_name, crypto_key_version_id: version_id
puts "Updated primary #{updated_key.name} to #{version_id}"

Python

Um diesen Code auszuführen, müssen Sie zuerst eine Python-Entwicklungsumgebung einrichten und das Cloud KMS Python SDK installieren.

from google.cloud import kms

def update_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}")
    return updated_key

API

In diesen Beispielen wird curl als HTTP-Client verwendet, um die Verwendung der API zu demonstrieren. Weitere Informationen zur Zugriffssteuerung finden Sie unter Auf die Cloud KMS API zugreifen.

Rufen Sie die Methode CryptoKey.updatePrimaryVersion auf, um die Primärschlüsselversion zu ändern.

curl "https://cloudkms.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/keyRings/KEY_RING/cryptoKeys/KEY_NAME:updatePrimaryVersion" \
    --request "POST" \
    --header "authorization: Bearer TOKEN" \
    --header "content-type: application/json" \
    --data '{"cryptoKeyVersionId": "KEY_VERSION"}'

Ersetzen Sie Folgendes:

  • PROJECT_ID: die ID des Projekts, das den Schlüsselbund enthält.
  • LOCATION: der Cloud KMS-Speicherort des Schlüsselbunds.
  • KEY_RING: der Name des Schlüsselbunds, der den Schlüssel enthält.
  • KEY_NAME: Der Name des Schlüssels.
  • KEY_VERSION: die Versionsnummer der neuen Primärschlüsselversion.

Wenn Sie die Primärschlüsselversion ändern, wird die Änderung in der Regel innerhalb von einer Minute konsistent. Es kann jedoch in Ausnahmefällen bis zu 3 Stunden dauern, bis diese Änderung wirksam wird. Während dieser Zeit wird möglicherweise die vorherige Primärversion zum Verschlüsseln von Daten verwendet. Weitere Informationen finden Sie unter Konsistenz von Cloud KMS-Ressourcen.

Automatische Rotation deaktivieren

Löschen Sie den Rotationsplan des Schlüssels, um die automatische Rotation für einen Schlüssel zu deaktivieren:

Console

  1. Rufen Sie in der Google Cloud Console die Seite Schlüsselverwaltung auf.

    Zur Seite „Schlüsselverwaltung“

  2. Klicken Sie auf den Namen des Schlüsselbunds, der den Schlüssel enthält, für den Sie den Rotationsplan entfernen möchten.

  3. Klicken Sie auf den Schlüssel, von dem Sie den Rotationsplan entfernen möchten.

  4. Klicken Sie in der Kopfzeile auf Rotationszeitraum bearbeiten.

  5. Klicken Sie in der Eingabeaufforderung auf das Feld Rotationszeitraum und wählen Sie Nie (manuelle Rotation) aus.

  6. Klicken Sie in der Eingabeaufforderung auf Speichern.

gcloud

Wenn Sie Cloud KMS in der Befehlszeile verwenden möchten, müssen Sie zuerst die neueste Version der Google Cloud CLI installieren oder ein Upgrade auf die neueste Version durchführen.

gcloud kms keys update KEY_NAME \
    --keyring KEY_RING \
    --location LOCATION \
    --remove-rotation-schedule

Ersetzen Sie Folgendes:

  • KEY_NAME: Der Name des Schlüssels.
  • KEY_RING: der Name des Schlüsselbunds, der den Schlüssel enthält.
  • LOCATION: der Cloud KMS-Speicherort des Schlüsselbunds.

Wenn Sie Informationen zu allen Flags und möglichen Werten erhalten möchten, führen Sie den Befehl mit dem Flag --help aus.

C#

Um diesen Code auszuführen, müssen Sie zuerst eine C#-Entwicklungsumgebung einrichten und das Cloud KMS C# SDK installieren.


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

public class UpdateKeyRemoveRotationSample
{
    public CryptoKey UpdateKeyRemoveRotation(string projectId = "my-project", string locationId = "us-east1", string keyRingId = "my-key-ring", string keyId = "my-key")
    {
        // Create the client.
        KeyManagementServiceClient client = KeyManagementServiceClient.Create();

        // Build the key.
        CryptoKey key = new CryptoKey
        {
            CryptoKeyName = new CryptoKeyName(projectId, locationId, keyRingId, keyId),
            RotationPeriod = null,
            NextRotationTime = null,
        };

        // Build the update mask.
        FieldMask fieldMask = new FieldMask
        {
            Paths = { "rotation_period", "next_rotation_time" },
        };

        // Call the API.
        CryptoKey result = client.UpdateCryptoKey(key, fieldMask);

        // Return the updated key.
        return result;
    }
}

Go

Um diesen Code auszuführen, müssen Sie zuerst eine Go-Entwicklungsumgebung einrichten und das Cloud KMS Go SDK installieren.

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.
func removeRotationSchedule(w io.Writer, name string) 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)
	if err != nil {
		return fmt.Errorf("failed to create kms client: %w", err)
	}
	defer client.Close()

	// Build the request.
	req := &kmspb.UpdateCryptoKeyRequest{
		CryptoKey: &kmspb.CryptoKey{
			// Provide the name of the key to update
			Name: 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)
	if err != nil {
		return fmt.Errorf("failed to update key: %w", err)
	}
	fmt.Fprintf(w, "Updated key: %s\n", result.Name)
	return nil
}

Java

Um diesen Code auszuführen, müssen Sie zuerst eine Java-Entwicklungsumgebung einrichten und das Cloud KMS Java SDK installieren.

import com.google.cloud.kms.v1.CryptoKey;
import com.google.cloud.kms.v1.CryptoKeyName;
import com.google.cloud.kms.v1.KeyManagementServiceClient;
import com.google.protobuf.FieldMask;
import com.google.protobuf.util.FieldMaskUtil;
import java.io.IOException;

public class UpdateKeyRemoveRotation {

  public void updateKeyRemoveRotation() throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "your-project-id";
    String locationId = "us-east1";
    String keyRingId = "my-key-ring";
    String keyId = "my-key";
    updateKeyRemoveRotation(projectId, locationId, keyRingId, keyId);
  }

  // Update a key to remove all labels.
  public void updateKeyRemoveRotation(
      String projectId, String locationId, String keyRingId, String keyId) throws IOException {
    // 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 (KeyManagementServiceClient client = KeyManagementServiceClient.create()) {
      // Build the name from the project, location, key ring, and keyId.
      CryptoKeyName cryptoKeyName = CryptoKeyName.of(projectId, locationId, keyRingId, keyId);

      // Build an empty key with no labels.
      CryptoKey key =
          CryptoKey.newBuilder()
              .setName(cryptoKeyName.toString())
              .clearRotationPeriod()
              .clearNextRotationTime()
              .build();

      // Construct the field mask.
      FieldMask fieldMask = FieldMaskUtil.fromString("rotation_period,next_rotation_time");

      // Create the key.
      CryptoKey createdKey = client.updateCryptoKey(key, fieldMask);
      System.out.printf("Updated key %s%n", createdKey.getName());
    }
  }
}

Node.js

Um diesen Code auszuführen, richten Sie zuerst eine Node.js-Entwicklungsumgebung ein und installieren Sie das 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 library
const {KeyManagementServiceClient} = require('@google-cloud/kms');

// Instantiates a client
const client = new KeyManagementServiceClient();

// Build the key name
const keyName = client.cryptoKeyPath(projectId, locationId, keyRingId, keyId);

async function updateKeyRemoveRotation() {
  const [key] = await client.updateCryptoKey({
    cryptoKey: {
      name: keyName,
      rotationPeriod: null,
      nextRotationTime: null,
    },
    updateMask: {
      paths: ['rotation_period', 'next_rotation_time'],
    },
  });

  console.log(`Removed rotation for: ${key.name}`);
  return key;
}

return updateKeyRemoveRotation();

PHP

Um diesen Code auszuführen, müssen Sie zuerst PHP in Google Cloud verwenden lernen und das Cloud KMS PHP SDK installieren.

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

Um diesen Code auszuführen, müssen Sie zuerst eine Ruby-Entwicklungsumgebung einrichten und das Cloud KMS Ruby SDK installieren.

# 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_path project:    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_key crypto_key: key, update_mask: update_mask
puts "Updated key: #{updated_key.name}"

Python

Um diesen Code auszuführen, müssen Sie zuerst eine Python-Entwicklungsumgebung einrichten und das Cloud KMS Python SDK installieren.

from google.cloud import kms

def update_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}")
    return updated_key

API

In diesen Beispielen wird curl als HTTP-Client verwendet, um die Verwendung der API zu demonstrieren. Weitere Informationen zur Zugriffssteuerung finden Sie unter Auf die Cloud KMS API zugreifen.

Verwenden Sie die Methode CryptoKey.patch, um einen Schlüssel zu aktualisieren:

curl "https://cloudkms.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/keyRings/KEY_RING/cryptoKeys/KEY_NAME?updateMask=rotationPeriod,nextRotationTime" \
    --request "PATCH" \
    --header "authorization: Bearer TOKEN" \
    --header "content-type: application/json" \
    --data '{"rotationPeriod": null, "nextRotationTime": null}'

Weitere Informationen zu rotationPeriod und nextRotationTime findest du unter keyRings.cryptoKeys.

Externen Schlüssel rotieren

Koordinierten externen Schlüssel rotieren

Sie können die automatische Rotation für symmetrische koordinierte externe Schlüssel konfigurieren. Sie können auch manuell eine neue Schlüsselversion für symmetrische oder asymmetrische koordinierte externe Schlüssel erstellen.

Durch Rotieren oder Erstellen einer neuen Schlüsselversion werden alle neu erstellten Daten, die mit diesem Schlüssel geschützt sind, mit der neuen Schlüsselversion verschlüsselt. Daten, die mit einer vorherigen Schlüsselversion geschützt sind, werden nicht neu verschlüsselt. Daher muss Ihr externes Schlüsselverwaltungssystem weiterhin das Schlüsselmaterial der vorherigen Schlüsselversion zur Verfügung stellen.

Führen Sie die folgenden Schritte aus, um eine neue Schlüsselversion für einen koordinierten externen Schlüssel zu erstellen:

Console

  1. Rufen Sie in der Google Cloud Console die Seite Schlüsselverwaltung auf.

    Key Management aufrufen

  2. Wählen Sie den Schlüsselbund und dann den Schlüssel aus.

  3. Klicken Sie auf Create version (Version erstellen). Eine Nachricht zeigt an, dass Ihre neue Schlüsselversion sowohl in Cloud KMS als auch in EKM generiert wird. Wenn Sie das Feld Schlüsselpfad oder Schlüssel-URI sehen, ist der ausgewählte Schlüssel kein koordinierter externer Schlüssel.

  4. Klicken Sie auf Version erstellen, um zu bestätigen, dass Sie eine neue Schlüsselversion erstellen möchten.

Die neue Schlüsselversion wird im Status Generierung ausstehend angezeigt. Bei symmetrischen Schlüsseln werden manuell erstellte Schlüsselversionen nicht automatisch als Primärschlüsselversion festgelegt. Sie können die neue Schlüsselversion als primäre Version festlegen.

gcloud-CLI

Verwenden Sie den Befehl kms keys versions create mit dem Flag --primary, um eine neue symmetrische Schlüsselversion zu erstellen und als Primärschlüsselversion festzulegen:

gcloud kms keys versions create \
  --key KEY_NAME \
  --keyring KEY_RING \
  --location LOCATION \
  --primary

Ersetzen Sie Folgendes:

  • KEY_NAME: Der Name des Schlüssels.
  • KEY_RING: der Name des Schlüsselbunds, der den Schlüssel enthält.
  • LOCATION: der Cloud KMS-Speicherort des Schlüsselbunds.

Verwenden Sie den Befehl kms keys versions create, um eine neue asymmetrische Schlüsselversion oder eine neue symmetrische Schlüsselversion zu erstellen, die nicht die Primärschlüsselversion ist:

gcloud kms keys versions create \
  --key KEY_NAME \
  --keyring KEY_RING \
  --location LOCATION

Ersetzen Sie Folgendes:

  • KEY_NAME: Der Name des Schlüssels.
  • KEY_RING: der Name des Schlüsselbunds, der den Schlüssel enthält.
  • LOCATION: der Cloud KMS-Speicherort des Schlüsselbunds.

Manuell verwalteten Cloud EKM über VPC-Schlüssel rotieren

Rotieren Sie zuerst das externe Schlüsselmaterial in Ihrem External Key Manager. Wenn dies zu einem neuen Schlüsselpfad führt, müssen Sie eine Cloud EKM-Schlüsselversion rotieren oder eine neue mit dem neuen Schlüsselpfad erstellen. Bei symmetrischen Verschlüsselungsschlüsseln rotieren Sie den Cloud EKM-Schlüssel und geben Sie den neuen Schlüsselpfad aus Ihrem External Key Manager an. Für asymmetrische Schlüssel erstellen Sie eine neue Schlüsselversion und geben den neuen Schlüsselpfad an.

Durch Rotieren oder Erstellen einer neuen Schlüsselversion werden alle neu erstellten Daten, die mit diesem Schlüssel geschützt sind, mit der neuen Schlüsselversion verschlüsselt. Daten, die mit einer vorherigen Schlüsselversion geschützt sind, werden nicht neu verschlüsselt. Daher muss Ihr externes Schlüsselverwaltungssystem weiterhin das Schlüsselmaterial der vorherigen Schlüsselversion zur Verfügung stellen.

Wenn sich das Schlüsselmaterial im Partnersystem für die externe Schlüsselverwaltung nicht ändert, sich aber der Schlüsselpfad ändert, können Sie den externen Pfad des Schlüssels aktualisieren, ohne den Schlüssel zu rotieren.

Console

  1. Rufen Sie in der Google Cloud Console die Seite Schlüsselverwaltung auf.

    Key Management aufrufen

  2. Wählen Sie den Schlüsselbund und dann den Schlüssel aus.

  3. Klicken Sie auf Schlüssel rotieren.

  4. Geben Sie unter Schlüsselpfad den Schlüsselpfad für die neue Version ein.

  5. Klicken Sie zum Bestätigen auf Schlüssel rotieren.

gcloud

Wenn Sie Cloud KMS in der Befehlszeile verwenden möchten, müssen Sie zuerst die neueste Version der Google Cloud CLI installieren oder ein Upgrade auf die neueste Version durchführen.

Verwenden Sie den Befehl kms keys versions create mit dem Flag --primary, um eine neue symmetrische Schlüsselversion zu erstellen und als Primärschlüsselversion festzulegen:

gcloud kms keys versions create \
    --key KEY_NAME \
    --keyring KEY_RING \
    --location LOCATION \
    --ekm-connection-key-path EXTERNAL_KEY_PATH \
    --primary

Ersetzen Sie Folgendes:

  • KEY_NAME: Der Name des Schlüssels.
  • KEY_RING: der Name des Schlüsselbunds, der den Schlüssel enthält.
  • LOCATION: der Cloud KMS-Speicherort des Schlüsselbunds.
  • EXTERNAL_KEY_PATH: der Pfad zur neuen externen Schlüsselversion.

Verwenden Sie den Befehl kms keys versions create, um eine neue asymmetrische Schlüsselversion oder eine neue symmetrische Schlüsselversion zu erstellen, die nicht die Primärschlüsselversion ist:

gcloud kms keys versions create \
    --key KEY_NAME \
    --keyring KEY_RING \
    --location LOCATION \
    --ekm-connection-key-path EXTERNAL_KEY_PATH

Ersetzen Sie Folgendes:

  • KEY_NAME: Der Name des Schlüssels.
  • KEY_RING: der Name des Schlüsselbunds, der den Schlüssel enthält.
  • LOCATION: der Cloud KMS-Speicherort des Schlüsselbunds.
  • EXTERNAL_KEY_PATH: der Pfad zur neuen externen Schlüsselversion.

Wenn Sie Informationen zu allen Flags und möglichen Werten erhalten möchten, führen Sie den Befehl mit dem Flag --help aus.

Nachdem die Schlüsselversion erstellt wurde, können Sie sie wie jede andere Cloud KMS-Schlüsselversion verwenden.

Manuell verwalteten Cloud EKM über einen Internetschlüssel rotieren

Rotieren Sie zuerst das externe Schlüsselmaterial in Ihrem External Key Manager. Wenn dies zu einem neuen URI führt, müssen Sie eine neue Cloud EKM-Schlüsselversion mit dem neuen URI erstellen oder rotieren. Bei symmetrischen Verschlüsselungsschlüsseln rotieren Sie den Cloud EKM-Schlüssel und geben Sie den neuen Schlüssel-URI aus Ihrem External Key Manager an. Für asymmetrische Schlüssel erstellen Sie eine neue Schlüsselversion und geben den neuen Schlüssel-URI an.

Durch Rotieren oder Erstellen einer neuen Schlüsselversion werden alle neu erstellten Daten, die mit diesem Schlüssel geschützt sind, mit der neuen Schlüsselversion verschlüsselt. Daten, die mit einer vorherigen Schlüsselversion geschützt sind, werden nicht neu verschlüsselt. Daher muss Ihr externes Schlüsselverwaltungssystem weiterhin das Schlüsselmaterial der vorherigen Schlüsselversion zur Verfügung stellen.

Wenn sich das Schlüsselmaterial im Partnersystem für die externe Schlüsselverwaltung nicht ändert, aber der URI ändert, können Sie den externen URI des Schlüssels aktualisieren, ohne den Schlüssel zu rotieren.

Console

  1. Rufen Sie in der Google Cloud Console die Seite Schlüsselverwaltung auf.

    Key Management aufrufen

  2. Wählen Sie den Schlüsselbund und dann den Schlüssel aus.

  3. Wählen Sie Schlüssel rotieren für symmetrische Schlüssel oder Version erstellen für asymmetrische Schlüssel aus.

  4. Geben Sie den neuen Schlüssel-URI ein und wählen Sie dann Schlüssel rotieren für symmetrische Schlüssel oder Version erstellen für asymmetrische Schlüssel aus.

Die neue Schlüsselversion wird die Hauptversion.

gcloud-CLI

Verwenden Sie den Befehl kms keys versions create mit dem Flag --primary, um eine neue symmetrische Schlüsselversion zu erstellen und als Primärschlüsselversion festzulegen:

gcloud kms keys versions create \
  --key KEY_NAME \
  --keyring KEY_RING \
  --location LOCATION \
  --external-key-uri EXTERNAL_KEY_URI \
  --primary

Ersetzen Sie Folgendes:

  • KEY_NAME: Der Name des Schlüssels.
  • KEY_RING: der Name des Schlüsselbunds, der den Schlüssel enthält.
  • LOCATION: der Cloud KMS-Speicherort des Schlüsselbunds.
  • EXTERNAL_KEY_URI: der Schlüssel-URI der neuen externen Schlüsselversion.

Verwenden Sie den Befehl kms keys versions create, um eine neue asymmetrische Schlüsselversion oder eine neue symmetrische Schlüsselversion zu erstellen, die nicht die Primärschlüsselversion ist:

gcloud kms keys versions create \
  --key KEY_NAME \
  --keyring KEY_RING \
  --location LOCATION \
  --external-key-uri EXTERNAL_KEY_URI

Ersetzen Sie Folgendes:

  • KEY_NAME: Der Name des Schlüssels.
  • KEY_RING: der Name des Schlüsselbunds, der den Schlüssel enthält.
  • LOCATION: der Cloud KMS-Speicherort des Schlüsselbunds.
  • EXTERNAL_KEY_URI: der Schlüssel-URI der neuen externen Schlüsselversion.