Schlüssel erstellen

Auf dieser Seite wird beschrieben, wie Sie einen Schlüssel in Cloud KMS erstellen. Ein Schlüssel kann ein symmetrischer oder asymmetrischer Verschlüsselungsschlüssel, ein asymmetrischer Signaturschlüssel oder ein MAC-Signaturschlüssel sein.

Wenn Sie einen Schlüssel erstellen, fügen Sie ihn einem Schlüsselbund an einem bestimmten Cloud KMS-Standort hinzu. Sie können einen neuen Schlüsselbund erstellen oder einen vorhandenen verwenden. Auf dieser Seite generieren Sie einen neuen Cloud KMS- oder Cloud HSM-Schlüssel und fügen ihn einem vorhandenen Schlüsselbund hinzu. Informationen zum Erstellen eines Cloud EKM-Schlüssels finden Sie unter Externen Schlüssel erstellen. Informationen zum Importieren eines Cloud KMS- oder Cloud HSM-Schlüssels finden Sie unter Schlüssel importieren.

Hinweise

Bevor Sie die Aufgaben auf dieser Seite ausführen, benötigen Sie Folgendes:

  1. Eine Google Cloud Projektressource für Ihre Cloud KMS-Ressourcen. Wir empfehlen, ein separates Projekt für Ihre Cloud KMS-Ressourcen zu verwenden, das keine anderen Google Cloud -Ressourcen enthält.
  2. Der Name und der Speicherort des Schlüsselbunds, in dem Sie den Schlüssel erstellen möchten. Wählen Sie einen Schlüsselbund an einem Ort aus, der sich in der Nähe Ihrer anderen Ressourcen befindet und das von Ihnen gewählte Schutzniveau unterstützt. Informationen zu verfügbaren Standorten und den von ihnen unterstützten Schutzstufen finden Sie unter Cloud KMS-Standorte. Informationen zum Erstellen eines Schlüsselbunds finden Sie unter Schlüsselbund erstellen.
  3. Optional: Wenn Sie die gcloud CLI verwenden möchten, bereiten Sie Ihre Umgebung vor.

    In the Google Cloud console, activate Cloud Shell.

    Activate Cloud Shell

    Erforderliche Rollen

    Bitten Sie Ihren Administrator, Ihnen die IAM-Rolle Cloud KMS-Administrator (roles/cloudkms.admin) für das Projekt oder eine übergeordnete Ressource zuzuweisen, um die Berechtigungen zu erhalten, die Sie zum Erstellen von Schlüsseln benötigen. Weitere Informationen zum Zuweisen von Rollen finden Sie unter Zugriff auf Projekte, Ordner und Organisationen verwalten.

    Diese vordefinierte Rolle enthält die Berechtigungen, die zum Erstellen von Schlüsseln erforderlich sind. Erweitern Sie den Abschnitt Erforderliche Berechtigungen, um die erforderlichen Berechtigungen anzuzeigen:

    Erforderliche Berechtigungen

    Die folgenden Berechtigungen sind zum Erstellen von Schlüsseln erforderlich:

    • cloudkms.cryptoKeys.create
    • cloudkms.cryptoKeys.get
    • cloudkms.cryptoKeys.list
    • cloudkms.cryptoKeyVersions.create
    • cloudkms.cryptoKeyVersions.get
    • cloudkms.cryptoKeyVersions.list
    • cloudkms.keyRings.get
    • cloudkms.keyRings.list
    • cloudkms.locations.get
    • cloudkms.locations.list
    • resourcemanager.projects.get
    • So rufen Sie einen öffentlichen Schlüssel ab: cloudkms.cryptoKeyVersions.viewPublicKey

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

    Symmetrischen Verschlüsselungsschlüssel erstellen

    Konsole

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

      Key Management aufrufen

    2. Klicken Sie auf den Namen des Schlüsselbunds, für den Sie einen Schlüssel erstellen.

    3. Klicken Sie auf Schlüssel erstellen.

    4. Geben Sie unter Schlüsselname einen Namen für den Schlüssel ein.

    5. Wählen Sie für Schutzniveau Software oder HSM aus.

    6. Wählen Sie unter Schlüsselmaterial die Option Generierter Schlüssel aus.

    7. Wählen Sie unter Purpose (Zweck) die Option Symmetric encrypt/decrypt aus.

    8. Übernehmen Sie die Standardwerte für Rotationszeitraum und Beginnt am.

    9. Klicken Sie auf Erstellen.

    gcloud

    Wenn Sie Cloud KMS in der Befehlszeile verwenden möchten, müssen Sie zuerst Google Cloud CLI installieren oder ein Upgrade ausführen.

    gcloud kms keys create KEY_NAME \
        --keyring KEY_RING \
        --location LOCATION \
        --purpose "encryption" \
        --protection-level "PROTECTION_LEVEL"
    

    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.
    • PROTECTION_LEVEL: Das Schutzniveau, das für den Schlüssel verwendet werden soll, z. B. software oder hsm. Sie können das Flag --protection-level für software-Schlüssel weglassen.

    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 CreateKeySymmetricEncryptDecryptSample
    {
        public CryptoKey CreateKeySymmetricEncryptDecrypt(
          string projectId = "my-project", string locationId = "us-east1", string keyRingId = "my-key-ring",
          string id = "my-symmetric-encryption-key")
        {
            // 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,
                }
            };
    
            // 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"
    
    	kms "cloud.google.com/go/kms/apiv1"
    	"cloud.google.com/go/kms/apiv1/kmspb"
    )
    
    // createKeySymmetricEncryptDecrypt creates a new symmetric encrypt/decrypt key
    // on Cloud KMS.
    func createKeySymmetricEncryptDecrypt(w io.Writer, parent, id string) error {
    	// parent := "projects/my-project/locations/us-east1/keyRings/my-key-ring"
    	// id := "my-symmetric-encryption-key"
    
    	// Create the client.
    	ctx := context.Background()
    	client, err := kms.NewKeyManagementClient(ctx)
    	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,
    			},
    		},
    	}
    
    	// 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 java.io.IOException;
    
    public class CreateKeySymmetricEncryptDecrypt {
    
      public void createKeySymmetricEncryptDecrypt() 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";
        createKeySymmetricEncryptDecrypt(projectId, locationId, keyRingId, id);
      }
    
      // Create a new key that is used for symmetric encryption and decryption.
      public void createKeySymmetricEncryptDecrypt(
          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);
    
          // Build the symmetric key to create.
          CryptoKey key =
              CryptoKey.newBuilder()
                  .setPurpose(CryptoKeyPurpose.ENCRYPT_DECRYPT)
                  .setVersionTemplate(
                      CryptoKeyVersionTemplate.newBuilder()
                          .setAlgorithm(CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION))
                  .build();
    
          // Create the key.
          CryptoKey createdKey = client.createCryptoKey(keyRingName, id, key);
          System.out.printf("Created symmetric 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 id = 'my-symmetric-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 createKeySymmetricEncryptDecrypt() {
      const [key] = await client.createCryptoKey({
        parent: keyRingName,
        cryptoKeyId: id,
        cryptoKey: {
          purpose: 'ENCRYPT_DECRYPT',
          versionTemplate: {
            algorithm: 'GOOGLE_SYMMETRIC_ENCRYPTION',
          },
        },
      });
    
      console.log(`Created symmetric key: ${key.name}`);
      return key;
    }
    
    return createKeySymmetricEncryptDecrypt();

    PHP

    Um diesen Code auszuführen, müssen Sie zuerst die Informationen zur Verwendung von PHP in Google Cloud lesen 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;
    
    function create_key_symmetric_encrypt_decrypt(
        string $projectId = 'my-project',
        string $locationId = 'us-east1',
        string $keyRingId = 'my-key-ring',
        string $id = 'my-symmetric-key'
    ): CryptoKey {
        // Create the Cloud KMS client.
        $client = new KeyManagementServiceClient();
    
        // Build the parent key ring name.
        $keyRingName = $client->keyRingName($projectId, $locationId, $keyRingId);
    
        // Build the key.
        $key = (new CryptoKey())
            ->setPurpose(CryptoKeyPurpose::ENCRYPT_DECRYPT)
            ->setVersionTemplate((new CryptoKeyVersionTemplate())
                ->setAlgorithm(CryptoKeyVersionAlgorithm::GOOGLE_SYMMETRIC_ENCRYPTION)
            );
    
        // Call the API.
        $createCryptoKeyRequest = (new CreateCryptoKeyRequest())
            ->setParent($keyRingName)
            ->setCryptoKeyId($id)
            ->setCryptoKey($key);
        $createdKey = $client->createCryptoKey($createCryptoKeyRequest);
        printf('Created symmetric key: %s' . PHP_EOL, $createdKey->getName());
    
        return $createdKey;
    }

    Python

    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_symmetric_encrypt_decrypt(
        project_id: str, location_id: str, key_ring_id: str, key_id: str
    ) -> kms.CryptoKey:
        """
        Creates a new symmetric encryption/decryption key in Cloud KMS.
    
        Args:
            project_id (string): Google Cloud project ID (e.g. 'my-project').
            location_id (string): Cloud KMS location (e.g. 'us-east1').
            key_ring_id (string): ID of the Cloud KMS key ring (e.g. 'my-key-ring').
            key_id (string): ID of the key to create (e.g. 'my-symmetric-key').
    
        Returns:
            CryptoKey: Cloud KMS key.
    
        """
    
        # Create the client.
        client = kms.KeyManagementServiceClient()
    
        # Build the parent key ring name.
        key_ring_name = client.key_ring_path(project_id, location_id, key_ring_id)
    
        # Build the key.
        purpose = kms.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT
        algorithm = (
            kms.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION
        )
        key = {
            "purpose": purpose,
            "version_template": {
                "algorithm": algorithm,
            },
        }
    
        # Call the API.
        created_key = client.create_crypto_key(
            request={"parent": key_ring_name, "crypto_key_id": key_id, "crypto_key": key}
        )
        print(f"Created symmetric key: {created_key.name}")
        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-symmetric-key"
    
    # Require the library.
    require "google/cloud/kms"
    
    # Create the client.
    client = Google::Cloud::Kms.key_management_service
    
    # Build the parent key ring name.
    key_ring_name = client.key_ring_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
      }
    }
    
    # Call the API.
    created_key = client.create_crypto_key parent: key_ring_name, crypto_key_id: id, crypto_key: key
    puts "Created symmetric 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": "ENCRYPT_DECRYPT", "versionTemplate": { "protectionLevel": "PROTECTION_LEVEL", "algorithm": "ALGORITHM" }}'
    

    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.
    • PROTECTION_LEVEL: Das Schutzniveau des Schlüssels, z. B. SOFTWARE oder HSM.
    • ALGORITHM: Der HMAC-Signaturalgorithmus, z. B. HMAC_SHA256. Eine Liste aller unterstützten HMAC-Algorithmen finden Sie unter HMAC-Signaturalgorithmen.

    Symmetrischen Verschlüsselungsschlüssel mit benutzerdefinierter automatischer Rotation erstellen

    Wenn Sie einen Schlüssel erstellen, können Sie seinen Rotationszeitraum angeben. Das ist der Zeitraum zwischen der automatischen Erstellung neuer Schlüsselversionen. Sie können auch unabhängig die nächste Rotationszeit angeben, sodass die nächste Rotation früher oder später als ein Rotationszeitraum ab jetzt erfolgt.

    Konsole

    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 Ihres Schlüssels einen anderen Rotationszeitraum und einen anderen Beginn angeben, bevor Sie auf die Schaltfläche Erstellen klicken:

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

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

    gcloud

    Wenn Sie Cloud KMS in der Befehlszeile verwenden möchten, müssen Sie zuerst Google Cloud CLI installieren oder ein Upgrade ausfü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 für die Rotation des Schlüssels, z. B. 30d, um den Schlüssel alle 30 Tage zu rotieren. Der Rotationszeitraum muss mindestens 1 Tag und höchstens 100 Jahre lang sein. 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 für einen Rotationszeitraum ab dem Zeitpunkt zu planen, an dem Sie den Befehl ausführen. 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.